BatteryStats.java revision ab5c0ea43cf457b20ab4267a14b224f39e0511bf
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.os; 18 19import java.io.PrintWriter; 20import java.util.ArrayList; 21import java.util.Collections; 22import java.util.Comparator; 23import java.util.Formatter; 24import java.util.List; 25import java.util.Map; 26 27import android.content.Context; 28import android.content.pm.ApplicationInfo; 29import android.telephony.SignalStrength; 30import android.text.format.DateFormat; 31import android.util.Printer; 32import android.util.SparseArray; 33import android.util.TimeUtils; 34import com.android.internal.os.BatterySipper; 35import com.android.internal.os.BatteryStatsHelper; 36 37/** 38 * A class providing access to battery usage statistics, including information on 39 * wakelocks, processes, packages, and services. All times are represented in microseconds 40 * except where indicated otherwise. 41 * @hide 42 */ 43public abstract class BatteryStats implements Parcelable { 44 45 private static final boolean LOCAL_LOGV = false; 46 47 /** @hide */ 48 public static final String SERVICE_NAME = "batterystats"; 49 50 /** 51 * A constant indicating a partial wake lock timer. 52 */ 53 public static final int WAKE_TYPE_PARTIAL = 0; 54 55 /** 56 * A constant indicating a full wake lock timer. 57 */ 58 public static final int WAKE_TYPE_FULL = 1; 59 60 /** 61 * A constant indicating a window wake lock timer. 62 */ 63 public static final int WAKE_TYPE_WINDOW = 2; 64 65 /** 66 * A constant indicating a sensor timer. 67 */ 68 public static final int SENSOR = 3; 69 70 /** 71 * A constant indicating a a wifi running timer 72 */ 73 public static final int WIFI_RUNNING = 4; 74 75 /** 76 * A constant indicating a full wifi lock timer 77 */ 78 public static final int FULL_WIFI_LOCK = 5; 79 80 /** 81 * A constant indicating a wifi scan 82 */ 83 public static final int WIFI_SCAN = 6; 84 85 /** 86 * A constant indicating a wifi multicast timer 87 */ 88 public static final int WIFI_MULTICAST_ENABLED = 7; 89 90 /** 91 * A constant indicating an audio turn on timer 92 */ 93 public static final int AUDIO_TURNED_ON = 7; 94 95 /** 96 * A constant indicating a video turn on timer 97 */ 98 public static final int VIDEO_TURNED_ON = 8; 99 100 /** 101 * A constant indicating a vibrator on timer 102 */ 103 public static final int VIBRATOR_ON = 9; 104 105 /** 106 * A constant indicating a foreground activity timer 107 */ 108 public static final int FOREGROUND_ACTIVITY = 10; 109 110 /** 111 * A constant indicating a wifi batched scan is active 112 */ 113 public static final int WIFI_BATCHED_SCAN = 11; 114 115 /** 116 * Include all of the data in the stats, including previously saved data. 117 */ 118 public static final int STATS_SINCE_CHARGED = 0; 119 120 /** 121 * Include only the current run in the stats. 122 */ 123 public static final int STATS_CURRENT = 1; 124 125 /** 126 * Include only the run since the last time the device was unplugged in the stats. 127 */ 128 public static final int STATS_SINCE_UNPLUGGED = 2; 129 130 // NOTE: Update this list if you add/change any stats above. 131 // These characters are supposed to represent "total", "last", "current", 132 // and "unplugged". They were shortened for efficiency sake. 133 private static final String[] STAT_NAMES = { "l", "c", "u" }; 134 135 /** 136 * Bump the version on this if the checkin format changes. 137 */ 138 private static final int BATTERY_STATS_CHECKIN_VERSION = 7; 139 140 private static final long BYTES_PER_KB = 1024; 141 private static final long BYTES_PER_MB = 1048576; // 1024^2 142 private static final long BYTES_PER_GB = 1073741824; //1024^3 143 144 145 private static final String UID_DATA = "uid"; 146 private static final String APK_DATA = "apk"; 147 private static final String PROCESS_DATA = "pr"; 148 private static final String SENSOR_DATA = "sr"; 149 private static final String VIBRATOR_DATA = "vib"; 150 private static final String FOREGROUND_DATA = "fg"; 151 private static final String WAKELOCK_DATA = "wl"; 152 private static final String KERNEL_WAKELOCK_DATA = "kwl"; 153 private static final String WAKEUP_REASON_DATA = "wr"; 154 private static final String NETWORK_DATA = "nt"; 155 private static final String USER_ACTIVITY_DATA = "ua"; 156 private static final String BATTERY_DATA = "bt"; 157 private static final String BATTERY_DISCHARGE_DATA = "dc"; 158 private static final String BATTERY_LEVEL_DATA = "lv"; 159 private static final String WIFI_DATA = "wfl"; 160 private static final String MISC_DATA = "m"; 161 private static final String GLOBAL_NETWORK_DATA = "gn"; 162 private static final String HISTORY_STRING_POOL = "hsp"; 163 private static final String HISTORY_DATA = "h"; 164 private static final String SCREEN_BRIGHTNESS_DATA = "br"; 165 private static final String SIGNAL_STRENGTH_TIME_DATA = "sgt"; 166 private static final String SIGNAL_SCANNING_TIME_DATA = "sst"; 167 private static final String SIGNAL_STRENGTH_COUNT_DATA = "sgc"; 168 private static final String DATA_CONNECTION_TIME_DATA = "dct"; 169 private static final String DATA_CONNECTION_COUNT_DATA = "dcc"; 170 private static final String WIFI_STATE_TIME_DATA = "wst"; 171 private static final String WIFI_STATE_COUNT_DATA = "wsc"; 172 private static final String BLUETOOTH_STATE_TIME_DATA = "bst"; 173 private static final String BLUETOOTH_STATE_COUNT_DATA = "bsc"; 174 private static final String POWER_USE_SUMMARY_DATA = "pws"; 175 private static final String POWER_USE_ITEM_DATA = "pwi"; 176 private static final String DISCHARGE_STEP_DATA = "dsd"; 177 private static final String CHARGE_STEP_DATA = "csd"; 178 179 private final StringBuilder mFormatBuilder = new StringBuilder(32); 180 private final Formatter mFormatter = new Formatter(mFormatBuilder); 181 182 /** 183 * State for keeping track of counting information. 184 */ 185 public static abstract class Counter { 186 187 /** 188 * Returns the count associated with this Counter for the 189 * selected type of statistics. 190 * 191 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT 192 */ 193 public abstract int getCountLocked(int which); 194 195 /** 196 * Temporary for debugging. 197 */ 198 public abstract void logState(Printer pw, String prefix); 199 } 200 201 /** 202 * State for keeping track of long counting information. 203 */ 204 public static abstract class LongCounter { 205 206 /** 207 * Returns the count associated with this Counter for the 208 * selected type of statistics. 209 * 210 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT 211 */ 212 public abstract long getCountLocked(int which); 213 214 /** 215 * Temporary for debugging. 216 */ 217 public abstract void logState(Printer pw, String prefix); 218 } 219 220 /** 221 * State for keeping track of timing information. 222 */ 223 public static abstract class Timer { 224 225 /** 226 * Returns the count associated with this Timer for the 227 * selected type of statistics. 228 * 229 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT 230 */ 231 public abstract int getCountLocked(int which); 232 233 /** 234 * Returns the total time in microseconds associated with this Timer for the 235 * selected type of statistics. 236 * 237 * @param elapsedRealtimeUs current elapsed realtime of system in microseconds 238 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT 239 * @return a time in microseconds 240 */ 241 public abstract long getTotalTimeLocked(long elapsedRealtimeUs, int which); 242 243 /** 244 * Temporary for debugging. 245 */ 246 public abstract void logState(Printer pw, String prefix); 247 } 248 249 /** 250 * The statistics associated with a particular uid. 251 */ 252 public static abstract class Uid { 253 254 /** 255 * Returns a mapping containing wakelock statistics. 256 * 257 * @return a Map from Strings to Uid.Wakelock objects. 258 */ 259 public abstract Map<String, ? extends Wakelock> getWakelockStats(); 260 261 /** 262 * The statistics associated with a particular wake lock. 263 */ 264 public static abstract class Wakelock { 265 public abstract Timer getWakeTime(int type); 266 } 267 268 /** 269 * Returns a mapping containing sensor statistics. 270 * 271 * @return a Map from Integer sensor ids to Uid.Sensor objects. 272 */ 273 public abstract Map<Integer, ? extends Sensor> getSensorStats(); 274 275 /** 276 * Returns a mapping containing active process data. 277 */ 278 public abstract SparseArray<? extends Pid> getPidStats(); 279 280 /** 281 * Returns a mapping containing process statistics. 282 * 283 * @return a Map from Strings to Uid.Proc objects. 284 */ 285 public abstract Map<String, ? extends Proc> getProcessStats(); 286 287 /** 288 * Returns a mapping containing package statistics. 289 * 290 * @return a Map from Strings to Uid.Pkg objects. 291 */ 292 public abstract Map<String, ? extends Pkg> getPackageStats(); 293 294 /** 295 * {@hide} 296 */ 297 public abstract int getUid(); 298 299 public abstract void noteWifiRunningLocked(long elapsedRealtime); 300 public abstract void noteWifiStoppedLocked(long elapsedRealtime); 301 public abstract void noteFullWifiLockAcquiredLocked(long elapsedRealtime); 302 public abstract void noteFullWifiLockReleasedLocked(long elapsedRealtime); 303 public abstract void noteWifiScanStartedLocked(long elapsedRealtime); 304 public abstract void noteWifiScanStoppedLocked(long elapsedRealtime); 305 public abstract void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtime); 306 public abstract void noteWifiBatchedScanStoppedLocked(long elapsedRealtime); 307 public abstract void noteWifiMulticastEnabledLocked(long elapsedRealtime); 308 public abstract void noteWifiMulticastDisabledLocked(long elapsedRealtime); 309 public abstract void noteAudioTurnedOnLocked(long elapsedRealtime); 310 public abstract void noteAudioTurnedOffLocked(long elapsedRealtime); 311 public abstract void noteVideoTurnedOnLocked(long elapsedRealtime); 312 public abstract void noteVideoTurnedOffLocked(long elapsedRealtime); 313 public abstract void noteActivityResumedLocked(long elapsedRealtime); 314 public abstract void noteActivityPausedLocked(long elapsedRealtime); 315 public abstract long getWifiRunningTime(long elapsedRealtimeUs, int which); 316 public abstract long getFullWifiLockTime(long elapsedRealtimeUs, int which); 317 public abstract long getWifiScanTime(long elapsedRealtimeUs, int which); 318 public abstract long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which); 319 public abstract long getWifiMulticastTime(long elapsedRealtimeUs, int which); 320 public abstract long getAudioTurnedOnTime(long elapsedRealtimeUs, int which); 321 public abstract long getVideoTurnedOnTime(long elapsedRealtimeUs, int which); 322 public abstract Timer getForegroundActivityTimer(); 323 public abstract Timer getVibratorOnTimer(); 324 325 public static final int NUM_WIFI_BATCHED_SCAN_BINS = 5; 326 327 /** 328 * Note that these must match the constants in android.os.PowerManager. 329 * Also, if the user activity types change, the BatteryStatsImpl.VERSION must 330 * also be bumped. 331 */ 332 static final String[] USER_ACTIVITY_TYPES = { 333 "other", "button", "touch" 334 }; 335 336 public static final int NUM_USER_ACTIVITY_TYPES = 3; 337 338 public abstract void noteUserActivityLocked(int type); 339 public abstract boolean hasUserActivity(); 340 public abstract int getUserActivityCount(int type, int which); 341 342 public abstract boolean hasNetworkActivity(); 343 public abstract long getNetworkActivityBytes(int type, int which); 344 public abstract long getNetworkActivityPackets(int type, int which); 345 public abstract long getMobileRadioActiveTime(int which); 346 public abstract int getMobileRadioActiveCount(int which); 347 348 public static abstract class Sensor { 349 /* 350 * FIXME: it's not correct to use this magic value because it 351 * could clash with a sensor handle (which are defined by 352 * the sensor HAL, and therefore out of our control 353 */ 354 // Magic sensor number for the GPS. 355 public static final int GPS = -10000; 356 357 public abstract int getHandle(); 358 359 public abstract Timer getSensorTime(); 360 } 361 362 public class Pid { 363 public int mWakeNesting; 364 public long mWakeSumMs; 365 public long mWakeStartMs; 366 } 367 368 /** 369 * The statistics associated with a particular process. 370 */ 371 public static abstract class Proc { 372 373 public static class ExcessivePower { 374 public static final int TYPE_WAKE = 1; 375 public static final int TYPE_CPU = 2; 376 377 public int type; 378 public long overTime; 379 public long usedTime; 380 } 381 382 /** 383 * Returns true if this process is still active in the battery stats. 384 */ 385 public abstract boolean isActive(); 386 387 /** 388 * Returns the total time (in 1/100 sec) spent executing in user code. 389 * 390 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 391 */ 392 public abstract long getUserTime(int which); 393 394 /** 395 * Returns the total time (in 1/100 sec) spent executing in system code. 396 * 397 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 398 */ 399 public abstract long getSystemTime(int which); 400 401 /** 402 * Returns the number of times the process has been started. 403 * 404 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 405 */ 406 public abstract int getStarts(int which); 407 408 /** 409 * Returns the cpu time spent in microseconds while the process was in the foreground. 410 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 411 * @return foreground cpu time in microseconds 412 */ 413 public abstract long getForegroundTime(int which); 414 415 /** 416 * Returns the approximate cpu time spent in microseconds, at a certain CPU speed. 417 * @param speedStep the index of the CPU speed. This is not the actual speed of the 418 * CPU. 419 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 420 * @see BatteryStats#getCpuSpeedSteps() 421 */ 422 public abstract long getTimeAtCpuSpeedStep(int speedStep, int which); 423 424 public abstract int countExcessivePowers(); 425 426 public abstract ExcessivePower getExcessivePower(int i); 427 } 428 429 /** 430 * The statistics associated with a particular package. 431 */ 432 public static abstract class Pkg { 433 434 /** 435 * Returns the number of times this package has done something that could wake up the 436 * device from sleep. 437 * 438 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 439 */ 440 public abstract int getWakeups(int which); 441 442 /** 443 * Returns a mapping containing service statistics. 444 */ 445 public abstract Map<String, ? extends Serv> getServiceStats(); 446 447 /** 448 * The statistics associated with a particular service. 449 */ 450 public abstract class Serv { 451 452 /** 453 * Returns the amount of time spent started. 454 * 455 * @param batteryUptime elapsed uptime on battery in microseconds. 456 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 457 * @return 458 */ 459 public abstract long getStartTime(long batteryUptime, int which); 460 461 /** 462 * Returns the total number of times startService() has been called. 463 * 464 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 465 */ 466 public abstract int getStarts(int which); 467 468 /** 469 * Returns the total number times the service has been launched. 470 * 471 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 472 */ 473 public abstract int getLaunches(int which); 474 } 475 } 476 } 477 478 public final static class HistoryTag { 479 public String string; 480 public int uid; 481 482 public int poolIdx; 483 484 public void setTo(HistoryTag o) { 485 string = o.string; 486 uid = o.uid; 487 poolIdx = o.poolIdx; 488 } 489 490 public void setTo(String _string, int _uid) { 491 string = _string; 492 uid = _uid; 493 poolIdx = -1; 494 } 495 496 public void writeToParcel(Parcel dest, int flags) { 497 dest.writeString(string); 498 dest.writeInt(uid); 499 } 500 501 public void readFromParcel(Parcel src) { 502 string = src.readString(); 503 uid = src.readInt(); 504 poolIdx = -1; 505 } 506 507 @Override 508 public boolean equals(Object o) { 509 if (this == o) return true; 510 if (o == null || getClass() != o.getClass()) return false; 511 512 HistoryTag that = (HistoryTag) o; 513 514 if (uid != that.uid) return false; 515 if (!string.equals(that.string)) return false; 516 517 return true; 518 } 519 520 @Override 521 public int hashCode() { 522 int result = string.hashCode(); 523 result = 31 * result + uid; 524 return result; 525 } 526 } 527 528 public final static class HistoryItem implements Parcelable { 529 public HistoryItem next; 530 531 public long time; 532 533 public static final byte CMD_UPDATE = 0; // These can be written as deltas 534 public static final byte CMD_NULL = -1; 535 public static final byte CMD_START = 4; 536 public static final byte CMD_CURRENT_TIME = 5; 537 public static final byte CMD_OVERFLOW = 6; 538 539 public byte cmd = CMD_NULL; 540 541 /** 542 * Return whether the command code is a delta data update. 543 */ 544 public boolean isDeltaData() { 545 return cmd == CMD_UPDATE; 546 } 547 548 public byte batteryLevel; 549 public byte batteryStatus; 550 public byte batteryHealth; 551 public byte batteryPlugType; 552 553 public short batteryTemperature; 554 public char batteryVoltage; 555 556 // Constants from SCREEN_BRIGHTNESS_* 557 public static final int STATE_BRIGHTNESS_SHIFT = 0; 558 public static final int STATE_BRIGHTNESS_MASK = 0x7; 559 // Constants from SIGNAL_STRENGTH_* 560 public static final int STATE_SIGNAL_STRENGTH_SHIFT = 3; 561 public static final int STATE_SIGNAL_STRENGTH_MASK = 0x7 << STATE_SIGNAL_STRENGTH_SHIFT; 562 // Constants from ServiceState.STATE_* 563 public static final int STATE_PHONE_STATE_SHIFT = 6; 564 public static final int STATE_PHONE_STATE_MASK = 0x7 << STATE_PHONE_STATE_SHIFT; 565 // Constants from DATA_CONNECTION_* 566 public static final int STATE_DATA_CONNECTION_SHIFT = 9; 567 public static final int STATE_DATA_CONNECTION_MASK = 0x1f << STATE_DATA_CONNECTION_SHIFT; 568 569 // These states always appear directly in the first int token 570 // of a delta change; they should be ones that change relatively 571 // frequently. 572 public static final int STATE_CPU_RUNNING_FLAG = 1<<31; 573 public static final int STATE_WAKE_LOCK_FLAG = 1<<30; 574 public static final int STATE_GPS_ON_FLAG = 1<<29; 575 public static final int STATE_WIFI_FULL_LOCK_FLAG = 1<<28; 576 public static final int STATE_WIFI_SCAN_FLAG = 1<<27; 577 public static final int STATE_WIFI_MULTICAST_ON_FLAG = 1<<26; 578 public static final int STATE_MOBILE_RADIO_ACTIVE_FLAG = 1<<25; 579 public static final int STATE_WIFI_RUNNING_FLAG = 1<<24; 580 // These are on the lower bits used for the command; if they change 581 // we need to write another int of data. 582 public static final int STATE_SENSOR_ON_FLAG = 1<<23; 583 public static final int STATE_AUDIO_ON_FLAG = 1<<22; 584 public static final int STATE_PHONE_SCANNING_FLAG = 1<<21; 585 public static final int STATE_SCREEN_ON_FLAG = 1<<20; 586 public static final int STATE_BATTERY_PLUGGED_FLAG = 1<<19; 587 public static final int STATE_PHONE_IN_CALL_FLAG = 1<<18; 588 public static final int STATE_WIFI_ON_FLAG = 1<<17; 589 public static final int STATE_BLUETOOTH_ON_FLAG = 1<<16; 590 591 public static final int MOST_INTERESTING_STATES = 592 STATE_BATTERY_PLUGGED_FLAG | STATE_SCREEN_ON_FLAG 593 | STATE_GPS_ON_FLAG | STATE_PHONE_IN_CALL_FLAG; 594 595 public int states; 596 597 public static final int STATE2_VIDEO_ON_FLAG = 1<<0; 598 public int states2; 599 600 // The wake lock that was acquired at this point. 601 public HistoryTag wakelockTag; 602 603 // Kernel wakeup reason at this point. 604 public HistoryTag wakeReasonTag; 605 606 public static final int EVENT_FLAG_START = 0x8000; 607 public static final int EVENT_FLAG_FINISH = 0x4000; 608 609 // No event in this item. 610 public static final int EVENT_NONE = 0x0000; 611 // Event is about a process that is running. 612 public static final int EVENT_PROC = 0x0001; 613 // Event is about an application package that is in the foreground. 614 public static final int EVENT_FOREGROUND = 0x0002; 615 // Event is about an application package that is at the top of the screen. 616 public static final int EVENT_TOP = 0x0003; 617 // Event is about an application package that is at the top of the screen. 618 public static final int EVENT_SYNC = 0x0004; 619 // Number of event types. 620 public static final int EVENT_COUNT = 0x0005; 621 622 public static final int EVENT_PROC_START = EVENT_PROC | EVENT_FLAG_START; 623 public static final int EVENT_PROC_FINISH = EVENT_PROC | EVENT_FLAG_FINISH; 624 public static final int EVENT_FOREGROUND_START = EVENT_FOREGROUND | EVENT_FLAG_START; 625 public static final int EVENT_FOREGROUND_FINISH = EVENT_FOREGROUND | EVENT_FLAG_FINISH; 626 public static final int EVENT_TOP_START = EVENT_TOP | EVENT_FLAG_START; 627 public static final int EVENT_TOP_FINISH = EVENT_TOP | EVENT_FLAG_FINISH; 628 public static final int EVENT_SYNC_START = EVENT_SYNC | EVENT_FLAG_START; 629 public static final int EVENT_SYNC_FINISH = EVENT_SYNC | EVENT_FLAG_FINISH; 630 631 // For CMD_EVENT. 632 public int eventCode; 633 public HistoryTag eventTag; 634 635 // Only set for CMD_CURRENT_TIME. 636 public long currentTime; 637 638 // Meta-data when reading. 639 public int numReadInts; 640 641 // Pre-allocated objects. 642 public final HistoryTag localWakelockTag = new HistoryTag(); 643 public final HistoryTag localWakeReasonTag = new HistoryTag(); 644 public final HistoryTag localEventTag = new HistoryTag(); 645 646 public HistoryItem() { 647 } 648 649 public HistoryItem(long time, Parcel src) { 650 this.time = time; 651 numReadInts = 2; 652 readFromParcel(src); 653 } 654 655 public int describeContents() { 656 return 0; 657 } 658 659 public void writeToParcel(Parcel dest, int flags) { 660 dest.writeLong(time); 661 int bat = (((int)cmd)&0xff) 662 | ((((int)batteryLevel)<<8)&0xff00) 663 | ((((int)batteryStatus)<<16)&0xf0000) 664 | ((((int)batteryHealth)<<20)&0xf00000) 665 | ((((int)batteryPlugType)<<24)&0xf000000) 666 | (wakelockTag != null ? 0x10000000 : 0) 667 | (wakeReasonTag != null ? 0x20000000 : 0) 668 | (eventCode != EVENT_NONE ? 0x40000000 : 0); 669 dest.writeInt(bat); 670 bat = (((int)batteryTemperature)&0xffff) 671 | ((((int)batteryVoltage)<<16)&0xffff0000); 672 dest.writeInt(bat); 673 dest.writeInt(states); 674 dest.writeInt(states2); 675 if (wakelockTag != null) { 676 wakelockTag.writeToParcel(dest, flags); 677 } 678 if (wakeReasonTag != null) { 679 wakeReasonTag.writeToParcel(dest, flags); 680 } 681 if (eventCode != EVENT_NONE) { 682 dest.writeInt(eventCode); 683 eventTag.writeToParcel(dest, flags); 684 } 685 if (cmd == CMD_CURRENT_TIME) { 686 dest.writeLong(currentTime); 687 } 688 } 689 690 public void readFromParcel(Parcel src) { 691 int start = src.dataPosition(); 692 int bat = src.readInt(); 693 cmd = (byte)(bat&0xff); 694 batteryLevel = (byte)((bat>>8)&0xff); 695 batteryStatus = (byte)((bat>>16)&0xf); 696 batteryHealth = (byte)((bat>>20)&0xf); 697 batteryPlugType = (byte)((bat>>24)&0xf); 698 int bat2 = src.readInt(); 699 batteryTemperature = (short)(bat2&0xffff); 700 batteryVoltage = (char)((bat2>>16)&0xffff); 701 states = src.readInt(); 702 states2 = src.readInt(); 703 if ((bat&0x10000000) != 0) { 704 wakelockTag = localWakelockTag; 705 wakelockTag.readFromParcel(src); 706 } else { 707 wakelockTag = null; 708 } 709 if ((bat&0x20000000) != 0) { 710 wakeReasonTag = localWakeReasonTag; 711 wakeReasonTag.readFromParcel(src); 712 } else { 713 wakeReasonTag = null; 714 } 715 if ((bat&0x40000000) != 0) { 716 eventCode = src.readInt(); 717 eventTag = localEventTag; 718 eventTag.readFromParcel(src); 719 } else { 720 eventCode = EVENT_NONE; 721 eventTag = null; 722 } 723 if (cmd == CMD_CURRENT_TIME) { 724 currentTime = src.readLong(); 725 } else { 726 currentTime = 0; 727 } 728 numReadInts += (src.dataPosition()-start)/4; 729 } 730 731 public void clear() { 732 time = 0; 733 cmd = CMD_NULL; 734 batteryLevel = 0; 735 batteryStatus = 0; 736 batteryHealth = 0; 737 batteryPlugType = 0; 738 batteryTemperature = 0; 739 batteryVoltage = 0; 740 states = 0; 741 states2 = 0; 742 wakelockTag = null; 743 wakeReasonTag = null; 744 eventCode = EVENT_NONE; 745 eventTag = null; 746 } 747 748 public void setTo(HistoryItem o) { 749 time = o.time; 750 cmd = o.cmd; 751 setToCommon(o); 752 } 753 754 public void setTo(long time, byte cmd, HistoryItem o) { 755 this.time = time; 756 this.cmd = cmd; 757 setToCommon(o); 758 } 759 760 private void setToCommon(HistoryItem o) { 761 batteryLevel = o.batteryLevel; 762 batteryStatus = o.batteryStatus; 763 batteryHealth = o.batteryHealth; 764 batteryPlugType = o.batteryPlugType; 765 batteryTemperature = o.batteryTemperature; 766 batteryVoltage = o.batteryVoltage; 767 states = o.states; 768 states2 = o.states2; 769 if (o.wakelockTag != null) { 770 wakelockTag = localWakelockTag; 771 wakelockTag.setTo(o.wakelockTag); 772 } else { 773 wakelockTag = null; 774 } 775 if (o.wakeReasonTag != null) { 776 wakeReasonTag = localWakeReasonTag; 777 wakeReasonTag.setTo(o.wakeReasonTag); 778 } else { 779 wakeReasonTag = null; 780 } 781 eventCode = o.eventCode; 782 if (o.eventTag != null) { 783 eventTag = localEventTag; 784 eventTag.setTo(o.eventTag); 785 } else { 786 eventTag = null; 787 } 788 currentTime = o.currentTime; 789 } 790 791 public boolean sameNonEvent(HistoryItem o) { 792 return batteryLevel == o.batteryLevel 793 && batteryStatus == o.batteryStatus 794 && batteryHealth == o.batteryHealth 795 && batteryPlugType == o.batteryPlugType 796 && batteryTemperature == o.batteryTemperature 797 && batteryVoltage == o.batteryVoltage 798 && states == o.states 799 && states2 == o.states2 800 && currentTime == o.currentTime; 801 } 802 803 public boolean same(HistoryItem o) { 804 if (!sameNonEvent(o) || eventCode != o.eventCode) { 805 return false; 806 } 807 if (wakelockTag != o.wakelockTag) { 808 if (wakelockTag == null || o.wakelockTag == null) { 809 return false; 810 } 811 if (!wakelockTag.equals(o.wakelockTag)) { 812 return false; 813 } 814 } 815 if (wakeReasonTag != o.wakeReasonTag) { 816 if (wakeReasonTag == null || o.wakeReasonTag == null) { 817 return false; 818 } 819 if (!wakeReasonTag.equals(o.wakeReasonTag)) { 820 return false; 821 } 822 } 823 if (eventTag != o.eventTag) { 824 if (eventTag == null || o.eventTag == null) { 825 return false; 826 } 827 if (!eventTag.equals(o.eventTag)) { 828 return false; 829 } 830 } 831 return true; 832 } 833 } 834 835 public static final class BitDescription { 836 public final int mask; 837 public final int shift; 838 public final String name; 839 public final String shortName; 840 public final String[] values; 841 public final String[] shortValues; 842 843 public BitDescription(int mask, String name, String shortName) { 844 this.mask = mask; 845 this.shift = -1; 846 this.name = name; 847 this.shortName = shortName; 848 this.values = null; 849 this.shortValues = null; 850 } 851 852 public BitDescription(int mask, int shift, String name, String shortName, 853 String[] values, String[] shortValues) { 854 this.mask = mask; 855 this.shift = shift; 856 this.name = name; 857 this.shortName = shortName; 858 this.values = values; 859 this.shortValues = shortValues; 860 } 861 } 862 863 public abstract int getHistoryTotalSize(); 864 865 public abstract int getHistoryUsedSize(); 866 867 public abstract boolean startIteratingHistoryLocked(); 868 869 public abstract int getHistoryStringPoolSize(); 870 871 public abstract int getHistoryStringPoolBytes(); 872 873 public abstract String getHistoryTagPoolString(int index); 874 875 public abstract int getHistoryTagPoolUid(int index); 876 877 public abstract boolean getNextHistoryLocked(HistoryItem out); 878 879 public abstract void finishIteratingHistoryLocked(); 880 881 public abstract boolean startIteratingOldHistoryLocked(); 882 883 public abstract boolean getNextOldHistoryLocked(HistoryItem out); 884 885 public abstract void finishIteratingOldHistoryLocked(); 886 887 /** 888 * Return the base time offset for the battery history. 889 */ 890 public abstract long getHistoryBaseTime(); 891 892 /** 893 * Returns the number of times the device has been started. 894 */ 895 public abstract int getStartCount(); 896 897 /** 898 * Returns the time in microseconds that the screen has been on while the device was 899 * running on battery. 900 * 901 * {@hide} 902 */ 903 public abstract long getScreenOnTime(long elapsedRealtimeUs, int which); 904 905 /** 906 * Returns the number of times the screen was turned on. 907 * 908 * {@hide} 909 */ 910 public abstract int getScreenOnCount(int which); 911 912 public static final int SCREEN_BRIGHTNESS_DARK = 0; 913 public static final int SCREEN_BRIGHTNESS_DIM = 1; 914 public static final int SCREEN_BRIGHTNESS_MEDIUM = 2; 915 public static final int SCREEN_BRIGHTNESS_LIGHT = 3; 916 public static final int SCREEN_BRIGHTNESS_BRIGHT = 4; 917 918 static final String[] SCREEN_BRIGHTNESS_NAMES = { 919 "dark", "dim", "medium", "light", "bright" 920 }; 921 922 static final String[] SCREEN_BRIGHTNESS_SHORT_NAMES = { 923 "0", "1", "2", "3", "4" 924 }; 925 926 public static final int NUM_SCREEN_BRIGHTNESS_BINS = 5; 927 928 /** 929 * Returns the time in microseconds that the screen has been on with 930 * the given brightness 931 * 932 * {@hide} 933 */ 934 public abstract long getScreenBrightnessTime(int brightnessBin, 935 long elapsedRealtimeUs, int which); 936 937 public abstract int getInputEventCount(int which); 938 939 /** 940 * Returns the time in microseconds that the phone has been on while the device was 941 * running on battery. 942 * 943 * {@hide} 944 */ 945 public abstract long getPhoneOnTime(long elapsedRealtimeUs, int which); 946 947 /** 948 * Returns the number of times a phone call was activated. 949 * 950 * {@hide} 951 */ 952 public abstract int getPhoneOnCount(int which); 953 954 /** 955 * Returns the time in microseconds that the phone has been running with 956 * the given signal strength. 957 * 958 * {@hide} 959 */ 960 public abstract long getPhoneSignalStrengthTime(int strengthBin, 961 long elapsedRealtimeUs, int which); 962 963 /** 964 * Returns the time in microseconds that the phone has been trying to 965 * acquire a signal. 966 * 967 * {@hide} 968 */ 969 public abstract long getPhoneSignalScanningTime( 970 long elapsedRealtimeUs, int which); 971 972 /** 973 * Returns the number of times the phone has entered the given signal strength. 974 * 975 * {@hide} 976 */ 977 public abstract int getPhoneSignalStrengthCount(int strengthBin, int which); 978 979 /** 980 * Returns the time in microseconds that the mobile network has been active 981 * (in a high power state). 982 * 983 * {@hide} 984 */ 985 public abstract long getMobileRadioActiveTime(long elapsedRealtimeUs, int which); 986 987 /** 988 * Returns the number of times that the mobile network has transitioned to the 989 * active state. 990 * 991 * {@hide} 992 */ 993 public abstract int getMobileRadioActiveCount(int which); 994 995 /** 996 * Returns the time in microseconds that is the difference between the mobile radio 997 * time we saw based on the elapsed timestamp when going down vs. the given time stamp 998 * from the radio. 999 * 1000 * {@hide} 1001 */ 1002 public abstract long getMobileRadioActiveAdjustedTime(int which); 1003 1004 /** 1005 * Returns the time in microseconds that the mobile network has been active 1006 * (in a high power state) but not being able to blame on an app. 1007 * 1008 * {@hide} 1009 */ 1010 public abstract long getMobileRadioActiveUnknownTime(int which); 1011 1012 /** 1013 * Return count of number of times radio was up that could not be blamed on apps. 1014 * 1015 * {@hide} 1016 */ 1017 public abstract int getMobileRadioActiveUnknownCount(int which); 1018 1019 public static final int DATA_CONNECTION_NONE = 0; 1020 public static final int DATA_CONNECTION_GPRS = 1; 1021 public static final int DATA_CONNECTION_EDGE = 2; 1022 public static final int DATA_CONNECTION_UMTS = 3; 1023 public static final int DATA_CONNECTION_CDMA = 4; 1024 public static final int DATA_CONNECTION_EVDO_0 = 5; 1025 public static final int DATA_CONNECTION_EVDO_A = 6; 1026 public static final int DATA_CONNECTION_1xRTT = 7; 1027 public static final int DATA_CONNECTION_HSDPA = 8; 1028 public static final int DATA_CONNECTION_HSUPA = 9; 1029 public static final int DATA_CONNECTION_HSPA = 10; 1030 public static final int DATA_CONNECTION_IDEN = 11; 1031 public static final int DATA_CONNECTION_EVDO_B = 12; 1032 public static final int DATA_CONNECTION_LTE = 13; 1033 public static final int DATA_CONNECTION_EHRPD = 14; 1034 public static final int DATA_CONNECTION_HSPAP = 15; 1035 public static final int DATA_CONNECTION_OTHER = 16; 1036 1037 static final String[] DATA_CONNECTION_NAMES = { 1038 "none", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A", 1039 "1xrtt", "hsdpa", "hsupa", "hspa", "iden", "evdo_b", "lte", 1040 "ehrpd", "hspap", "other" 1041 }; 1042 1043 public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER+1; 1044 1045 /** 1046 * Returns the time in microseconds that the phone has been running with 1047 * the given data connection. 1048 * 1049 * {@hide} 1050 */ 1051 public abstract long getPhoneDataConnectionTime(int dataType, 1052 long elapsedRealtimeUs, int which); 1053 1054 /** 1055 * Returns the number of times the phone has entered the given data 1056 * connection type. 1057 * 1058 * {@hide} 1059 */ 1060 public abstract int getPhoneDataConnectionCount(int dataType, int which); 1061 1062 public static final BitDescription[] HISTORY_STATE_DESCRIPTIONS 1063 = new BitDescription[] { 1064 new BitDescription(HistoryItem.STATE_CPU_RUNNING_FLAG, "running", "r"), 1065 new BitDescription(HistoryItem.STATE_WAKE_LOCK_FLAG, "wake_lock", "w"), 1066 new BitDescription(HistoryItem.STATE_SENSOR_ON_FLAG, "sensor", "s"), 1067 new BitDescription(HistoryItem.STATE_GPS_ON_FLAG, "gps", "g"), 1068 new BitDescription(HistoryItem.STATE_WIFI_FULL_LOCK_FLAG, "wifi_full_lock", "Wl"), 1069 new BitDescription(HistoryItem.STATE_WIFI_SCAN_FLAG, "wifi_scan", "Ws"), 1070 new BitDescription(HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG, "wifi_multicast", "Wm"), 1071 new BitDescription(HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG, "mobile_radio", "Pr"), 1072 new BitDescription(HistoryItem.STATE_WIFI_RUNNING_FLAG, "wifi_running", "Wr"), 1073 new BitDescription(HistoryItem.STATE_PHONE_SCANNING_FLAG, "phone_scanning", "Psc"), 1074 new BitDescription(HistoryItem.STATE_AUDIO_ON_FLAG, "audio", "a"), 1075 new BitDescription(HistoryItem.STATE_SCREEN_ON_FLAG, "screen", "S"), 1076 new BitDescription(HistoryItem.STATE_BATTERY_PLUGGED_FLAG, "plugged", "BP"), 1077 new BitDescription(HistoryItem.STATE_PHONE_IN_CALL_FLAG, "phone_in_call", "Pcl"), 1078 new BitDescription(HistoryItem.STATE_WIFI_ON_FLAG, "wifi", "W"), 1079 new BitDescription(HistoryItem.STATE_BLUETOOTH_ON_FLAG, "bluetooth", "b"), 1080 new BitDescription(HistoryItem.STATE_DATA_CONNECTION_MASK, 1081 HistoryItem.STATE_DATA_CONNECTION_SHIFT, "data_conn", "Pcn", 1082 DATA_CONNECTION_NAMES, DATA_CONNECTION_NAMES), 1083 new BitDescription(HistoryItem.STATE_PHONE_STATE_MASK, 1084 HistoryItem.STATE_PHONE_STATE_SHIFT, "phone_state", "Pst", 1085 new String[] {"in", "out", "emergency", "off"}, 1086 new String[] {"in", "out", "em", "off"}), 1087 new BitDescription(HistoryItem.STATE_SIGNAL_STRENGTH_MASK, 1088 HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT, "signal_strength", "Pss", 1089 SignalStrength.SIGNAL_STRENGTH_NAMES, new String[] { 1090 "0", "1", "2", "3", "4" 1091 }), 1092 new BitDescription(HistoryItem.STATE_BRIGHTNESS_MASK, 1093 HistoryItem.STATE_BRIGHTNESS_SHIFT, "brightness", "Sb", 1094 SCREEN_BRIGHTNESS_NAMES, SCREEN_BRIGHTNESS_SHORT_NAMES), 1095 }; 1096 1097 public static final BitDescription[] HISTORY_STATE2_DESCRIPTIONS 1098 = new BitDescription[] { 1099 new BitDescription(HistoryItem.STATE2_VIDEO_ON_FLAG, "video", "v"), 1100 }; 1101 1102 public static final String[] HISTORY_EVENT_NAMES = new String[] { 1103 "null", "proc", "fg", "top", "sync" 1104 }; 1105 1106 public static final String[] HISTORY_EVENT_CHECKIN_NAMES = new String[] { 1107 "Enl", "Epr", "Efg", "Etp", "Esy" 1108 }; 1109 1110 /** 1111 * Returns the time in microseconds that wifi has been on while the device was 1112 * running on battery. 1113 * 1114 * {@hide} 1115 */ 1116 public abstract long getWifiOnTime(long elapsedRealtimeUs, int which); 1117 1118 /** 1119 * Returns the time in microseconds that wifi has been on and the driver has 1120 * been in the running state while the device was running on battery. 1121 * 1122 * {@hide} 1123 */ 1124 public abstract long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which); 1125 1126 public static final int WIFI_STATE_OFF = 0; 1127 public static final int WIFI_STATE_OFF_SCANNING = 1; 1128 public static final int WIFI_STATE_ON_NO_NETWORKS = 2; 1129 public static final int WIFI_STATE_ON_DISCONNECTED = 3; 1130 public static final int WIFI_STATE_ON_CONNECTED_STA = 4; 1131 public static final int WIFI_STATE_ON_CONNECTED_P2P = 5; 1132 public static final int WIFI_STATE_ON_CONNECTED_STA_P2P = 6; 1133 public static final int WIFI_STATE_SOFT_AP = 7; 1134 1135 static final String[] WIFI_STATE_NAMES = { 1136 "off", "scanning", "no_net", "disconn", 1137 "sta", "p2p", "sta_p2p", "soft_ap" 1138 }; 1139 1140 public static final int NUM_WIFI_STATES = WIFI_STATE_SOFT_AP+1; 1141 1142 /** 1143 * Returns the time in microseconds that WiFi has been running in the given state. 1144 * 1145 * {@hide} 1146 */ 1147 public abstract long getWifiStateTime(int wifiState, 1148 long elapsedRealtimeUs, int which); 1149 1150 /** 1151 * Returns the number of times that WiFi has entered the given state. 1152 * 1153 * {@hide} 1154 */ 1155 public abstract int getWifiStateCount(int wifiState, int which); 1156 1157 /** 1158 * Returns the time in microseconds that bluetooth has been on while the device was 1159 * running on battery. 1160 * 1161 * {@hide} 1162 */ 1163 public abstract long getBluetoothOnTime(long elapsedRealtimeUs, int which); 1164 1165 public abstract int getBluetoothPingCount(); 1166 1167 public static final int BLUETOOTH_STATE_INACTIVE = 0; 1168 public static final int BLUETOOTH_STATE_LOW = 1; 1169 public static final int BLUETOOTH_STATE_MEDIUM = 2; 1170 public static final int BLUETOOTH_STATE_HIGH = 3; 1171 1172 static final String[] BLUETOOTH_STATE_NAMES = { 1173 "inactive", "low", "med", "high" 1174 }; 1175 1176 public static final int NUM_BLUETOOTH_STATES = BLUETOOTH_STATE_HIGH +1; 1177 1178 /** 1179 * Returns the time in microseconds that Bluetooth has been running in the 1180 * given active state. 1181 * 1182 * {@hide} 1183 */ 1184 public abstract long getBluetoothStateTime(int bluetoothState, 1185 long elapsedRealtimeUs, int which); 1186 1187 /** 1188 * Returns the number of times that Bluetooth has entered the given active state. 1189 * 1190 * {@hide} 1191 */ 1192 public abstract int getBluetoothStateCount(int bluetoothState, int which); 1193 1194 public static final int NETWORK_MOBILE_RX_DATA = 0; 1195 public static final int NETWORK_MOBILE_TX_DATA = 1; 1196 public static final int NETWORK_WIFI_RX_DATA = 2; 1197 public static final int NETWORK_WIFI_TX_DATA = 3; 1198 1199 public static final int NUM_NETWORK_ACTIVITY_TYPES = NETWORK_WIFI_TX_DATA + 1; 1200 1201 public abstract long getNetworkActivityBytes(int type, int which); 1202 public abstract long getNetworkActivityPackets(int type, int which); 1203 1204 /** 1205 * Return the wall clock time when battery stats data collection started. 1206 */ 1207 public abstract long getStartClockTime(); 1208 1209 /** 1210 * Return whether we are currently running on battery. 1211 */ 1212 public abstract boolean getIsOnBattery(); 1213 1214 /** 1215 * Returns a SparseArray containing the statistics for each uid. 1216 */ 1217 public abstract SparseArray<? extends Uid> getUidStats(); 1218 1219 /** 1220 * Returns the current battery uptime in microseconds. 1221 * 1222 * @param curTime the amount of elapsed realtime in microseconds. 1223 */ 1224 public abstract long getBatteryUptime(long curTime); 1225 1226 /** 1227 * Returns the current battery realtime in microseconds. 1228 * 1229 * @param curTime the amount of elapsed realtime in microseconds. 1230 */ 1231 public abstract long getBatteryRealtime(long curTime); 1232 1233 /** 1234 * Returns the battery percentage level at the last time the device was unplugged from power, or 1235 * the last time it booted on battery power. 1236 */ 1237 public abstract int getDischargeStartLevel(); 1238 1239 /** 1240 * Returns the current battery percentage level if we are in a discharge cycle, otherwise 1241 * returns the level at the last plug event. 1242 */ 1243 public abstract int getDischargeCurrentLevel(); 1244 1245 /** 1246 * Get the amount the battery has discharged since the stats were 1247 * last reset after charging, as a lower-end approximation. 1248 */ 1249 public abstract int getLowDischargeAmountSinceCharge(); 1250 1251 /** 1252 * Get the amount the battery has discharged since the stats were 1253 * last reset after charging, as an upper-end approximation. 1254 */ 1255 public abstract int getHighDischargeAmountSinceCharge(); 1256 1257 /** 1258 * Retrieve the discharge amount over the selected discharge period <var>which</var>. 1259 */ 1260 public abstract int getDischargeAmount(int which); 1261 1262 /** 1263 * Get the amount the battery has discharged while the screen was on, 1264 * since the last time power was unplugged. 1265 */ 1266 public abstract int getDischargeAmountScreenOn(); 1267 1268 /** 1269 * Get the amount the battery has discharged while the screen was on, 1270 * since the last time the device was charged. 1271 */ 1272 public abstract int getDischargeAmountScreenOnSinceCharge(); 1273 1274 /** 1275 * Get the amount the battery has discharged while the screen was off, 1276 * since the last time power was unplugged. 1277 */ 1278 public abstract int getDischargeAmountScreenOff(); 1279 1280 /** 1281 * Get the amount the battery has discharged while the screen was off, 1282 * since the last time the device was charged. 1283 */ 1284 public abstract int getDischargeAmountScreenOffSinceCharge(); 1285 1286 /** 1287 * Returns the total, last, or current battery uptime in microseconds. 1288 * 1289 * @param curTime the elapsed realtime in microseconds. 1290 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1291 */ 1292 public abstract long computeBatteryUptime(long curTime, int which); 1293 1294 /** 1295 * Returns the total, last, or current battery realtime in microseconds. 1296 * 1297 * @param curTime the current elapsed realtime in microseconds. 1298 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1299 */ 1300 public abstract long computeBatteryRealtime(long curTime, int which); 1301 1302 /** 1303 * Returns the total, last, or current battery screen off uptime in microseconds. 1304 * 1305 * @param curTime the elapsed realtime in microseconds. 1306 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1307 */ 1308 public abstract long computeBatteryScreenOffUptime(long curTime, int which); 1309 1310 /** 1311 * Returns the total, last, or current battery screen off realtime in microseconds. 1312 * 1313 * @param curTime the current elapsed realtime in microseconds. 1314 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1315 */ 1316 public abstract long computeBatteryScreenOffRealtime(long curTime, int which); 1317 1318 /** 1319 * Returns the total, last, or current uptime in microseconds. 1320 * 1321 * @param curTime the current elapsed realtime in microseconds. 1322 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1323 */ 1324 public abstract long computeUptime(long curTime, int which); 1325 1326 /** 1327 * Returns the total, last, or current realtime in microseconds. 1328 * 1329 * @param curTime the current elapsed realtime in microseconds. 1330 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1331 */ 1332 public abstract long computeRealtime(long curTime, int which); 1333 1334 /** 1335 * Compute an approximation for how much run time (in microseconds) is remaining on 1336 * the battery. Returns -1 if no time can be computed: either there is not 1337 * enough current data to make a decision, or the battery is currently 1338 * charging. 1339 * 1340 * @param curTime The current elepsed realtime in microseconds. 1341 */ 1342 public abstract long computeBatteryTimeRemaining(long curTime); 1343 1344 /** 1345 * Return the historical number of discharge steps we currently have. 1346 */ 1347 public abstract int getNumDischargeStepDurations(); 1348 1349 /** 1350 * Return the array of discharge step durations; the number of valid 1351 * items in it is returned by {@link #getNumDischargeStepDurations()}. 1352 * These values are in milliseconds. 1353 */ 1354 public abstract long[] getDischargeStepDurationsArray(); 1355 1356 /** 1357 * Compute an approximation for how much time (in microseconds) remains until the battery 1358 * is fully charged. Returns -1 if no time can be computed: either there is not 1359 * enough current data to make a decision, or the battery is currently 1360 * discharging. 1361 * 1362 * @param curTime The current elepsed realtime in microseconds. 1363 */ 1364 public abstract long computeChargeTimeRemaining(long curTime); 1365 1366 /** 1367 * Return the historical number of charge steps we currently have. 1368 */ 1369 public abstract int getNumChargeStepDurations(); 1370 1371 /** 1372 * Return the array of charge step durations; the number of valid 1373 * items in it is returned by {@link #getNumChargeStepDurations()}. 1374 * These values are in milliseconds. 1375 */ 1376 public abstract long[] getChargeStepDurationsArray(); 1377 1378 public abstract Map<String, ? extends LongCounter> getWakeupReasonStats(); 1379 1380 public abstract Map<String, ? extends Timer> getKernelWakelockStats(); 1381 1382 /** Returns the number of different speeds that the CPU can run at */ 1383 public abstract int getCpuSpeedSteps(); 1384 1385 public abstract void writeToParcelWithoutUids(Parcel out, int flags); 1386 1387 private final static void formatTimeRaw(StringBuilder out, long seconds) { 1388 long days = seconds / (60 * 60 * 24); 1389 if (days != 0) { 1390 out.append(days); 1391 out.append("d "); 1392 } 1393 long used = days * 60 * 60 * 24; 1394 1395 long hours = (seconds - used) / (60 * 60); 1396 if (hours != 0 || used != 0) { 1397 out.append(hours); 1398 out.append("h "); 1399 } 1400 used += hours * 60 * 60; 1401 1402 long mins = (seconds-used) / 60; 1403 if (mins != 0 || used != 0) { 1404 out.append(mins); 1405 out.append("m "); 1406 } 1407 used += mins * 60; 1408 1409 if (seconds != 0 || used != 0) { 1410 out.append(seconds-used); 1411 out.append("s "); 1412 } 1413 } 1414 1415 public final static void formatTime(StringBuilder sb, long time) { 1416 long sec = time / 100; 1417 formatTimeRaw(sb, sec); 1418 sb.append((time - (sec * 100)) * 10); 1419 sb.append("ms "); 1420 } 1421 1422 public final static void formatTimeMs(StringBuilder sb, long time) { 1423 long sec = time / 1000; 1424 formatTimeRaw(sb, sec); 1425 sb.append(time - (sec * 1000)); 1426 sb.append("ms "); 1427 } 1428 1429 public final static void formatTimeMsNoSpace(StringBuilder sb, long time) { 1430 long sec = time / 1000; 1431 formatTimeRaw(sb, sec); 1432 sb.append(time - (sec * 1000)); 1433 sb.append("ms"); 1434 } 1435 1436 public final String formatRatioLocked(long num, long den) { 1437 if (den == 0L) { 1438 return "--%"; 1439 } 1440 float perc = ((float)num) / ((float)den) * 100; 1441 mFormatBuilder.setLength(0); 1442 mFormatter.format("%.1f%%", perc); 1443 return mFormatBuilder.toString(); 1444 } 1445 1446 final String formatBytesLocked(long bytes) { 1447 mFormatBuilder.setLength(0); 1448 1449 if (bytes < BYTES_PER_KB) { 1450 return bytes + "B"; 1451 } else if (bytes < BYTES_PER_MB) { 1452 mFormatter.format("%.2fKB", bytes / (double) BYTES_PER_KB); 1453 return mFormatBuilder.toString(); 1454 } else if (bytes < BYTES_PER_GB){ 1455 mFormatter.format("%.2fMB", bytes / (double) BYTES_PER_MB); 1456 return mFormatBuilder.toString(); 1457 } else { 1458 mFormatter.format("%.2fGB", bytes / (double) BYTES_PER_GB); 1459 return mFormatBuilder.toString(); 1460 } 1461 } 1462 1463 private static long computeWakeLock(Timer timer, long elapsedRealtimeUs, int which) { 1464 if (timer != null) { 1465 // Convert from microseconds to milliseconds with rounding 1466 long totalTimeMicros = timer.getTotalTimeLocked(elapsedRealtimeUs, which); 1467 long totalTimeMillis = (totalTimeMicros + 500) / 1000; 1468 return totalTimeMillis; 1469 } 1470 return 0; 1471 } 1472 1473 /** 1474 * 1475 * @param sb a StringBuilder object. 1476 * @param timer a Timer object contining the wakelock times. 1477 * @param elapsedRealtimeUs the current on-battery time in microseconds. 1478 * @param name the name of the wakelock. 1479 * @param which which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1480 * @param linePrefix a String to be prepended to each line of output. 1481 * @return the line prefix 1482 */ 1483 private static final String printWakeLock(StringBuilder sb, Timer timer, 1484 long elapsedRealtimeUs, String name, int which, String linePrefix) { 1485 1486 if (timer != null) { 1487 long totalTimeMillis = computeWakeLock(timer, elapsedRealtimeUs, which); 1488 1489 int count = timer.getCountLocked(which); 1490 if (totalTimeMillis != 0) { 1491 sb.append(linePrefix); 1492 formatTimeMs(sb, totalTimeMillis); 1493 if (name != null) { 1494 sb.append(name); 1495 sb.append(' '); 1496 } 1497 sb.append('('); 1498 sb.append(count); 1499 sb.append(" times)"); 1500 return ", "; 1501 } 1502 } 1503 return linePrefix; 1504 } 1505 1506 /** 1507 * Checkin version of wakelock printer. Prints simple comma-separated list. 1508 * 1509 * @param sb a StringBuilder object. 1510 * @param timer a Timer object contining the wakelock times. 1511 * @param elapsedRealtimeUs the current time in microseconds. 1512 * @param name the name of the wakelock. 1513 * @param which which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. 1514 * @param linePrefix a String to be prepended to each line of output. 1515 * @return the line prefix 1516 */ 1517 private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, 1518 long elapsedRealtimeUs, String name, int which, String linePrefix) { 1519 long totalTimeMicros = 0; 1520 int count = 0; 1521 if (timer != null) { 1522 totalTimeMicros = timer.getTotalTimeLocked(elapsedRealtimeUs, which); 1523 count = timer.getCountLocked(which); 1524 } 1525 sb.append(linePrefix); 1526 sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding 1527 sb.append(','); 1528 sb.append(name != null ? name + "," : ""); 1529 sb.append(count); 1530 return ","; 1531 } 1532 1533 /** 1534 * Dump a comma-separated line of values for terse checkin mode. 1535 * 1536 * @param pw the PageWriter to dump log to 1537 * @param category category of data (e.g. "total", "last", "unplugged", "current" ) 1538 * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" , "process", "network") 1539 * @param args type-dependent data arguments 1540 */ 1541 private static final void dumpLine(PrintWriter pw, int uid, String category, String type, 1542 Object... args ) { 1543 pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); 1544 pw.print(uid); pw.print(','); 1545 pw.print(category); pw.print(','); 1546 pw.print(type); 1547 1548 for (Object arg : args) { 1549 pw.print(','); 1550 pw.print(arg); 1551 } 1552 pw.println(); 1553 } 1554 1555 /** 1556 * Checkin server version of dump to produce more compact, computer-readable log. 1557 * 1558 * NOTE: all times are expressed in 'ms'. 1559 */ 1560 public final void dumpCheckinLocked(Context context, PrintWriter pw, int which, int reqUid) { 1561 final long rawUptime = SystemClock.uptimeMillis() * 1000; 1562 final long rawRealtime = SystemClock.elapsedRealtime() * 1000; 1563 final long batteryUptime = getBatteryUptime(rawUptime); 1564 final long whichBatteryUptime = computeBatteryUptime(rawUptime, which); 1565 final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which); 1566 final long whichBatteryScreenOffUptime = computeBatteryScreenOffUptime(rawUptime, which); 1567 final long whichBatteryScreenOffRealtime = computeBatteryScreenOffRealtime(rawRealtime, 1568 which); 1569 final long totalRealtime = computeRealtime(rawRealtime, which); 1570 final long totalUptime = computeUptime(rawUptime, which); 1571 final long screenOnTime = getScreenOnTime(rawRealtime, which); 1572 final long phoneOnTime = getPhoneOnTime(rawRealtime, which); 1573 final long wifiOnTime = getWifiOnTime(rawRealtime, which); 1574 final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which); 1575 final long bluetoothOnTime = getBluetoothOnTime(rawRealtime, which); 1576 1577 StringBuilder sb = new StringBuilder(128); 1578 1579 SparseArray<? extends Uid> uidStats = getUidStats(); 1580 final int NU = uidStats.size(); 1581 1582 String category = STAT_NAMES[which]; 1583 1584 // Dump "battery" stat 1585 dumpLine(pw, 0 /* uid */, category, BATTERY_DATA, 1586 which == STATS_SINCE_CHARGED ? getStartCount() : "N/A", 1587 whichBatteryRealtime / 1000, whichBatteryUptime / 1000, 1588 totalRealtime / 1000, totalUptime / 1000, 1589 getStartClockTime(), 1590 whichBatteryScreenOffRealtime / 1000, whichBatteryScreenOffUptime / 1000); 1591 1592 // Calculate wakelock times across all uids. 1593 long fullWakeLockTimeTotal = 0; 1594 long partialWakeLockTimeTotal = 0; 1595 1596 for (int iu = 0; iu < NU; iu++) { 1597 Uid u = uidStats.valueAt(iu); 1598 1599 Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats(); 1600 if (wakelocks.size() > 0) { 1601 for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent 1602 : wakelocks.entrySet()) { 1603 Uid.Wakelock wl = ent.getValue(); 1604 1605 Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL); 1606 if (fullWakeTimer != null) { 1607 fullWakeLockTimeTotal += fullWakeTimer.getTotalTimeLocked(rawRealtime, 1608 which); 1609 } 1610 1611 Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL); 1612 if (partialWakeTimer != null) { 1613 partialWakeLockTimeTotal += partialWakeTimer.getTotalTimeLocked( 1614 rawRealtime, which); 1615 } 1616 } 1617 } 1618 } 1619 1620 long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which); 1621 long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which); 1622 long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which); 1623 long wifiTxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which); 1624 long mobileRxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which); 1625 long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which); 1626 long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which); 1627 long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which); 1628 1629 // Dump network stats 1630 dumpLine(pw, 0 /* uid */, category, GLOBAL_NETWORK_DATA, 1631 mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes, 1632 mobileRxTotalPackets, mobileTxTotalPackets, wifiRxTotalPackets, wifiTxTotalPackets); 1633 1634 // Dump misc stats 1635 dumpLine(pw, 0 /* uid */, category, MISC_DATA, 1636 screenOnTime / 1000, phoneOnTime / 1000, wifiOnTime / 1000, 1637 wifiRunningTime / 1000, bluetoothOnTime / 1000, 1638 mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes, 1639 fullWakeLockTimeTotal, partialWakeLockTimeTotal, 1640 getInputEventCount(which), getMobileRadioActiveTime(rawRealtime, which), 1641 getMobileRadioActiveAdjustedTime(which)); 1642 1643 // Dump screen brightness stats 1644 Object[] args = new Object[NUM_SCREEN_BRIGHTNESS_BINS]; 1645 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 1646 args[i] = getScreenBrightnessTime(i, rawRealtime, which) / 1000; 1647 } 1648 dumpLine(pw, 0 /* uid */, category, SCREEN_BRIGHTNESS_DATA, args); 1649 1650 // Dump signal strength stats 1651 args = new Object[SignalStrength.NUM_SIGNAL_STRENGTH_BINS]; 1652 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 1653 args[i] = getPhoneSignalStrengthTime(i, rawRealtime, which) / 1000; 1654 } 1655 dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_TIME_DATA, args); 1656 dumpLine(pw, 0 /* uid */, category, SIGNAL_SCANNING_TIME_DATA, 1657 getPhoneSignalScanningTime(rawRealtime, which) / 1000); 1658 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 1659 args[i] = getPhoneSignalStrengthCount(i, which); 1660 } 1661 dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_COUNT_DATA, args); 1662 1663 // Dump network type stats 1664 args = new Object[NUM_DATA_CONNECTION_TYPES]; 1665 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 1666 args[i] = getPhoneDataConnectionTime(i, rawRealtime, which) / 1000; 1667 } 1668 dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_TIME_DATA, args); 1669 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 1670 args[i] = getPhoneDataConnectionCount(i, which); 1671 } 1672 dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_COUNT_DATA, args); 1673 1674 // Dump wifi state stats 1675 args = new Object[NUM_WIFI_STATES]; 1676 for (int i=0; i<NUM_WIFI_STATES; i++) { 1677 args[i] = getWifiStateTime(i, rawRealtime, which) / 1000; 1678 } 1679 dumpLine(pw, 0 /* uid */, category, WIFI_STATE_TIME_DATA, args); 1680 for (int i=0; i<NUM_WIFI_STATES; i++) { 1681 args[i] = getWifiStateCount(i, which); 1682 } 1683 dumpLine(pw, 0 /* uid */, category, WIFI_STATE_COUNT_DATA, args); 1684 1685 // Dump bluetooth state stats 1686 args = new Object[NUM_BLUETOOTH_STATES]; 1687 for (int i=0; i<NUM_BLUETOOTH_STATES; i++) { 1688 args[i] = getBluetoothStateTime(i, rawRealtime, which) / 1000; 1689 } 1690 dumpLine(pw, 0 /* uid */, category, BLUETOOTH_STATE_TIME_DATA, args); 1691 for (int i=0; i<NUM_BLUETOOTH_STATES; i++) { 1692 args[i] = getBluetoothStateCount(i, which); 1693 } 1694 dumpLine(pw, 0 /* uid */, category, BLUETOOTH_STATE_COUNT_DATA, args); 1695 1696 if (which == STATS_SINCE_UNPLUGGED) { 1697 dumpLine(pw, 0 /* uid */, category, BATTERY_LEVEL_DATA, getDischargeStartLevel(), 1698 getDischargeCurrentLevel()); 1699 } 1700 1701 if (which == STATS_SINCE_UNPLUGGED) { 1702 dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA, 1703 getDischargeStartLevel()-getDischargeCurrentLevel(), 1704 getDischargeStartLevel()-getDischargeCurrentLevel(), 1705 getDischargeAmountScreenOn(), getDischargeAmountScreenOff()); 1706 } else { 1707 dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA, 1708 getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(), 1709 getDischargeAmountScreenOn(), getDischargeAmountScreenOff()); 1710 } 1711 1712 if (reqUid < 0) { 1713 Map<String, ? extends Timer> kernelWakelocks = getKernelWakelockStats(); 1714 if (kernelWakelocks.size() > 0) { 1715 for (Map.Entry<String, ? extends Timer> ent : kernelWakelocks.entrySet()) { 1716 sb.setLength(0); 1717 printWakeLockCheckin(sb, ent.getValue(), rawRealtime, null, which, ""); 1718 dumpLine(pw, 0 /* uid */, category, KERNEL_WAKELOCK_DATA, ent.getKey(), 1719 sb.toString()); 1720 } 1721 } 1722 Map<String, ? extends LongCounter> wakeupReasons = getWakeupReasonStats(); 1723 if (wakeupReasons.size() > 0) { 1724 for (Map.Entry<String, ? extends LongCounter> ent : wakeupReasons.entrySet()) { 1725 dumpLine(pw, 0 /* uid */, category, WAKEUP_REASON_DATA, 1726 "\"" + ent.getKey() + "\"", ent.getValue().getCountLocked(which)); 1727 } 1728 } 1729 } 1730 1731 BatteryStatsHelper helper = new BatteryStatsHelper(context, false); 1732 helper.create(this); 1733 helper.refreshStats(which, UserHandle.USER_ALL); 1734 List<BatterySipper> sippers = helper.getUsageList(); 1735 if (sippers != null && sippers.size() > 0) { 1736 dumpLine(pw, 0 /* uid */, category, POWER_USE_SUMMARY_DATA, 1737 BatteryStatsHelper.makemAh(helper.getPowerProfile().getBatteryCapacity()), 1738 BatteryStatsHelper.makemAh(helper.getComputedPower()), 1739 BatteryStatsHelper.makemAh(helper.getMinDrainedPower()), 1740 BatteryStatsHelper.makemAh(helper.getMaxDrainedPower())); 1741 for (int i=0; i<sippers.size(); i++) { 1742 BatterySipper bs = sippers.get(i); 1743 int uid = 0; 1744 String label; 1745 switch (bs.drainType) { 1746 case IDLE: 1747 label="idle"; 1748 break; 1749 case CELL: 1750 label="cell"; 1751 break; 1752 case PHONE: 1753 label="phone"; 1754 break; 1755 case WIFI: 1756 label="wifi"; 1757 break; 1758 case BLUETOOTH: 1759 label="blue"; 1760 break; 1761 case SCREEN: 1762 label="scrn"; 1763 break; 1764 case APP: 1765 uid = bs.uidObj.getUid(); 1766 label = "uid"; 1767 break; 1768 case USER: 1769 uid = UserHandle.getUid(bs.userId, 0); 1770 label = "user"; 1771 break; 1772 case UNACCOUNTED: 1773 label = "unacc"; 1774 break; 1775 case OVERCOUNTED: 1776 label = "over"; 1777 break; 1778 default: 1779 label = "???"; 1780 } 1781 dumpLine(pw, uid, category, POWER_USE_ITEM_DATA, label, 1782 BatteryStatsHelper.makemAh(bs.value)); 1783 } 1784 } 1785 1786 for (int iu = 0; iu < NU; iu++) { 1787 final int uid = uidStats.keyAt(iu); 1788 if (reqUid >= 0 && uid != reqUid) { 1789 continue; 1790 } 1791 Uid u = uidStats.valueAt(iu); 1792 // Dump Network stats per uid, if any 1793 long mobileBytesRx = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which); 1794 long mobileBytesTx = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which); 1795 long wifiBytesRx = u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which); 1796 long wifiBytesTx = u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which); 1797 long mobilePacketsRx = u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which); 1798 long mobilePacketsTx = u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which); 1799 long mobileActiveTime = u.getMobileRadioActiveTime(which); 1800 int mobileActiveCount = u.getMobileRadioActiveCount(which); 1801 long wifiPacketsRx = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which); 1802 long wifiPacketsTx = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which); 1803 long fullWifiLockOnTime = u.getFullWifiLockTime(rawRealtime, which); 1804 long wifiScanTime = u.getWifiScanTime(rawRealtime, which); 1805 long uidWifiRunningTime = u.getWifiRunningTime(rawRealtime, which); 1806 1807 if (mobileBytesRx > 0 || mobileBytesTx > 0 || wifiBytesRx > 0 || wifiBytesTx > 0 1808 || mobilePacketsRx > 0 || mobilePacketsTx > 0 || wifiPacketsRx > 0 1809 || wifiPacketsTx > 0 || mobileActiveTime > 0 || mobileActiveCount > 0) { 1810 dumpLine(pw, uid, category, NETWORK_DATA, mobileBytesRx, mobileBytesTx, 1811 wifiBytesRx, wifiBytesTx, 1812 mobilePacketsRx, mobilePacketsTx, 1813 wifiPacketsRx, wifiPacketsTx, 1814 mobileActiveTime, mobileActiveCount); 1815 } 1816 1817 if (fullWifiLockOnTime != 0 || wifiScanTime != 0 1818 || uidWifiRunningTime != 0) { 1819 dumpLine(pw, uid, category, WIFI_DATA, 1820 fullWifiLockOnTime, wifiScanTime, uidWifiRunningTime); 1821 } 1822 1823 if (u.hasUserActivity()) { 1824 args = new Object[Uid.NUM_USER_ACTIVITY_TYPES]; 1825 boolean hasData = false; 1826 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) { 1827 int val = u.getUserActivityCount(i, which); 1828 args[i] = val; 1829 if (val != 0) hasData = true; 1830 } 1831 if (hasData) { 1832 dumpLine(pw, 0 /* uid */, category, USER_ACTIVITY_DATA, args); 1833 } 1834 } 1835 1836 Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats(); 1837 if (wakelocks.size() > 0) { 1838 for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent 1839 : wakelocks.entrySet()) { 1840 Uid.Wakelock wl = ent.getValue(); 1841 String linePrefix = ""; 1842 sb.setLength(0); 1843 linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL), 1844 rawRealtime, "f", which, linePrefix); 1845 linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), 1846 rawRealtime, "p", which, linePrefix); 1847 linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), 1848 rawRealtime, "w", which, linePrefix); 1849 1850 // Only log if we had at lease one wakelock... 1851 if (sb.length() > 0) { 1852 String name = ent.getKey(); 1853 if (name.indexOf(',') >= 0) { 1854 name = name.replace(',', '_'); 1855 } 1856 dumpLine(pw, uid, category, WAKELOCK_DATA, name, sb.toString()); 1857 } 1858 } 1859 } 1860 1861 Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats(); 1862 if (sensors.size() > 0) { 1863 for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent 1864 : sensors.entrySet()) { 1865 Uid.Sensor se = ent.getValue(); 1866 int sensorNumber = ent.getKey(); 1867 Timer timer = se.getSensorTime(); 1868 if (timer != null) { 1869 // Convert from microseconds to milliseconds with rounding 1870 long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000; 1871 int count = timer.getCountLocked(which); 1872 if (totalTime != 0) { 1873 dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count); 1874 } 1875 } 1876 } 1877 } 1878 1879 Timer vibTimer = u.getVibratorOnTimer(); 1880 if (vibTimer != null) { 1881 // Convert from microseconds to milliseconds with rounding 1882 long totalTime = (vibTimer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000; 1883 int count = vibTimer.getCountLocked(which); 1884 if (totalTime != 0) { 1885 dumpLine(pw, uid, category, VIBRATOR_DATA, totalTime, count); 1886 } 1887 } 1888 1889 Timer fgTimer = u.getForegroundActivityTimer(); 1890 if (fgTimer != null) { 1891 // Convert from microseconds to milliseconds with rounding 1892 long totalTime = (fgTimer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000; 1893 int count = fgTimer.getCountLocked(which); 1894 if (totalTime != 0) { 1895 dumpLine(pw, uid, category, FOREGROUND_DATA, totalTime, count); 1896 } 1897 } 1898 1899 Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats(); 1900 if (processStats.size() > 0) { 1901 for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent 1902 : processStats.entrySet()) { 1903 Uid.Proc ps = ent.getValue(); 1904 1905 final long userMillis = ps.getUserTime(which) * 10; 1906 final long systemMillis = ps.getSystemTime(which) * 10; 1907 final long foregroundMillis = ps.getForegroundTime(which) * 10; 1908 final long starts = ps.getStarts(which); 1909 1910 if (userMillis != 0 || systemMillis != 0 || foregroundMillis != 0 1911 || starts != 0) { 1912 dumpLine(pw, uid, category, PROCESS_DATA, ent.getKey(), userMillis, 1913 systemMillis, foregroundMillis, starts); 1914 } 1915 } 1916 } 1917 1918 Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats(); 1919 if (packageStats.size() > 0) { 1920 for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent 1921 : packageStats.entrySet()) { 1922 1923 Uid.Pkg ps = ent.getValue(); 1924 int wakeups = ps.getWakeups(which); 1925 Map<String, ? extends Uid.Pkg.Serv> serviceStats = ps.getServiceStats(); 1926 for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent 1927 : serviceStats.entrySet()) { 1928 BatteryStats.Uid.Pkg.Serv ss = sent.getValue(); 1929 long startTime = ss.getStartTime(batteryUptime, which); 1930 int starts = ss.getStarts(which); 1931 int launches = ss.getLaunches(which); 1932 if (startTime != 0 || starts != 0 || launches != 0) { 1933 dumpLine(pw, uid, category, APK_DATA, 1934 wakeups, // wakeup alarms 1935 ent.getKey(), // Apk 1936 sent.getKey(), // service 1937 startTime / 1000, // time spent started, in ms 1938 starts, 1939 launches); 1940 } 1941 } 1942 } 1943 } 1944 } 1945 } 1946 1947 static final class TimerEntry { 1948 final String mName; 1949 final int mId; 1950 final BatteryStats.Timer mTimer; 1951 final long mTime; 1952 TimerEntry(String name, int id, BatteryStats.Timer timer, long time) { 1953 mName = name; 1954 mId = id; 1955 mTimer = timer; 1956 mTime = time; 1957 } 1958 } 1959 1960 private void printmAh(PrintWriter printer, double power) { 1961 printer.print(BatteryStatsHelper.makemAh(power)); 1962 } 1963 1964 @SuppressWarnings("unused") 1965 public final void dumpLocked(Context context, PrintWriter pw, String prefix, final int which, 1966 int reqUid) { 1967 final long rawUptime = SystemClock.uptimeMillis() * 1000; 1968 final long rawRealtime = SystemClock.elapsedRealtime() * 1000; 1969 final long batteryUptime = getBatteryUptime(rawUptime); 1970 1971 final long whichBatteryUptime = computeBatteryUptime(rawUptime, which); 1972 final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which); 1973 final long totalRealtime = computeRealtime(rawRealtime, which); 1974 final long totalUptime = computeUptime(rawUptime, which); 1975 final long whichBatteryScreenOffUptime = computeBatteryScreenOffUptime(rawUptime, which); 1976 final long whichBatteryScreenOffRealtime = computeBatteryScreenOffRealtime(rawRealtime, 1977 which); 1978 final long batteryTimeRemaining = computeBatteryTimeRemaining(rawRealtime); 1979 final long chargeTimeRemaining = computeChargeTimeRemaining(rawRealtime); 1980 1981 StringBuilder sb = new StringBuilder(128); 1982 1983 SparseArray<? extends Uid> uidStats = getUidStats(); 1984 final int NU = uidStats.size(); 1985 1986 sb.setLength(0); 1987 sb.append(prefix); 1988 sb.append(" Time on battery: "); 1989 formatTimeMs(sb, whichBatteryRealtime / 1000); sb.append("("); 1990 sb.append(formatRatioLocked(whichBatteryRealtime, totalRealtime)); 1991 sb.append(") realtime, "); 1992 formatTimeMs(sb, whichBatteryUptime / 1000); 1993 sb.append("("); sb.append(formatRatioLocked(whichBatteryUptime, totalRealtime)); 1994 sb.append(") uptime"); 1995 pw.println(sb.toString()); 1996 sb.setLength(0); 1997 sb.append(prefix); 1998 sb.append(" Time on battery screen off: "); 1999 formatTimeMs(sb, whichBatteryScreenOffRealtime / 1000); sb.append("("); 2000 sb.append(formatRatioLocked(whichBatteryScreenOffRealtime, totalRealtime)); 2001 sb.append(") realtime, "); 2002 formatTimeMs(sb, whichBatteryScreenOffUptime / 1000); 2003 sb.append("("); 2004 sb.append(formatRatioLocked(whichBatteryScreenOffUptime, totalRealtime)); 2005 sb.append(") uptime"); 2006 pw.println(sb.toString()); 2007 sb.setLength(0); 2008 sb.append(prefix); 2009 sb.append(" Total run time: "); 2010 formatTimeMs(sb, totalRealtime / 1000); 2011 sb.append("realtime, "); 2012 formatTimeMs(sb, totalUptime / 1000); 2013 sb.append("uptime"); 2014 if (batteryTimeRemaining >= 0) { 2015 sb.setLength(0); 2016 sb.append(prefix); 2017 sb.append(" Battery time remaining: "); 2018 formatTimeMs(sb, batteryTimeRemaining / 1000); 2019 pw.println(sb.toString()); 2020 } 2021 if (chargeTimeRemaining >= 0) { 2022 sb.setLength(0); 2023 sb.append(prefix); 2024 sb.append(" Charge time remaining: "); 2025 formatTimeMs(sb, chargeTimeRemaining / 1000); 2026 pw.println(sb.toString()); 2027 } 2028 pw.print(" Start clock time: "); 2029 pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss", getStartClockTime()).toString()); 2030 2031 final long screenOnTime = getScreenOnTime(rawRealtime, which); 2032 final long phoneOnTime = getPhoneOnTime(rawRealtime, which); 2033 final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which); 2034 final long wifiOnTime = getWifiOnTime(rawRealtime, which); 2035 final long bluetoothOnTime = getBluetoothOnTime(rawRealtime, which); 2036 sb.setLength(0); 2037 sb.append(prefix); 2038 sb.append(" Screen on: "); formatTimeMs(sb, screenOnTime / 1000); 2039 sb.append("("); sb.append(formatRatioLocked(screenOnTime, whichBatteryRealtime)); 2040 sb.append(") "); sb.append(getScreenOnCount(which)); 2041 sb.append("x, Input events: "); sb.append(getInputEventCount(which)); 2042 pw.println(sb.toString()); 2043 if (phoneOnTime != 0) { 2044 sb.setLength(0); 2045 sb.append(prefix); 2046 sb.append(" Active phone call: "); formatTimeMs(sb, phoneOnTime / 1000); 2047 sb.append("("); sb.append(formatRatioLocked(phoneOnTime, whichBatteryRealtime)); 2048 sb.append(") "); sb.append(getPhoneOnCount(which)); 2049 } 2050 sb.setLength(0); 2051 sb.append(prefix); 2052 sb.append(" Screen brightnesses:"); 2053 boolean didOne = false; 2054 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 2055 final long time = getScreenBrightnessTime(i, rawRealtime, which); 2056 if (time == 0) { 2057 continue; 2058 } 2059 sb.append("\n "); 2060 sb.append(prefix); 2061 didOne = true; 2062 sb.append(SCREEN_BRIGHTNESS_NAMES[i]); 2063 sb.append(" "); 2064 formatTimeMs(sb, time/1000); 2065 sb.append("("); 2066 sb.append(formatRatioLocked(time, screenOnTime)); 2067 sb.append(")"); 2068 } 2069 if (!didOne) sb.append(" (no activity)"); 2070 pw.println(sb.toString()); 2071 2072 // Calculate wakelock times across all uids. 2073 long fullWakeLockTimeTotalMicros = 0; 2074 long partialWakeLockTimeTotalMicros = 0; 2075 2076 final ArrayList<TimerEntry> timers = new ArrayList<TimerEntry>(); 2077 2078 for (int iu = 0; iu < NU; iu++) { 2079 Uid u = uidStats.valueAt(iu); 2080 2081 Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats(); 2082 if (wakelocks.size() > 0) { 2083 for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent 2084 : wakelocks.entrySet()) { 2085 Uid.Wakelock wl = ent.getValue(); 2086 2087 Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL); 2088 if (fullWakeTimer != null) { 2089 fullWakeLockTimeTotalMicros += fullWakeTimer.getTotalTimeLocked( 2090 rawRealtime, which); 2091 } 2092 2093 Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL); 2094 if (partialWakeTimer != null) { 2095 long totalTimeMicros = partialWakeTimer.getTotalTimeLocked( 2096 rawRealtime, which); 2097 if (totalTimeMicros > 0) { 2098 if (reqUid < 0) { 2099 // Only show the ordered list of all wake 2100 // locks if the caller is not asking for data 2101 // about a specific uid. 2102 timers.add(new TimerEntry(ent.getKey(), u.getUid(), 2103 partialWakeTimer, totalTimeMicros)); 2104 } 2105 partialWakeLockTimeTotalMicros += totalTimeMicros; 2106 } 2107 } 2108 } 2109 } 2110 } 2111 2112 long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which); 2113 long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which); 2114 long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which); 2115 long wifiTxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which); 2116 long mobileRxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which); 2117 long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which); 2118 long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which); 2119 long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which); 2120 2121 if (fullWakeLockTimeTotalMicros != 0) { 2122 sb.setLength(0); 2123 sb.append(prefix); 2124 sb.append(" Total full wakelock time: "); formatTimeMsNoSpace(sb, 2125 (fullWakeLockTimeTotalMicros + 500) / 1000); 2126 pw.println(sb.toString()); 2127 } 2128 2129 if (partialWakeLockTimeTotalMicros != 0) { 2130 sb.setLength(0); 2131 sb.append(prefix); 2132 sb.append(" Total partial wakelock time: "); formatTimeMsNoSpace(sb, 2133 (partialWakeLockTimeTotalMicros + 500) / 1000); 2134 pw.println(sb.toString()); 2135 } 2136 2137 pw.print(prefix); 2138 pw.print(" Mobile total received: "); pw.print(formatBytesLocked(mobileRxTotalBytes)); 2139 pw.print(", sent: "); pw.print(formatBytesLocked(mobileTxTotalBytes)); 2140 pw.print(" (packets received "); pw.print(mobileRxTotalPackets); 2141 pw.print(", sent "); pw.print(mobileTxTotalPackets); pw.println(")"); 2142 sb.setLength(0); 2143 sb.append(prefix); 2144 sb.append(" Signal levels:"); 2145 didOne = false; 2146 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 2147 final long time = getPhoneSignalStrengthTime(i, rawRealtime, which); 2148 if (time == 0) { 2149 continue; 2150 } 2151 sb.append("\n "); 2152 sb.append(prefix); 2153 didOne = true; 2154 sb.append(SignalStrength.SIGNAL_STRENGTH_NAMES[i]); 2155 sb.append(" "); 2156 formatTimeMs(sb, time/1000); 2157 sb.append("("); 2158 sb.append(formatRatioLocked(time, whichBatteryRealtime)); 2159 sb.append(") "); 2160 sb.append(getPhoneSignalStrengthCount(i, which)); 2161 sb.append("x"); 2162 } 2163 if (!didOne) sb.append(" (no activity)"); 2164 pw.println(sb.toString()); 2165 2166 sb.setLength(0); 2167 sb.append(prefix); 2168 sb.append(" Signal scanning time: "); 2169 formatTimeMsNoSpace(sb, getPhoneSignalScanningTime(rawRealtime, which) / 1000); 2170 pw.println(sb.toString()); 2171 2172 sb.setLength(0); 2173 sb.append(prefix); 2174 sb.append(" Radio types:"); 2175 didOne = false; 2176 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 2177 final long time = getPhoneDataConnectionTime(i, rawRealtime, which); 2178 if (time == 0) { 2179 continue; 2180 } 2181 sb.append("\n "); 2182 sb.append(prefix); 2183 didOne = true; 2184 sb.append(DATA_CONNECTION_NAMES[i]); 2185 sb.append(" "); 2186 formatTimeMs(sb, time/1000); 2187 sb.append("("); 2188 sb.append(formatRatioLocked(time, whichBatteryRealtime)); 2189 sb.append(") "); 2190 sb.append(getPhoneDataConnectionCount(i, which)); 2191 sb.append("x"); 2192 } 2193 if (!didOne) sb.append(" (no activity)"); 2194 pw.println(sb.toString()); 2195 2196 sb.setLength(0); 2197 sb.append(prefix); 2198 sb.append(" Mobile radio active time: "); 2199 final long mobileActiveTime = getMobileRadioActiveTime(rawRealtime, which); 2200 formatTimeMs(sb, mobileActiveTime / 1000); 2201 sb.append("("); sb.append(formatRatioLocked(mobileActiveTime, whichBatteryRealtime)); 2202 sb.append(") "); sb.append(getMobileRadioActiveCount(which)); 2203 sb.append("x"); 2204 pw.println(sb.toString()); 2205 2206 final long mobileActiveUnknownTime = getMobileRadioActiveUnknownTime(which); 2207 if (mobileActiveUnknownTime != 0) { 2208 sb.setLength(0); 2209 sb.append(prefix); 2210 sb.append(" Mobile radio active unknown time: "); 2211 formatTimeMs(sb, mobileActiveUnknownTime / 1000); 2212 sb.append("("); 2213 sb.append(formatRatioLocked(mobileActiveUnknownTime, whichBatteryRealtime)); 2214 sb.append(") "); sb.append(getMobileRadioActiveUnknownCount(which)); 2215 sb.append("x"); 2216 pw.println(sb.toString()); 2217 } 2218 2219 final long mobileActiveAdjustedTime = getMobileRadioActiveAdjustedTime(which); 2220 if (mobileActiveAdjustedTime != 0) { 2221 sb.setLength(0); 2222 sb.append(prefix); 2223 sb.append(" Mobile radio active adjusted time: "); 2224 formatTimeMs(sb, mobileActiveAdjustedTime / 1000); 2225 sb.append("("); 2226 sb.append(formatRatioLocked(mobileActiveAdjustedTime, whichBatteryRealtime)); 2227 sb.append(")"); 2228 pw.println(sb.toString()); 2229 } 2230 2231 pw.print(prefix); 2232 pw.print(" Wi-Fi total received: "); pw.print(formatBytesLocked(wifiRxTotalBytes)); 2233 pw.print(", sent: "); pw.print(formatBytesLocked(wifiTxTotalBytes)); 2234 pw.print(" (packets received "); pw.print(wifiRxTotalPackets); 2235 pw.print(", sent "); pw.print(wifiTxTotalPackets); pw.println(")"); 2236 sb.setLength(0); 2237 sb.append(prefix); 2238 sb.append(" Wifi on: "); formatTimeMs(sb, wifiOnTime / 1000); 2239 sb.append("("); sb.append(formatRatioLocked(wifiOnTime, whichBatteryRealtime)); 2240 sb.append("), Wifi running: "); formatTimeMs(sb, wifiRunningTime / 1000); 2241 sb.append("("); sb.append(formatRatioLocked(wifiRunningTime, whichBatteryRealtime)); 2242 sb.append(")"); 2243 pw.println(sb.toString()); 2244 2245 sb.setLength(0); 2246 sb.append(prefix); 2247 sb.append(" Wifi states:"); 2248 didOne = false; 2249 for (int i=0; i<NUM_WIFI_STATES; i++) { 2250 final long time = getWifiStateTime(i, rawRealtime, which); 2251 if (time == 0) { 2252 continue; 2253 } 2254 sb.append("\n "); 2255 didOne = true; 2256 sb.append(WIFI_STATE_NAMES[i]); 2257 sb.append(" "); 2258 formatTimeMs(sb, time/1000); 2259 sb.append("("); 2260 sb.append(formatRatioLocked(time, whichBatteryRealtime)); 2261 sb.append(") "); 2262 sb.append(getPhoneDataConnectionCount(i, which)); 2263 sb.append("x"); 2264 } 2265 if (!didOne) sb.append(" (no activity)"); 2266 pw.println(sb.toString()); 2267 2268 sb.setLength(0); 2269 sb.append(prefix); 2270 sb.append(" Bluetooth on: "); formatTimeMs(sb, bluetoothOnTime / 1000); 2271 sb.append("("); sb.append(formatRatioLocked(bluetoothOnTime, whichBatteryRealtime)); 2272 sb.append(")"); 2273 pw.println(sb.toString()); 2274 2275 sb.setLength(0); 2276 sb.append(prefix); 2277 sb.append(" Bluetooth states:"); 2278 didOne = false; 2279 for (int i=0; i<NUM_BLUETOOTH_STATES; i++) { 2280 final long time = getBluetoothStateTime(i, rawRealtime, which); 2281 if (time == 0) { 2282 continue; 2283 } 2284 sb.append("\n "); 2285 didOne = true; 2286 sb.append(BLUETOOTH_STATE_NAMES[i]); 2287 sb.append(" "); 2288 formatTimeMs(sb, time/1000); 2289 sb.append("("); 2290 sb.append(formatRatioLocked(time, whichBatteryRealtime)); 2291 sb.append(") "); 2292 sb.append(getPhoneDataConnectionCount(i, which)); 2293 sb.append("x"); 2294 } 2295 if (!didOne) sb.append(" (no activity)"); 2296 pw.println(sb.toString()); 2297 2298 pw.println(); 2299 2300 if (which == STATS_SINCE_UNPLUGGED) { 2301 if (getIsOnBattery()) { 2302 pw.print(prefix); pw.println(" Device is currently unplugged"); 2303 pw.print(prefix); pw.print(" Discharge cycle start level: "); 2304 pw.println(getDischargeStartLevel()); 2305 pw.print(prefix); pw.print(" Discharge cycle current level: "); 2306 pw.println(getDischargeCurrentLevel()); 2307 } else { 2308 pw.print(prefix); pw.println(" Device is currently plugged into power"); 2309 pw.print(prefix); pw.print(" Last discharge cycle start level: "); 2310 pw.println(getDischargeStartLevel()); 2311 pw.print(prefix); pw.print(" Last discharge cycle end level: "); 2312 pw.println(getDischargeCurrentLevel()); 2313 } 2314 pw.print(prefix); pw.print(" Amount discharged while screen on: "); 2315 pw.println(getDischargeAmountScreenOn()); 2316 pw.print(prefix); pw.print(" Amount discharged while screen off: "); 2317 pw.println(getDischargeAmountScreenOff()); 2318 pw.println(" "); 2319 } else { 2320 pw.print(prefix); pw.println(" Device battery use since last full charge"); 2321 pw.print(prefix); pw.print(" Amount discharged (lower bound): "); 2322 pw.println(getLowDischargeAmountSinceCharge()); 2323 pw.print(prefix); pw.print(" Amount discharged (upper bound): "); 2324 pw.println(getHighDischargeAmountSinceCharge()); 2325 pw.print(prefix); pw.print(" Amount discharged while screen on: "); 2326 pw.println(getDischargeAmountScreenOnSinceCharge()); 2327 pw.print(prefix); pw.print(" Amount discharged while screen off: "); 2328 pw.println(getDischargeAmountScreenOffSinceCharge()); 2329 pw.println(); 2330 } 2331 2332 BatteryStatsHelper helper = new BatteryStatsHelper(context, false); 2333 helper.create(this); 2334 helper.refreshStats(which, UserHandle.USER_ALL); 2335 List<BatterySipper> sippers = helper.getUsageList(); 2336 if (sippers != null && sippers.size() > 0) { 2337 pw.print(prefix); pw.println(" Estimated power use (mAh):"); 2338 pw.print(prefix); pw.print(" Capacity: "); 2339 printmAh(pw, helper.getPowerProfile().getBatteryCapacity()); 2340 pw.print(", Computed drain: "); printmAh(pw, helper.getComputedPower()); 2341 pw.print(", Min drain: "); printmAh(pw, helper.getMinDrainedPower()); 2342 pw.print(", Max drain: "); printmAh(pw, helper.getMaxDrainedPower()); 2343 pw.println(); 2344 for (int i=0; i<sippers.size(); i++) { 2345 BatterySipper bs = sippers.get(i); 2346 switch (bs.drainType) { 2347 case IDLE: 2348 pw.print(prefix); pw.print(" Idle: "); printmAh(pw, bs.value); 2349 pw.println(); 2350 break; 2351 case CELL: 2352 pw.print(prefix); pw.print(" Cell standby: "); printmAh(pw, bs.value); 2353 pw.println(); 2354 break; 2355 case PHONE: 2356 pw.print(prefix); pw.print(" Phone calls: "); printmAh(pw, bs.value); 2357 pw.println(); 2358 break; 2359 case WIFI: 2360 pw.print(prefix); pw.print(" Wifi: "); printmAh(pw, bs.value); 2361 pw.println(); 2362 break; 2363 case BLUETOOTH: 2364 pw.print(prefix); pw.print(" Bluetooth: "); printmAh(pw, bs.value); 2365 pw.println(); 2366 break; 2367 case SCREEN: 2368 pw.print(prefix); pw.print(" Screen: "); printmAh(pw, bs.value); 2369 pw.println(); 2370 break; 2371 case APP: 2372 pw.print(prefix); pw.print(" Uid "); 2373 UserHandle.formatUid(pw, bs.uidObj.getUid()); 2374 pw.print(": "); printmAh(pw, bs.value); pw.println(); 2375 break; 2376 case USER: 2377 pw.print(prefix); pw.print(" User "); pw.print(bs.userId); 2378 pw.print(": "); printmAh(pw, bs.value); pw.println(); 2379 break; 2380 case UNACCOUNTED: 2381 pw.print(prefix); pw.print(" Unaccounted: "); printmAh(pw, bs.value); 2382 pw.println(); 2383 break; 2384 case OVERCOUNTED: 2385 pw.print(prefix); pw.print(" Over-counted: "); printmAh(pw, bs.value); 2386 pw.println(); 2387 break; 2388 } 2389 } 2390 pw.println(); 2391 } 2392 2393 sippers = helper.getMobilemsppList(); 2394 if (sippers != null && sippers.size() > 0) { 2395 pw.print(prefix); pw.println(" Per-app mobile ms per packet:"); 2396 long totalTime = 0; 2397 for (int i=0; i<sippers.size(); i++) { 2398 BatterySipper bs = sippers.get(i); 2399 sb.setLength(0); 2400 sb.append(prefix); sb.append(" Uid "); 2401 UserHandle.formatUid(sb, bs.uidObj.getUid()); 2402 sb.append(": "); sb.append(BatteryStatsHelper.makemAh(bs.mobilemspp)); 2403 sb.append(" ("); sb.append(bs.mobileRxPackets+bs.mobileTxPackets); 2404 sb.append(" packets over "); formatTimeMsNoSpace(sb, bs.mobileActive); 2405 sb.append(") "); sb.append(bs.mobileActiveCount); sb.append("x"); 2406 pw.println(sb.toString()); 2407 totalTime += bs.mobileActive; 2408 } 2409 sb.setLength(0); 2410 sb.append(prefix); 2411 sb.append(" TOTAL TIME: "); 2412 formatTimeMs(sb, totalTime); 2413 sb.append("("); sb.append(formatRatioLocked(totalTime, whichBatteryRealtime)); 2414 sb.append(")"); 2415 pw.println(sb.toString()); 2416 pw.println(); 2417 } 2418 2419 final Comparator<TimerEntry> timerComparator = new Comparator<TimerEntry>() { 2420 @Override 2421 public int compare(TimerEntry lhs, TimerEntry rhs) { 2422 long lhsTime = lhs.mTime; 2423 long rhsTime = rhs.mTime; 2424 if (lhsTime < rhsTime) { 2425 return 1; 2426 } 2427 if (lhsTime > rhsTime) { 2428 return -1; 2429 } 2430 return 0; 2431 } 2432 }; 2433 2434 if (reqUid < 0) { 2435 Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats(); 2436 if (kernelWakelocks.size() > 0) { 2437 final ArrayList<TimerEntry> ktimers = new ArrayList<TimerEntry>(); 2438 for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) { 2439 BatteryStats.Timer timer = ent.getValue(); 2440 long totalTimeMillis = computeWakeLock(timer, rawRealtime, which); 2441 if (totalTimeMillis > 0) { 2442 ktimers.add(new TimerEntry(ent.getKey(), 0, timer, totalTimeMillis)); 2443 } 2444 } 2445 if (ktimers.size() > 0) { 2446 Collections.sort(ktimers, timerComparator); 2447 pw.print(prefix); pw.println(" All kernel wake locks:"); 2448 for (int i=0; i<ktimers.size(); i++) { 2449 TimerEntry timer = ktimers.get(i); 2450 String linePrefix = ": "; 2451 sb.setLength(0); 2452 sb.append(prefix); 2453 sb.append(" Kernel Wake lock "); 2454 sb.append(timer.mName); 2455 linePrefix = printWakeLock(sb, timer.mTimer, rawRealtime, null, 2456 which, linePrefix); 2457 if (!linePrefix.equals(": ")) { 2458 sb.append(" realtime"); 2459 // Only print out wake locks that were held 2460 pw.println(sb.toString()); 2461 } 2462 } 2463 pw.println(); 2464 } 2465 } 2466 2467 if (timers.size() > 0) { 2468 Collections.sort(timers, timerComparator); 2469 pw.print(prefix); pw.println(" All partial wake locks:"); 2470 for (int i=0; i<timers.size(); i++) { 2471 TimerEntry timer = timers.get(i); 2472 sb.setLength(0); 2473 sb.append(" Wake lock "); 2474 UserHandle.formatUid(sb, timer.mId); 2475 sb.append(" "); 2476 sb.append(timer.mName); 2477 printWakeLock(sb, timer.mTimer, rawRealtime, null, which, ": "); 2478 sb.append(" realtime"); 2479 pw.println(sb.toString()); 2480 } 2481 timers.clear(); 2482 pw.println(); 2483 } 2484 2485 Map<String, ? extends LongCounter> wakeupReasons = getWakeupReasonStats(); 2486 if (wakeupReasons.size() > 0) { 2487 pw.print(prefix); pw.println(" All wakeup reasons:"); 2488 final ArrayList<TimerEntry> reasons = new ArrayList<TimerEntry>(); 2489 for (Map.Entry<String, ? extends LongCounter> ent : wakeupReasons.entrySet()) { 2490 BatteryStats.LongCounter counter = ent.getValue(); 2491 reasons.add(new TimerEntry(ent.getKey(), 0, null, 2492 ent.getValue().getCountLocked(which))); 2493 } 2494 Collections.sort(reasons, timerComparator); 2495 for (int i=0; i<reasons.size(); i++) { 2496 TimerEntry timer = reasons.get(i); 2497 String linePrefix = ": "; 2498 sb.setLength(0); 2499 sb.append(prefix); 2500 sb.append(" Wakeup reason "); 2501 sb.append(timer.mName); 2502 sb.append(": "); 2503 formatTimeMs(sb, timer.mTime); 2504 sb.append("realtime"); 2505 pw.println(sb.toString()); 2506 } 2507 pw.println(); 2508 } 2509 } 2510 2511 for (int iu=0; iu<NU; iu++) { 2512 final int uid = uidStats.keyAt(iu); 2513 if (reqUid >= 0 && uid != reqUid && uid != Process.SYSTEM_UID) { 2514 continue; 2515 } 2516 2517 Uid u = uidStats.valueAt(iu); 2518 2519 pw.print(prefix); 2520 pw.print(" "); 2521 UserHandle.formatUid(pw, uid); 2522 pw.println(":"); 2523 boolean uidActivity = false; 2524 2525 long mobileRxBytes = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which); 2526 long mobileTxBytes = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which); 2527 long wifiRxBytes = u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which); 2528 long wifiTxBytes = u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which); 2529 long mobileRxPackets = u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which); 2530 long mobileTxPackets = u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which); 2531 long uidMobileActiveTime = u.getMobileRadioActiveTime(which); 2532 int uidMobileActiveCount = u.getMobileRadioActiveCount(which); 2533 long wifiRxPackets = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which); 2534 long wifiTxPackets = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which); 2535 long fullWifiLockOnTime = u.getFullWifiLockTime(rawRealtime, which); 2536 long wifiScanTime = u.getWifiScanTime(rawRealtime, which); 2537 long uidWifiRunningTime = u.getWifiRunningTime(rawRealtime, which); 2538 2539 if (mobileRxBytes > 0 || mobileTxBytes > 0 2540 || mobileRxPackets > 0 || mobileTxPackets > 0) { 2541 pw.print(prefix); pw.print(" Mobile network: "); 2542 pw.print(formatBytesLocked(mobileRxBytes)); pw.print(" received, "); 2543 pw.print(formatBytesLocked(mobileTxBytes)); 2544 pw.print(" sent (packets "); pw.print(mobileRxPackets); 2545 pw.print(" received, "); pw.print(mobileTxPackets); pw.println(" sent)"); 2546 } 2547 if (uidMobileActiveTime > 0 || uidMobileActiveCount > 0) { 2548 sb.setLength(0); 2549 sb.append(prefix); sb.append(" Mobile radio active: "); 2550 formatTimeMs(sb, uidMobileActiveTime / 1000); 2551 sb.append("("); 2552 sb.append(formatRatioLocked(uidMobileActiveTime, mobileActiveTime)); 2553 sb.append(") "); sb.append(uidMobileActiveCount); sb.append("x"); 2554 long packets = mobileRxPackets + mobileTxPackets; 2555 if (packets == 0) { 2556 packets = 1; 2557 } 2558 sb.append(" @ "); 2559 sb.append(BatteryStatsHelper.makemAh(uidMobileActiveTime / 1000 / (double)packets)); 2560 sb.append(" mspp"); 2561 pw.println(sb.toString()); 2562 } 2563 2564 if (wifiRxBytes > 0 || wifiTxBytes > 0 || wifiRxPackets > 0 || wifiTxPackets > 0) { 2565 pw.print(prefix); pw.print(" Wi-Fi network: "); 2566 pw.print(formatBytesLocked(wifiRxBytes)); pw.print(" received, "); 2567 pw.print(formatBytesLocked(wifiTxBytes)); 2568 pw.print(" sent (packets "); pw.print(wifiRxPackets); 2569 pw.print(" received, "); pw.print(wifiTxPackets); pw.println(" sent)"); 2570 } 2571 2572 if (fullWifiLockOnTime != 0 || wifiScanTime != 0 2573 || uidWifiRunningTime != 0) { 2574 sb.setLength(0); 2575 sb.append(prefix); sb.append(" Wifi Running: "); 2576 formatTimeMs(sb, uidWifiRunningTime / 1000); 2577 sb.append("("); sb.append(formatRatioLocked(uidWifiRunningTime, 2578 whichBatteryRealtime)); sb.append(")\n"); 2579 sb.append(prefix); sb.append(" Full Wifi Lock: "); 2580 formatTimeMs(sb, fullWifiLockOnTime / 1000); 2581 sb.append("("); sb.append(formatRatioLocked(fullWifiLockOnTime, 2582 whichBatteryRealtime)); sb.append(")\n"); 2583 sb.append(prefix); sb.append(" Wifi Scan: "); 2584 formatTimeMs(sb, wifiScanTime / 1000); 2585 sb.append("("); sb.append(formatRatioLocked(wifiScanTime, 2586 whichBatteryRealtime)); sb.append(")"); 2587 pw.println(sb.toString()); 2588 } 2589 2590 if (u.hasUserActivity()) { 2591 boolean hasData = false; 2592 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) { 2593 int val = u.getUserActivityCount(i, which); 2594 if (val != 0) { 2595 if (!hasData) { 2596 sb.setLength(0); 2597 sb.append(" User activity: "); 2598 hasData = true; 2599 } else { 2600 sb.append(", "); 2601 } 2602 sb.append(val); 2603 sb.append(" "); 2604 sb.append(Uid.USER_ACTIVITY_TYPES[i]); 2605 } 2606 } 2607 if (hasData) { 2608 pw.println(sb.toString()); 2609 } 2610 } 2611 2612 Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats(); 2613 if (wakelocks.size() > 0) { 2614 long totalFull = 0, totalPartial = 0, totalWindow = 0; 2615 int count = 0; 2616 for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent 2617 : wakelocks.entrySet()) { 2618 Uid.Wakelock wl = ent.getValue(); 2619 String linePrefix = ": "; 2620 sb.setLength(0); 2621 sb.append(prefix); 2622 sb.append(" Wake lock "); 2623 sb.append(ent.getKey()); 2624 linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), rawRealtime, 2625 "full", which, linePrefix); 2626 linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), rawRealtime, 2627 "partial", which, linePrefix); 2628 linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), rawRealtime, 2629 "window", which, linePrefix); 2630 if (!linePrefix.equals(": ")) { 2631 sb.append(" realtime"); 2632 // Only print out wake locks that were held 2633 pw.println(sb.toString()); 2634 uidActivity = true; 2635 count++; 2636 } 2637 totalFull += computeWakeLock(wl.getWakeTime(WAKE_TYPE_FULL), 2638 rawRealtime, which); 2639 totalPartial += computeWakeLock(wl.getWakeTime(WAKE_TYPE_PARTIAL), 2640 rawRealtime, which); 2641 totalWindow += computeWakeLock(wl.getWakeTime(WAKE_TYPE_WINDOW), 2642 rawRealtime, which); 2643 } 2644 if (count > 1) { 2645 if (totalFull != 0 || totalPartial != 0 || totalWindow != 0) { 2646 sb.setLength(0); 2647 sb.append(prefix); 2648 sb.append(" TOTAL wake: "); 2649 boolean needComma = false; 2650 if (totalFull != 0) { 2651 needComma = true; 2652 formatTimeMs(sb, totalFull); 2653 sb.append("full"); 2654 } 2655 if (totalPartial != 0) { 2656 if (needComma) { 2657 sb.append(", "); 2658 } 2659 needComma = true; 2660 formatTimeMs(sb, totalPartial); 2661 sb.append("partial"); 2662 } 2663 if (totalWindow != 0) { 2664 if (needComma) { 2665 sb.append(", "); 2666 } 2667 needComma = true; 2668 formatTimeMs(sb, totalWindow); 2669 sb.append("window"); 2670 } 2671 sb.append(" realtime"); 2672 pw.println(sb.toString()); 2673 } 2674 } 2675 } 2676 2677 Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats(); 2678 if (sensors.size() > 0) { 2679 for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent 2680 : sensors.entrySet()) { 2681 Uid.Sensor se = ent.getValue(); 2682 int sensorNumber = ent.getKey(); 2683 sb.setLength(0); 2684 sb.append(prefix); 2685 sb.append(" Sensor "); 2686 int handle = se.getHandle(); 2687 if (handle == Uid.Sensor.GPS) { 2688 sb.append("GPS"); 2689 } else { 2690 sb.append(handle); 2691 } 2692 sb.append(": "); 2693 2694 Timer timer = se.getSensorTime(); 2695 if (timer != null) { 2696 // Convert from microseconds to milliseconds with rounding 2697 long totalTime = (timer.getTotalTimeLocked( 2698 rawRealtime, which) + 500) / 1000; 2699 int count = timer.getCountLocked(which); 2700 //timer.logState(); 2701 if (totalTime != 0) { 2702 formatTimeMs(sb, totalTime); 2703 sb.append("realtime ("); 2704 sb.append(count); 2705 sb.append(" times)"); 2706 } else { 2707 sb.append("(not used)"); 2708 } 2709 } else { 2710 sb.append("(not used)"); 2711 } 2712 2713 pw.println(sb.toString()); 2714 uidActivity = true; 2715 } 2716 } 2717 2718 Timer vibTimer = u.getVibratorOnTimer(); 2719 if (vibTimer != null) { 2720 // Convert from microseconds to milliseconds with rounding 2721 long totalTime = (vibTimer.getTotalTimeLocked( 2722 rawRealtime, which) + 500) / 1000; 2723 int count = vibTimer.getCountLocked(which); 2724 //timer.logState(); 2725 if (totalTime != 0) { 2726 sb.setLength(0); 2727 sb.append(prefix); 2728 sb.append(" Vibrator: "); 2729 formatTimeMs(sb, totalTime); 2730 sb.append("realtime ("); 2731 sb.append(count); 2732 sb.append(" times)"); 2733 pw.println(sb.toString()); 2734 uidActivity = true; 2735 } 2736 } 2737 2738 Timer fgTimer = u.getForegroundActivityTimer(); 2739 if (fgTimer != null) { 2740 // Convert from microseconds to milliseconds with rounding 2741 long totalTime = (fgTimer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000; 2742 int count = fgTimer.getCountLocked(which); 2743 if (totalTime != 0) { 2744 sb.setLength(0); 2745 sb.append(prefix); 2746 sb.append(" Foreground activities: "); 2747 formatTimeMs(sb, totalTime); 2748 sb.append("realtime ("); 2749 sb.append(count); 2750 sb.append(" times)"); 2751 pw.println(sb.toString()); 2752 uidActivity = true; 2753 } 2754 } 2755 2756 Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats(); 2757 if (processStats.size() > 0) { 2758 for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent 2759 : processStats.entrySet()) { 2760 Uid.Proc ps = ent.getValue(); 2761 long userTime; 2762 long systemTime; 2763 long foregroundTime; 2764 int starts; 2765 int numExcessive; 2766 2767 userTime = ps.getUserTime(which); 2768 systemTime = ps.getSystemTime(which); 2769 foregroundTime = ps.getForegroundTime(which); 2770 starts = ps.getStarts(which); 2771 numExcessive = which == STATS_SINCE_CHARGED 2772 ? ps.countExcessivePowers() : 0; 2773 2774 if (userTime != 0 || systemTime != 0 || foregroundTime != 0 || starts != 0 2775 || numExcessive != 0) { 2776 sb.setLength(0); 2777 sb.append(prefix); sb.append(" Proc "); 2778 sb.append(ent.getKey()); sb.append(":\n"); 2779 sb.append(prefix); sb.append(" CPU: "); 2780 formatTime(sb, userTime); sb.append("usr + "); 2781 formatTime(sb, systemTime); sb.append("krn ; "); 2782 formatTime(sb, foregroundTime); sb.append("fg"); 2783 if (starts != 0) { 2784 sb.append("\n"); sb.append(prefix); sb.append(" "); 2785 sb.append(starts); sb.append(" proc starts"); 2786 } 2787 pw.println(sb.toString()); 2788 for (int e=0; e<numExcessive; e++) { 2789 Uid.Proc.ExcessivePower ew = ps.getExcessivePower(e); 2790 if (ew != null) { 2791 pw.print(prefix); pw.print(" * Killed for "); 2792 if (ew.type == Uid.Proc.ExcessivePower.TYPE_WAKE) { 2793 pw.print("wake lock"); 2794 } else if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) { 2795 pw.print("cpu"); 2796 } else { 2797 pw.print("unknown"); 2798 } 2799 pw.print(" use: "); 2800 TimeUtils.formatDuration(ew.usedTime, pw); 2801 pw.print(" over "); 2802 TimeUtils.formatDuration(ew.overTime, pw); 2803 if (ew.overTime != 0) { 2804 pw.print(" ("); 2805 pw.print((ew.usedTime*100)/ew.overTime); 2806 pw.println("%)"); 2807 } 2808 } 2809 } 2810 uidActivity = true; 2811 } 2812 } 2813 } 2814 2815 Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats(); 2816 if (packageStats.size() > 0) { 2817 for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent 2818 : packageStats.entrySet()) { 2819 pw.print(prefix); pw.print(" Apk "); pw.print(ent.getKey()); pw.println(":"); 2820 boolean apkActivity = false; 2821 Uid.Pkg ps = ent.getValue(); 2822 int wakeups = ps.getWakeups(which); 2823 if (wakeups != 0) { 2824 pw.print(prefix); pw.print(" "); 2825 pw.print(wakeups); pw.println(" wakeup alarms"); 2826 apkActivity = true; 2827 } 2828 Map<String, ? extends Uid.Pkg.Serv> serviceStats = ps.getServiceStats(); 2829 if (serviceStats.size() > 0) { 2830 for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent 2831 : serviceStats.entrySet()) { 2832 BatteryStats.Uid.Pkg.Serv ss = sent.getValue(); 2833 long startTime = ss.getStartTime(batteryUptime, which); 2834 int starts = ss.getStarts(which); 2835 int launches = ss.getLaunches(which); 2836 if (startTime != 0 || starts != 0 || launches != 0) { 2837 sb.setLength(0); 2838 sb.append(prefix); sb.append(" Service "); 2839 sb.append(sent.getKey()); sb.append(":\n"); 2840 sb.append(prefix); sb.append(" Created for: "); 2841 formatTimeMs(sb, startTime / 1000); 2842 sb.append("uptime\n"); 2843 sb.append(prefix); sb.append(" Starts: "); 2844 sb.append(starts); 2845 sb.append(", launches: "); sb.append(launches); 2846 pw.println(sb.toString()); 2847 apkActivity = true; 2848 } 2849 } 2850 } 2851 if (!apkActivity) { 2852 pw.print(prefix); pw.println(" (nothing executed)"); 2853 } 2854 uidActivity = true; 2855 } 2856 } 2857 if (!uidActivity) { 2858 pw.print(prefix); pw.println(" (nothing executed)"); 2859 } 2860 } 2861 } 2862 2863 static void printBitDescriptions(PrintWriter pw, int oldval, int newval, HistoryTag wakelockTag, 2864 BitDescription[] descriptions, boolean longNames) { 2865 int diff = oldval ^ newval; 2866 if (diff == 0) return; 2867 boolean didWake = false; 2868 for (int i=0; i<descriptions.length; i++) { 2869 BitDescription bd = descriptions[i]; 2870 if ((diff&bd.mask) != 0) { 2871 pw.print(longNames ? " " : ","); 2872 if (bd.shift < 0) { 2873 pw.print((newval&bd.mask) != 0 ? "+" : "-"); 2874 pw.print(longNames ? bd.name : bd.shortName); 2875 if (bd.mask == HistoryItem.STATE_WAKE_LOCK_FLAG && wakelockTag != null) { 2876 didWake = true; 2877 pw.print("="); 2878 if (longNames) { 2879 UserHandle.formatUid(pw, wakelockTag.uid); 2880 pw.print(":\""); 2881 pw.print(wakelockTag.string); 2882 pw.print("\""); 2883 } else { 2884 pw.print(wakelockTag.poolIdx); 2885 } 2886 } 2887 } else { 2888 pw.print(longNames ? bd.name : bd.shortName); 2889 pw.print("="); 2890 int val = (newval&bd.mask)>>bd.shift; 2891 if (bd.values != null && val >= 0 && val < bd.values.length) { 2892 pw.print(longNames? bd.values[val] : bd.shortValues[val]); 2893 } else { 2894 pw.print(val); 2895 } 2896 } 2897 } 2898 } 2899 if (!didWake && wakelockTag != null) { 2900 pw.print(longNames ? "wake_lock=" : "w="); 2901 if (longNames) { 2902 UserHandle.formatUid(pw, wakelockTag.uid); 2903 pw.print(":\""); 2904 pw.print(wakelockTag.string); 2905 pw.print("\""); 2906 } else { 2907 pw.print(wakelockTag.poolIdx); 2908 } 2909 } 2910 } 2911 2912 public void prepareForDumpLocked() { 2913 } 2914 2915 public static class HistoryPrinter { 2916 int oldState = 0; 2917 int oldState2 = 0; 2918 int oldLevel = -1; 2919 int oldStatus = -1; 2920 int oldHealth = -1; 2921 int oldPlug = -1; 2922 int oldTemp = -1; 2923 int oldVolt = -1; 2924 long lastTime = -1; 2925 long firstTime = -1; 2926 2927 public void printNextItem(PrintWriter pw, HistoryItem rec, long baseTime, boolean checkin, 2928 boolean verbose) { 2929 if (!checkin) { 2930 pw.print(" "); 2931 TimeUtils.formatDuration(rec.time - baseTime, pw, TimeUtils.HUNDRED_DAY_FIELD_LEN); 2932 pw.print(" ("); 2933 pw.print(rec.numReadInts); 2934 pw.print(") "); 2935 } else { 2936 if (lastTime < 0) { 2937 pw.print(rec.time - baseTime); 2938 } else { 2939 pw.print(rec.time - lastTime); 2940 } 2941 lastTime = rec.time; 2942 } 2943 if (rec.cmd == HistoryItem.CMD_START) { 2944 if (checkin) { 2945 pw.print(":"); 2946 } 2947 pw.println("START"); 2948 } else if (rec.cmd == HistoryItem.CMD_CURRENT_TIME) { 2949 if (checkin) { 2950 pw.print(":"); 2951 } 2952 pw.print("TIME:"); 2953 if (checkin) { 2954 pw.println(rec.currentTime); 2955 } else { 2956 pw.print(" "); 2957 pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss", 2958 rec.currentTime).toString()); 2959 } 2960 } else if (rec.cmd == HistoryItem.CMD_OVERFLOW) { 2961 if (checkin) { 2962 pw.print(":"); 2963 } 2964 pw.println("*OVERFLOW*"); 2965 } else { 2966 if (!checkin) { 2967 if (rec.batteryLevel < 10) pw.print("00"); 2968 else if (rec.batteryLevel < 100) pw.print("0"); 2969 pw.print(rec.batteryLevel); 2970 if (verbose) { 2971 pw.print(" "); 2972 if (rec.states < 0) ; 2973 else if (rec.states < 0x10) pw.print("0000000"); 2974 else if (rec.states < 0x100) pw.print("000000"); 2975 else if (rec.states < 0x1000) pw.print("00000"); 2976 else if (rec.states < 0x10000) pw.print("0000"); 2977 else if (rec.states < 0x100000) pw.print("000"); 2978 else if (rec.states < 0x1000000) pw.print("00"); 2979 else if (rec.states < 0x10000000) pw.print("0"); 2980 pw.print(Integer.toHexString(rec.states)); 2981 } 2982 } else { 2983 if (oldLevel != rec.batteryLevel) { 2984 oldLevel = rec.batteryLevel; 2985 pw.print(",Bl="); pw.print(rec.batteryLevel); 2986 } 2987 } 2988 if (oldStatus != rec.batteryStatus) { 2989 oldStatus = rec.batteryStatus; 2990 pw.print(checkin ? ",Bs=" : " status="); 2991 switch (oldStatus) { 2992 case BatteryManager.BATTERY_STATUS_UNKNOWN: 2993 pw.print(checkin ? "?" : "unknown"); 2994 break; 2995 case BatteryManager.BATTERY_STATUS_CHARGING: 2996 pw.print(checkin ? "c" : "charging"); 2997 break; 2998 case BatteryManager.BATTERY_STATUS_DISCHARGING: 2999 pw.print(checkin ? "d" : "discharging"); 3000 break; 3001 case BatteryManager.BATTERY_STATUS_NOT_CHARGING: 3002 pw.print(checkin ? "n" : "not-charging"); 3003 break; 3004 case BatteryManager.BATTERY_STATUS_FULL: 3005 pw.print(checkin ? "f" : "full"); 3006 break; 3007 default: 3008 pw.print(oldStatus); 3009 break; 3010 } 3011 } 3012 if (oldHealth != rec.batteryHealth) { 3013 oldHealth = rec.batteryHealth; 3014 pw.print(checkin ? ",Bh=" : " health="); 3015 switch (oldHealth) { 3016 case BatteryManager.BATTERY_HEALTH_UNKNOWN: 3017 pw.print(checkin ? "?" : "unknown"); 3018 break; 3019 case BatteryManager.BATTERY_HEALTH_GOOD: 3020 pw.print(checkin ? "g" : "good"); 3021 break; 3022 case BatteryManager.BATTERY_HEALTH_OVERHEAT: 3023 pw.print(checkin ? "h" : "overheat"); 3024 break; 3025 case BatteryManager.BATTERY_HEALTH_DEAD: 3026 pw.print(checkin ? "d" : "dead"); 3027 break; 3028 case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE: 3029 pw.print(checkin ? "v" : "over-voltage"); 3030 break; 3031 case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE: 3032 pw.print(checkin ? "f" : "failure"); 3033 break; 3034 case BatteryManager.BATTERY_HEALTH_COLD: 3035 pw.print(checkin ? "c" : "cold"); 3036 break; 3037 default: 3038 pw.print(oldHealth); 3039 break; 3040 } 3041 } 3042 if (oldPlug != rec.batteryPlugType) { 3043 oldPlug = rec.batteryPlugType; 3044 pw.print(checkin ? ",Bp=" : " plug="); 3045 switch (oldPlug) { 3046 case 0: 3047 pw.print(checkin ? "n" : "none"); 3048 break; 3049 case BatteryManager.BATTERY_PLUGGED_AC: 3050 pw.print(checkin ? "a" : "ac"); 3051 break; 3052 case BatteryManager.BATTERY_PLUGGED_USB: 3053 pw.print(checkin ? "u" : "usb"); 3054 break; 3055 case BatteryManager.BATTERY_PLUGGED_WIRELESS: 3056 pw.print(checkin ? "w" : "wireless"); 3057 break; 3058 default: 3059 pw.print(oldPlug); 3060 break; 3061 } 3062 } 3063 if (oldTemp != rec.batteryTemperature) { 3064 oldTemp = rec.batteryTemperature; 3065 pw.print(checkin ? ",Bt=" : " temp="); 3066 pw.print(oldTemp); 3067 } 3068 if (oldVolt != rec.batteryVoltage) { 3069 oldVolt = rec.batteryVoltage; 3070 pw.print(checkin ? ",Bv=" : " volt="); 3071 pw.print(oldVolt); 3072 } 3073 printBitDescriptions(pw, oldState, rec.states, rec.wakelockTag, 3074 HISTORY_STATE_DESCRIPTIONS, !checkin); 3075 printBitDescriptions(pw, oldState2, rec.states2, null, 3076 HISTORY_STATE2_DESCRIPTIONS, !checkin); 3077 if (rec.wakeReasonTag != null) { 3078 if (checkin) { 3079 pw.print(",Wr="); 3080 pw.print(rec.wakeReasonTag.poolIdx); 3081 } else { 3082 pw.print(" wake_reason="); 3083 pw.print(rec.wakeReasonTag.uid); 3084 pw.print(":\""); 3085 pw.print(rec.wakeReasonTag.string); 3086 pw.print("\""); 3087 } 3088 } 3089 if (rec.eventCode != HistoryItem.EVENT_NONE) { 3090 pw.print(checkin ? "," : " "); 3091 if ((rec.eventCode&HistoryItem.EVENT_FLAG_START) != 0) { 3092 pw.print("+"); 3093 } else if ((rec.eventCode&HistoryItem.EVENT_FLAG_FINISH) != 0) { 3094 pw.print("-"); 3095 } 3096 String[] eventNames = checkin ? HISTORY_EVENT_CHECKIN_NAMES 3097 : HISTORY_EVENT_NAMES; 3098 int idx = rec.eventCode & ~(HistoryItem.EVENT_FLAG_START 3099 | HistoryItem.EVENT_FLAG_FINISH); 3100 if (idx >= 0 && idx < eventNames.length) { 3101 pw.print(eventNames[idx]); 3102 } else { 3103 pw.print(checkin ? "Ev" : "event"); 3104 pw.print(idx); 3105 } 3106 pw.print("="); 3107 if (checkin) { 3108 pw.print(rec.eventTag.poolIdx); 3109 } else { 3110 UserHandle.formatUid(pw, rec.eventTag.uid); 3111 pw.print(":\""); 3112 pw.print(rec.eventTag.string); 3113 pw.print("\""); 3114 } 3115 } 3116 pw.println(); 3117 oldState = rec.states; 3118 } 3119 } 3120 } 3121 3122 private void printSizeValue(PrintWriter pw, long size) { 3123 float result = size; 3124 String suffix = ""; 3125 if (result >= 10*1024) { 3126 suffix = "KB"; 3127 result = result / 1024; 3128 } 3129 if (result >= 10*1024) { 3130 suffix = "MB"; 3131 result = result / 1024; 3132 } 3133 if (result >= 10*1024) { 3134 suffix = "GB"; 3135 result = result / 1024; 3136 } 3137 if (result >= 10*1024) { 3138 suffix = "TB"; 3139 result = result / 1024; 3140 } 3141 if (result >= 10*1024) { 3142 suffix = "PB"; 3143 result = result / 1024; 3144 } 3145 pw.print((int)result); 3146 pw.print(suffix); 3147 } 3148 3149 private static boolean dumpDurationSteps(PrintWriter pw, String header, long[] steps, 3150 int count, boolean checkin) { 3151 if (count <= 0) { 3152 return false; 3153 } 3154 if (!checkin) { 3155 pw.println(header); 3156 } 3157 String[] lineArgs = new String[1]; 3158 for (int i=0; i<count; i++) { 3159 if (checkin) { 3160 lineArgs[0] = Long.toString(steps[i]); 3161 dumpLine(pw, 0 /* uid */, "i" /* category */, header, (Object[])lineArgs); 3162 } else { 3163 pw.print(" #"); pw.print(i); pw.print(": "); 3164 TimeUtils.formatDuration(steps[i], pw); 3165 pw.println(); 3166 } 3167 } 3168 return true; 3169 } 3170 3171 public static final int DUMP_UNPLUGGED_ONLY = 1<<0; 3172 public static final int DUMP_CHARGED_ONLY = 1<<1; 3173 public static final int DUMP_HISTORY_ONLY = 1<<2; 3174 public static final int DUMP_INCLUDE_HISTORY = 1<<3; 3175 public static final int DUMP_VERBOSE = 1<<4; 3176 3177 /** 3178 * Dumps a human-readable summary of the battery statistics to the given PrintWriter. 3179 * 3180 * @param pw a Printer to receive the dump output. 3181 */ 3182 @SuppressWarnings("unused") 3183 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) { 3184 prepareForDumpLocked(); 3185 3186 final boolean filtering = 3187 (flags&(DUMP_HISTORY_ONLY|DUMP_UNPLUGGED_ONLY|DUMP_CHARGED_ONLY)) != 0; 3188 3189 if ((flags&DUMP_HISTORY_ONLY) != 0 || !filtering) { 3190 long now = getHistoryBaseTime() + SystemClock.elapsedRealtime(); 3191 3192 final HistoryItem rec = new HistoryItem(); 3193 final long historyTotalSize = getHistoryTotalSize(); 3194 final long historyUsedSize = getHistoryUsedSize(); 3195 if (startIteratingHistoryLocked()) { 3196 try { 3197 pw.print("Battery History ("); 3198 pw.print((100*historyUsedSize)/historyTotalSize); 3199 pw.print("% used, "); 3200 printSizeValue(pw, historyUsedSize); 3201 pw.print(" used of "); 3202 printSizeValue(pw, historyTotalSize); 3203 pw.print(", "); 3204 pw.print(getHistoryStringPoolSize()); 3205 pw.print(" strings using "); 3206 printSizeValue(pw, getHistoryStringPoolBytes()); 3207 pw.println("):"); 3208 HistoryPrinter hprinter = new HistoryPrinter(); 3209 long lastTime = -1; 3210 long baseTime = -1; 3211 boolean printed = false; 3212 while (getNextHistoryLocked(rec)) { 3213 lastTime = rec.time; 3214 if (baseTime < 0) { 3215 baseTime = lastTime; 3216 } 3217 if (rec.time >= histStart) { 3218 if (histStart >= 0 && !printed) { 3219 if (rec.cmd == HistoryItem.CMD_CURRENT_TIME) { 3220 printed = true; 3221 } else if (rec.currentTime != 0) { 3222 printed = true; 3223 byte cmd = rec.cmd; 3224 rec.cmd = HistoryItem.CMD_CURRENT_TIME; 3225 hprinter.printNextItem(pw, rec, baseTime, false, 3226 (flags&DUMP_VERBOSE) != 0); 3227 rec.cmd = cmd; 3228 } 3229 } 3230 hprinter.printNextItem(pw, rec, baseTime, false, 3231 (flags&DUMP_VERBOSE) != 0); 3232 } 3233 } 3234 if (histStart >= 0) { 3235 pw.print(" NEXT: "); pw.println(lastTime+1); 3236 } 3237 pw.println(); 3238 } finally { 3239 finishIteratingHistoryLocked(); 3240 } 3241 } 3242 3243 if (startIteratingOldHistoryLocked()) { 3244 try { 3245 pw.println("Old battery History:"); 3246 HistoryPrinter hprinter = new HistoryPrinter(); 3247 long baseTime = -1; 3248 while (getNextOldHistoryLocked(rec)) { 3249 if (baseTime < 0) { 3250 baseTime = rec.time; 3251 } 3252 hprinter.printNextItem(pw, rec, baseTime, false, (flags&DUMP_VERBOSE) != 0); 3253 } 3254 pw.println(); 3255 } finally { 3256 finishIteratingOldHistoryLocked(); 3257 } 3258 } 3259 } 3260 3261 if (filtering && (flags&(DUMP_UNPLUGGED_ONLY|DUMP_CHARGED_ONLY)) == 0) { 3262 return; 3263 } 3264 3265 if (!filtering) { 3266 SparseArray<? extends Uid> uidStats = getUidStats(); 3267 final int NU = uidStats.size(); 3268 boolean didPid = false; 3269 long nowRealtime = SystemClock.elapsedRealtime(); 3270 for (int i=0; i<NU; i++) { 3271 Uid uid = uidStats.valueAt(i); 3272 SparseArray<? extends Uid.Pid> pids = uid.getPidStats(); 3273 if (pids != null) { 3274 for (int j=0; j<pids.size(); j++) { 3275 Uid.Pid pid = pids.valueAt(j); 3276 if (!didPid) { 3277 pw.println("Per-PID Stats:"); 3278 didPid = true; 3279 } 3280 long time = pid.mWakeSumMs + (pid.mWakeNesting > 0 3281 ? (nowRealtime - pid.mWakeStartMs) : 0); 3282 pw.print(" PID "); pw.print(pids.keyAt(j)); 3283 pw.print(" wake time: "); 3284 TimeUtils.formatDuration(time, pw); 3285 pw.println(""); 3286 } 3287 } 3288 } 3289 if (didPid) { 3290 pw.println(); 3291 } 3292 if (dumpDurationSteps(pw, "Discharge step durations:", getDischargeStepDurationsArray(), 3293 getNumDischargeStepDurations(), false)) { 3294 long timeRemaining = computeBatteryTimeRemaining(SystemClock.elapsedRealtime()); 3295 if (timeRemaining >= 0) { 3296 pw.print(" Estimated discharge time remaining: "); 3297 TimeUtils.formatDuration(timeRemaining / 1000, pw); 3298 pw.println(); 3299 } 3300 pw.println(); 3301 } 3302 if (dumpDurationSteps(pw, "Charge step durations:", getChargeStepDurationsArray(), 3303 getNumChargeStepDurations(), false)) { 3304 long timeRemaining = computeChargeTimeRemaining(SystemClock.elapsedRealtime()); 3305 if (timeRemaining >= 0) { 3306 pw.print(" Estimated charge time remaining: "); 3307 TimeUtils.formatDuration(timeRemaining / 1000, pw); 3308 pw.println(); 3309 } 3310 pw.println(); 3311 } 3312 } 3313 3314 if (!filtering || (flags&DUMP_CHARGED_ONLY) != 0) { 3315 pw.println("Statistics since last charge:"); 3316 pw.println(" System starts: " + getStartCount() 3317 + ", currently on battery: " + getIsOnBattery()); 3318 dumpLocked(context, pw, "", STATS_SINCE_CHARGED, reqUid); 3319 pw.println(); 3320 } 3321 if (!filtering || (flags&DUMP_UNPLUGGED_ONLY) != 0) { 3322 pw.println("Statistics since last unplugged:"); 3323 dumpLocked(context, pw, "", STATS_SINCE_UNPLUGGED, reqUid); 3324 } 3325 } 3326 3327 @SuppressWarnings("unused") 3328 public void dumpCheckinLocked(Context context, PrintWriter pw, 3329 List<ApplicationInfo> apps, int flags, long histStart) { 3330 prepareForDumpLocked(); 3331 3332 long now = getHistoryBaseTime() + SystemClock.elapsedRealtime(); 3333 3334 final boolean filtering = 3335 (flags&(DUMP_HISTORY_ONLY|DUMP_UNPLUGGED_ONLY|DUMP_CHARGED_ONLY)) != 0; 3336 3337 if ((flags&DUMP_INCLUDE_HISTORY) != 0 || (flags&DUMP_HISTORY_ONLY) != 0) { 3338 final HistoryItem rec = new HistoryItem(); 3339 if (startIteratingHistoryLocked()) { 3340 try { 3341 for (int i=0; i<getHistoryStringPoolSize(); i++) { 3342 pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); 3343 pw.print(HISTORY_STRING_POOL); pw.print(','); 3344 pw.print(i); 3345 pw.print(","); 3346 pw.print(getHistoryTagPoolUid(i)); 3347 pw.print(",\""); 3348 String str = getHistoryTagPoolString(i); 3349 str = str.replace("\\", "\\\\"); 3350 str = str.replace("\"", "\\\""); 3351 pw.print(str); 3352 pw.print("\""); 3353 pw.println(); 3354 } 3355 HistoryPrinter hprinter = new HistoryPrinter(); 3356 long lastTime = -1; 3357 long baseTime = -1; 3358 boolean printed = false; 3359 while (getNextHistoryLocked(rec)) { 3360 lastTime = rec.time; 3361 if (baseTime < 0) { 3362 baseTime = lastTime; 3363 } 3364 if (rec.time >= histStart) { 3365 if (histStart >= 0 && !printed) { 3366 if (rec.cmd == HistoryItem.CMD_CURRENT_TIME) { 3367 printed = true; 3368 } else if (rec.currentTime != 0) { 3369 printed = true; 3370 byte cmd = rec.cmd; 3371 rec.cmd = HistoryItem.CMD_CURRENT_TIME; 3372 pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); 3373 pw.print(HISTORY_DATA); pw.print(','); 3374 hprinter.printNextItem(pw, rec, baseTime, true, false); 3375 rec.cmd = cmd; 3376 } 3377 } 3378 pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); 3379 pw.print(HISTORY_DATA); pw.print(','); 3380 hprinter.printNextItem(pw, rec, baseTime, true, false); 3381 } 3382 } 3383 if (histStart >= 0) { 3384 pw.print("NEXT: "); pw.println(lastTime+1); 3385 } 3386 } finally { 3387 finishIteratingHistoryLocked(); 3388 } 3389 } 3390 } 3391 3392 if (filtering && (flags&(DUMP_UNPLUGGED_ONLY|DUMP_CHARGED_ONLY)) == 0) { 3393 return; 3394 } 3395 3396 if (apps != null) { 3397 SparseArray<ArrayList<String>> uids = new SparseArray<ArrayList<String>>(); 3398 for (int i=0; i<apps.size(); i++) { 3399 ApplicationInfo ai = apps.get(i); 3400 ArrayList<String> pkgs = uids.get(ai.uid); 3401 if (pkgs == null) { 3402 pkgs = new ArrayList<String>(); 3403 uids.put(ai.uid, pkgs); 3404 } 3405 pkgs.add(ai.packageName); 3406 } 3407 SparseArray<? extends Uid> uidStats = getUidStats(); 3408 final int NU = uidStats.size(); 3409 String[] lineArgs = new String[2]; 3410 for (int i=0; i<NU; i++) { 3411 int uid = uidStats.keyAt(i); 3412 ArrayList<String> pkgs = uids.get(uid); 3413 if (pkgs != null) { 3414 for (int j=0; j<pkgs.size(); j++) { 3415 lineArgs[0] = Integer.toString(uid); 3416 lineArgs[1] = pkgs.get(j); 3417 dumpLine(pw, 0 /* uid */, "i" /* category */, UID_DATA, 3418 (Object[])lineArgs); 3419 } 3420 } 3421 } 3422 } 3423 if (!filtering) { 3424 dumpDurationSteps(pw, DISCHARGE_STEP_DATA, getDischargeStepDurationsArray(), 3425 getNumDischargeStepDurations(), true); 3426 dumpDurationSteps(pw, CHARGE_STEP_DATA, getChargeStepDurationsArray(), 3427 getNumChargeStepDurations(), true); 3428 } 3429 if (!filtering || (flags&DUMP_CHARGED_ONLY) != 0) { 3430 dumpCheckinLocked(context, pw, STATS_SINCE_CHARGED, -1); 3431 } 3432 if (!filtering || (flags&DUMP_UNPLUGGED_ONLY) != 0) { 3433 dumpCheckinLocked(context, pw, STATS_SINCE_UNPLUGGED, -1); 3434 } 3435 } 3436} 3437