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