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