Debian Codegraph @

core/java/android/os/BatteryStats.java

raw symbols SCIP
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
17 package android.os;
18
19 import static android.os.BatteryStatsManager.NUM_WIFI_STATES;
20 import static android.os.BatteryStatsManager.NUM_WIFI_SUPPL_STATES;
21
22 import android.annotation.IntDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.app.ActivityManager;
26 import android.app.job.JobParameters;
27 import android.compat.annotation.UnsupportedAppUsage;
28 import android.content.Context;
29 import android.content.pm.ApplicationInfo;
30 import android.content.pm.PackageManager;
31 import android.content.res.Resources;
32 import android.location.GnssSignalQuality;
33 import android.os.BatteryStatsManager.WifiState;
34 import android.os.BatteryStatsManager.WifiSupplState;
35 import android.server.ServerProtoEnums;
36 import android.service.batterystats.BatteryStatsServiceDumpHistoryProto;
37 import android.service.batterystats.BatteryStatsServiceDumpProto;
38 import android.telephony.CellSignalStrength;
39 import android.telephony.ServiceState;
40 import android.telephony.TelephonyManager;
41 import android.text.format.DateFormat;
42 import android.util.ArrayMap;
43 import android.util.LongSparseArray;
44 import android.util.MutableBoolean;
45 import android.util.Pair;
46 import android.util.Printer;
47 import android.util.SparseArray;
48 import android.util.SparseDoubleArray;
49 import android.util.SparseIntArray;
50 import android.util.TimeUtils;
51 import android.util.proto.ProtoOutputStream;
52 import android.view.Display;
53
54 import com.android.internal.annotations.VisibleForTesting;
55 import com.android.internal.os.BatteryUsageStatsProvider;
56
57 import com.google.android.collect.Lists;
58
59 import java.io.FileDescriptor;
60 import java.io.PrintWriter;
61 import java.lang.annotation.Retention;
62 import java.lang.annotation.RetentionPolicy;
63 import java.text.DecimalFormat;
64 import java.util.ArrayList;
65 import java.util.Arrays;
66 import java.util.Collections;
67 import java.util.Comparator;
68 import java.util.Formatter;
69 import java.util.HashMap;
70 import java.util.HashSet;
71 import java.util.List;
72 import java.util.Locale;
73 import java.util.Map;
74
75 /**
76 * A class providing access to battery usage statistics, including information on
77 * wakelocks, processes, packages, and services. All times are represented in microseconds
78 * except where indicated otherwise.
79 * @hide
80 */
81 public abstract class BatteryStats implements Parcelable {
82
83 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
84 public BatteryStats() {}
85
86 private static final String TAG = "BatteryStats";
87
88 private static final boolean LOCAL_LOGV = false;
89 /** Fetching RPM stats is too slow to do each time screen changes, so disable it. */
90 protected static final boolean SCREEN_OFF_RPM_STATS_ENABLED = false;
91
92 /** @hide */
93 public static final String SERVICE_NAME = Context.BATTERY_STATS_SERVICE;
94
95 /**
96 * A constant indicating a partial wake lock timer.
97 */
98 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
99 public static final int WAKE_TYPE_PARTIAL = 0;
100
101 /**
102 * A constant indicating a full wake lock timer.
103 */
104 public static final int WAKE_TYPE_FULL = 1;
105
106 /**
107 * A constant indicating a window wake lock timer.
108 */
109 public static final int WAKE_TYPE_WINDOW = 2;
110
111 /**
112 * A constant indicating a sensor timer.
113 */
114 public static final int SENSOR = 3;
115
116 /**
117 * A constant indicating a a wifi running timer
118 */
119 public static final int WIFI_RUNNING = 4;
120
121 /**
122 * A constant indicating a full wifi lock timer
123 */
124 public static final int FULL_WIFI_LOCK = 5;
125
126 /**
127 * A constant indicating a wifi scan
128 */
129 public static final int WIFI_SCAN = 6;
130
131 /**
132 * A constant indicating a wifi multicast timer
133 */
134 public static final int WIFI_MULTICAST_ENABLED = 7;
135
136 /**
137 * A constant indicating a video turn on timer
138 */
139 public static final int VIDEO_TURNED_ON = 8;
140
141 /**
142 * A constant indicating a vibrator on timer
143 */
144 public static final int VIBRATOR_ON = 9;
145
146 /**
147 * A constant indicating a foreground activity timer
148 */
149 public static final int FOREGROUND_ACTIVITY = 10;
150
151 /**
152 * A constant indicating a wifi batched scan is active
153 */
154 public static final int WIFI_BATCHED_SCAN = 11;
155
156 /**
157 * A constant indicating a process state timer
158 */
159 public static final int PROCESS_STATE = 12;
160
161 /**
162 * A constant indicating a sync timer
163 */
164 public static final int SYNC = 13;
165
166 /**
167 * A constant indicating a job timer
168 */
169 public static final int JOB = 14;
170
171 /**
172 * A constant indicating an audio turn on timer
173 */
174 public static final int AUDIO_TURNED_ON = 15;
175
176 /**
177 * A constant indicating a flashlight turn on timer
178 */
179 public static final int FLASHLIGHT_TURNED_ON = 16;
180
181 /**
182 * A constant indicating a camera turn on timer
183 */
184 public static final int CAMERA_TURNED_ON = 17;
185
186 /**
187 * A constant indicating a draw wake lock timer.
188 */
189 public static final int WAKE_TYPE_DRAW = 18;
190
191 /**
192 * A constant indicating a bluetooth scan timer.
193 */
194 public static final int BLUETOOTH_SCAN_ON = 19;
195
196 /**
197 * A constant indicating an aggregated partial wake lock timer.
198 */
199 public static final int AGGREGATED_WAKE_TYPE_PARTIAL = 20;
200
201 /**
202 * A constant indicating a bluetooth scan timer for unoptimized scans.
203 */
204 public static final int BLUETOOTH_UNOPTIMIZED_SCAN_ON = 21;
205
206 /**
207 * A constant indicating a foreground service timer
208 */
209 public static final int FOREGROUND_SERVICE = 22;
210
211 /**
212 * A constant indicating an aggregate wifi multicast timer
213 */
214 public static final int WIFI_AGGREGATE_MULTICAST_ENABLED = 23;
215
216 /**
217 * Include all of the data in the stats, including previously saved data.
218 */
219 public static final int STATS_SINCE_CHARGED = 0;
220
221 /**
222 * Include only the current run in the stats.
223 *
224 * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, only {@link #STATS_SINCE_CHARGED}
225 * is supported.
226 */
227 @UnsupportedAppUsage
228 @Deprecated
229 public static final int STATS_CURRENT = 1;
230
231 /**
232 * Include only the run since the last time the device was unplugged in the stats.
233 *
234 * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, only {@link #STATS_SINCE_CHARGED}
235 * is supported.
236 */
237 @Deprecated
238 public static final int STATS_SINCE_UNPLUGGED = 2;
239
240 /** @hide */
241 @IntDef(flag = true, prefix = { "STATS_" }, value = {
242 STATS_SINCE_CHARGED,
243 STATS_CURRENT,
244 STATS_SINCE_UNPLUGGED
245 })
246 @Retention(RetentionPolicy.SOURCE)
247 public @interface StatName {}
248
249 // NOTE: Update this list if you add/change any stats above.
250 // These characters are supposed to represent "total", "last", "current",
251 // and "unplugged". They were shortened for efficiency sake.
252 private static final String[] STAT_NAMES = { "l", "c", "u" };
253
254 /**
255 * Current version of checkin data format.
256 *
257 * New in version 19:
258 * - Wakelock data (wl) gets current and max times.
259 * New in version 20:
260 * - Background timers and counters for: Sensor, BluetoothScan, WifiScan, Jobs, Syncs.
261 * New in version 21:
262 * - Actual (not just apportioned) Wakelock time is also recorded.
263 * - Aggregated partial wakelock time (per uid, instead of per wakelock) is recorded.
264 * - BLE scan result count
265 * - CPU frequency time per uid
266 * New in version 22:
267 * - BLE scan result background count, BLE unoptimized scan time
268 * - Background partial wakelock time & count
269 * New in version 23:
270 * - Logging smeared power model values
271 * New in version 24:
272 * - Fixed bugs in background timers and BLE scan time
273 * New in version 25:
274 * - Package wakeup alarms are now on screen-off timebase
275 * New in version 26:
276 * - Resource power manager (rpm) states [but screenOffRpm is disabled from working properly]
277 * New in version 27:
278 * - Always On Display (screen doze mode) time and power
279 * New in version 28:
280 * - Light/Deep Doze power
281 * - WiFi Multicast Wakelock statistics (count & duration)
282 * New in version 29:
283 * - Process states re-ordered. TOP_SLEEPING now below BACKGROUND. HEAVY_WEIGHT introduced.
284 * - CPU times per UID process state
285 * New in version 30:
286 * - Uid.PROCESS_STATE_FOREGROUND_SERVICE only tracks
287 * ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE.
288 * New in version 31:
289 * - New cellular network types.
290 * - Deferred job metrics.
291 * New in version 32:
292 * - Ambient display properly output in data dump.
293 * New in version 33:
294 * - Fixed bug in min learned capacity updating process.
295 * New in version 34:
296 * - Deprecated STATS_SINCE_UNPLUGGED and STATS_CURRENT.
297 * New in version 35:
298 * - Fixed bug that was not reporting high cellular tx power correctly
299 * - Added out of service and emergency service modes to data connection types
300 */
301 static final int CHECKIN_VERSION = 35;
302
303 /**
304 * Old version, we hit 9 and ran out of room, need to remove.
305 */
306 private static final int BATTERY_STATS_CHECKIN_VERSION = 9;
307
308 private static final long BYTES_PER_KB = 1024;
309 private static final long BYTES_PER_MB = 1048576; // 1024^2
310 private static final long BYTES_PER_GB = 1073741824; //1024^3
311 public static final double MILLISECONDS_IN_HOUR = 3600 * 1000;
312
313 private static final String VERSION_DATA = "vers";
314 private static final String UID_DATA = "uid";
315 private static final String WAKEUP_ALARM_DATA = "wua";
316 private static final String APK_DATA = "apk";
317 private static final String PROCESS_DATA = "pr";
318 private static final String CPU_DATA = "cpu";
319 private static final String GLOBAL_CPU_FREQ_DATA = "gcf";
320 private static final String CPU_TIMES_AT_FREQ_DATA = "ctf";
321 // rpm line is:
322 // BATTERY_STATS_CHECKIN_VERSION, uid, which, "rpm", state/voter name, total time, total count,
323 // screen-off time, screen-off count
324 private static final String RESOURCE_POWER_MANAGER_DATA = "rpm";
325 private static final String SENSOR_DATA = "sr";
326 private static final String VIBRATOR_DATA = "vib";
327 private static final String FOREGROUND_ACTIVITY_DATA = "fg";
328 // fgs line is:
329 // BATTERY_STATS_CHECKIN_VERSION, uid, category, "fgs",
330 // foreground service time, count
331 private static final String FOREGROUND_SERVICE_DATA = "fgs";
332 private static final String STATE_TIME_DATA = "st";
333 // wl line is:
334 // BATTERY_STATS_CHECKIN_VERSION, uid, which, "wl", name,
335 // full totalTime, 'f', count, current duration, max duration, total duration,
336 // partial totalTime, 'p', count, current duration, max duration, total duration,
337 // bg partial totalTime, 'bp', count, current duration, max duration, total duration,
338 // window totalTime, 'w', count, current duration, max duration, total duration
339 // [Currently, full and window wakelocks have durations current = max = total = -1]
340 private static final String WAKELOCK_DATA = "wl";
341 // awl line is:
342 // BATTERY_STATS_CHECKIN_VERSION, uid, which, "awl",
343 // cumulative partial wakelock duration, cumulative background partial wakelock duration
344 private static final String AGGREGATED_WAKELOCK_DATA = "awl";
345 private static final String SYNC_DATA = "sy";
346 private static final String JOB_DATA = "jb";
347 private static final String JOB_COMPLETION_DATA = "jbc";
348
349 /**
350 * jbd line is:
351 * BATTERY_STATS_CHECKIN_VERSION, uid, which, "jbd",
352 * jobsDeferredEventCount, jobsDeferredCount, totalLatencyMillis,
353 * count at latency < 1 hr, count at latency 1 to 2 hrs, 2 to 4 hrs, 4 to 8 hrs, and past 8 hrs
354 * <p>
355 * @see #JOB_FRESHNESS_BUCKETS
356 */
357 private static final String JOBS_DEFERRED_DATA = "jbd";
358 private static final String KERNEL_WAKELOCK_DATA = "kwl";
359 private static final String WAKEUP_REASON_DATA = "wr";
360 private static final String NETWORK_DATA = "nt";
361 private static final String USER_ACTIVITY_DATA = "ua";
362 private static final String BATTERY_DATA = "bt";
363 private static final String BATTERY_DISCHARGE_DATA = "dc";
364 private static final String BATTERY_LEVEL_DATA = "lv";
365 private static final String GLOBAL_WIFI_DATA = "gwfl";
366 private static final String WIFI_DATA = "wfl";
367 private static final String GLOBAL_WIFI_CONTROLLER_DATA = "gwfcd";
368 private static final String WIFI_CONTROLLER_DATA = "wfcd";
369 private static final String GLOBAL_BLUETOOTH_CONTROLLER_DATA = "gble";
370 private static final String BLUETOOTH_CONTROLLER_DATA = "ble";
371 private static final String BLUETOOTH_MISC_DATA = "blem";
372 private static final String MISC_DATA = "m";
373 private static final String GLOBAL_NETWORK_DATA = "gn";
374 private static final String GLOBAL_MODEM_CONTROLLER_DATA = "gmcd";
375 private static final String MODEM_CONTROLLER_DATA = "mcd";
376 private static final String HISTORY_STRING_POOL = "hsp";
377 private static final String HISTORY_DATA = "h";
378 private static final String SCREEN_BRIGHTNESS_DATA = "br";
379 private static final String SIGNAL_STRENGTH_TIME_DATA = "sgt";
380 private static final String SIGNAL_SCANNING_TIME_DATA = "sst";
381 private static final String SIGNAL_STRENGTH_COUNT_DATA = "sgc";
382 private static final String DATA_CONNECTION_TIME_DATA = "dct";
383 private static final String DATA_CONNECTION_COUNT_DATA = "dcc";
384 private static final String WIFI_STATE_TIME_DATA = "wst";
385 private static final String WIFI_STATE_COUNT_DATA = "wsc";
386 private static final String WIFI_SUPPL_STATE_TIME_DATA = "wsst";
387 private static final String WIFI_SUPPL_STATE_COUNT_DATA = "wssc";
388 private static final String WIFI_SIGNAL_STRENGTH_TIME_DATA = "wsgt";
389 private static final String WIFI_SIGNAL_STRENGTH_COUNT_DATA = "wsgc";
390 private static final String POWER_USE_SUMMARY_DATA = "pws";
391 private static final String POWER_USE_ITEM_DATA = "pwi";
392 private static final String DISCHARGE_STEP_DATA = "dsd";
393 private static final String CHARGE_STEP_DATA = "csd";
394 private static final String DISCHARGE_TIME_REMAIN_DATA = "dtr";
395 private static final String CHARGE_TIME_REMAIN_DATA = "ctr";
396 private static final String FLASHLIGHT_DATA = "fla";
397 private static final String CAMERA_DATA = "cam";
398 private static final String VIDEO_DATA = "vid";
399 private static final String AUDIO_DATA = "aud";
400 private static final String WIFI_MULTICAST_TOTAL_DATA = "wmct";
401 private static final String WIFI_MULTICAST_DATA = "wmc";
402
403 public static final String RESULT_RECEIVER_CONTROLLER_KEY = "controller_activity";
404
405 private final StringBuilder mFormatBuilder = new StringBuilder(32);
406 private final Formatter mFormatter = new Formatter(mFormatBuilder);
407
408 private static final String CELLULAR_CONTROLLER_NAME = "Cellular";
409 private static final String WIFI_CONTROLLER_NAME = "WiFi";
410
411 /**
412 * Indicates times spent by the uid at each cpu frequency in all process states.
413 *
414 * Other types might include times spent in foreground, background etc.
415 */
416 @VisibleForTesting
417 public static final String UID_TIMES_TYPE_ALL = "A";
418
419 /**
420 * These are the thresholds for bucketing last time since a job was run for an app
421 * that just moved to ACTIVE due to a launch. So if the last time a job ran was less
422 * than 1 hour ago, then it's reasonably fresh, 2 hours ago, not so fresh and so
423 * on.
424 */
425 public static final long[] JOB_FRESHNESS_BUCKETS = {
426 1 * 60 * 60 * 1000L,
427 2 * 60 * 60 * 1000L,
428 4 * 60 * 60 * 1000L,
429 8 * 60 * 60 * 1000L,
430 Long.MAX_VALUE
431 };
432
433 /**
434 * State for keeping track of counting information.
435 */
436 public static abstract class Counter {
437
438 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
439 public Counter() {}
440
441 /**
442 * Returns the count associated with this Counter for the
443 * selected type of statistics.
444 *
445 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
446 */
447 @UnsupportedAppUsage
448 public abstract int getCountLocked(int which);
449
450 /**
451 * Temporary for debugging.
452 */
453 public abstract void logState(Printer pw, String prefix);
454 }
455
456 /**
457 * State for keeping track of long counting information.
458 */
459 public static abstract class LongCounter {
460
461 /**
462 * Returns the count associated with this Counter for the
463 * selected type of statistics.
464 *
465 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
466 */
467 public abstract long getCountLocked(int which);
468
469 /**
470 * Returns the count accumulated by this Counter for the specified process state.
471 * If the counter does not support per-procstate tracking, returns 0.
472 */
473 public abstract long getCountForProcessState(@BatteryConsumer.ProcessState int procState);
474
475 /**
476 * Temporary for debugging.
477 */
478 public abstract void logState(Printer pw, String prefix);
479 }
480
481 /**
482 * State for keeping track of array of long counting information.
483 */
484 public static abstract class LongCounterArray {
485 /**
486 * Returns the counts associated with this Counter for the
487 * selected type of statistics.
488 *
489 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
490 */
491 public abstract long[] getCountsLocked(int which);
492
493 /**
494 * Temporary for debugging.
495 */
496 public abstract void logState(Printer pw, String prefix);
497 }
498
499 /**
500 * Container class that aggregates counters for transmit, receive, and idle state of a
501 * radio controller.
502 */
503 public static abstract class ControllerActivityCounter {
504 /**
505 * @return a non-null {@link LongCounter} representing time spent (milliseconds) in the
506 * idle state.
507 */
508 public abstract LongCounter getIdleTimeCounter();
509
510 /**
511 * @return a non-null {@link LongCounter} representing time spent (milliseconds) in the
512 * scan state.
513 */
514 public abstract LongCounter getScanTimeCounter();
515
516 /**
517 * @return a non-null {@link LongCounter} representing time spent (milliseconds) in the
518 * sleep state.
519 */
520 public abstract LongCounter getSleepTimeCounter();
521
522 /**
523 * @return a non-null {@link LongCounter} representing time spent (milliseconds) in the
524 * receive state.
525 */
526 public abstract LongCounter getRxTimeCounter();
527
528 /**
529 * An array of {@link LongCounter}, representing various transmit levels, where each level
530 * may draw a different amount of power. The levels themselves are controller-specific.
531 * @return non-null array of {@link LongCounter}s representing time spent (milliseconds) in
532 * various transmit level states.
533 */
534 public abstract LongCounter[] getTxTimeCounters();
535
536 /**
537 * @return a non-null {@link LongCounter} representing the power consumed by the controller
538 * in all states, measured in milli-ampere-milliseconds (mAms). The counter may always
539 * yield a value of 0 if the device doesn't support power calculations.
540 */
541 public abstract LongCounter getPowerCounter();
542
543 /**
544 * @return a non-null {@link LongCounter} representing total power monitored on the rails
545 * in mAms (miliamps-milliseconds). The counter may always yield a value of 0 if the device
546 * doesn't support power rail monitoring.
547 */
548 public abstract LongCounter getMonitoredRailChargeConsumedMaMs();
549 }
550
551 /**
552 * State for keeping track of timing information.
553 */
554 public static abstract class Timer {
555
556 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
557 public Timer() {}
558
559 /**
560 * Returns the count associated with this Timer for the
561 * selected type of statistics.
562 *
563 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
564 */
565 @UnsupportedAppUsage
566 public abstract int getCountLocked(int which);
567
568 /**
569 * Returns the total time in microseconds associated with this Timer for the
570 * selected type of statistics.
571 *
572 * @param elapsedRealtimeUs current elapsed realtime of system in microseconds
573 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
574 * @return a time in microseconds
575 */
576 @UnsupportedAppUsage
577 public abstract long getTotalTimeLocked(long elapsedRealtimeUs, int which);
578
579 /**
580 * Returns the total time in microseconds associated with this Timer since the
581 * 'mark' was last set.
582 *
583 * @param elapsedRealtimeUs current elapsed realtime of system in microseconds
584 * @return a time in microseconds
585 */
586 public abstract long getTimeSinceMarkLocked(long elapsedRealtimeUs);
587
588 /**
589 * Returns the max duration if it is being tracked.
590 * Not all Timer subclasses track the max, total, and current durations.
591 */
592 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
593 return -1;
594 }
595
596 /**
597 * Returns the current time the timer has been active, if it is being tracked.
598 * Not all Timer subclasses track the max, total, and current durations.
599 */
600 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
601 return -1;
602 }
603
604 /**
605 * Returns the total time the timer has been active, if it is being tracked.
606 *
607 * Returns the total cumulative duration (i.e. sum of past durations) that this timer has
608 * been on since reset.
609 * This may differ from getTotalTimeLocked(elapsedRealtimeUs, STATS_SINCE_CHARGED)/1000 since,
610 * depending on the Timer, getTotalTimeLocked may represent the total 'blamed' or 'pooled'
611 * time, rather than the actual time. By contrast, getTotalDurationMsLocked always gives
612 * the actual total time.
613 * Not all Timer subclasses track the max, total, and current durations.
614 */
615 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
616 return -1;
617 }
618
619 /**
620 * Returns the secondary Timer held by the Timer, if one exists. This secondary timer may be
621 * used, for example, for tracking background usage. Secondary timers are never pooled.
622 *
623 * Not all Timer subclasses have a secondary timer; those that don't return null.
624 */
625 public Timer getSubTimer() {
626 return null;
627 }
628
629 /**
630 * Returns whether the timer is currently running. Some types of timers
631 * (e.g. BatchTimers) don't know whether the event is currently active,
632 * and report false.
633 */
634 public boolean isRunningLocked() {
635 return false;
636 }
637
638 /**
639 * Temporary for debugging.
640 */
641 public abstract void logState(Printer pw, String prefix);
642 }
643
644 /**
645 * Maps the ActivityManager procstate into corresponding BatteryStats procstate.
646 */
647 public static int mapToInternalProcessState(int procState) {
648 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
649 return Uid.PROCESS_STATE_NONEXISTENT;
650 } else if (procState == ActivityManager.PROCESS_STATE_TOP) {
651 return Uid.PROCESS_STATE_TOP;
652 } else if (ActivityManager.isForegroundService(procState)) {
653 // State when app has put itself in the foreground.
654 return Uid.PROCESS_STATE_FOREGROUND_SERVICE;
655 } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
656 // Persistent and other foreground states go here.
657 return Uid.PROCESS_STATE_FOREGROUND;
658 } else if (procState <= ActivityManager.PROCESS_STATE_RECEIVER) {
659 return Uid.PROCESS_STATE_BACKGROUND;
660 } else if (procState <= ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
661 return Uid.PROCESS_STATE_TOP_SLEEPING;
662 } else if (procState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
663 return Uid.PROCESS_STATE_HEAVY_WEIGHT;
664 } else {
665 return Uid.PROCESS_STATE_CACHED;
666 }
667 }
668
669 /**
670 * Maps BatteryStats.Uid process state to the BatteryConsumer process state.
671 */
672 public static @BatteryConsumer.ProcessState int
673 mapUidProcessStateToBatteryConsumerProcessState(int processState) {
674 switch (processState) {
675 case BatteryStats.Uid.PROCESS_STATE_TOP:
676 case BatteryStats.Uid.PROCESS_STATE_FOREGROUND:
677 return BatteryConsumer.PROCESS_STATE_FOREGROUND;
678 case BatteryStats.Uid.PROCESS_STATE_BACKGROUND:
679 case BatteryStats.Uid.PROCESS_STATE_TOP_SLEEPING:
680 return BatteryConsumer.PROCESS_STATE_BACKGROUND;
681 case BatteryStats.Uid.PROCESS_STATE_FOREGROUND_SERVICE:
682 return BatteryConsumer.PROCESS_STATE_FOREGROUND_SERVICE;
683 case BatteryStats.Uid.PROCESS_STATE_CACHED:
684 return BatteryConsumer.PROCESS_STATE_CACHED;
685 default:
686 return BatteryConsumer.PROCESS_STATE_UNSPECIFIED;
687 }
688 }
689
690 /**
691 * Returns true if battery consumption is tracked on a per-process-state basis.
692 */
693 public abstract boolean isProcessStateDataAvailable();
694
695 /**
696 * The statistics associated with a particular uid.
697 */
698 public static abstract class Uid {
699
700 @UnsupportedAppUsage
701 public Uid() {
702 }
703
704 /**
705 * Returns a mapping containing wakelock statistics.
706 *
707 * @return a Map from Strings to Uid.Wakelock objects.
708 */
709 @UnsupportedAppUsage
710 public abstract ArrayMap<String, ? extends Wakelock> getWakelockStats();
711
712 /**
713 * Returns the WiFi Multicast Wakelock statistics.
714 *
715 * @return a Timer Object for the per uid Multicast statistics.
716 */
717 public abstract Timer getMulticastWakelockStats();
718
719 /**
720 * Returns a mapping containing sync statistics.
721 *
722 * @return a Map from Strings to Timer objects.
723 */
724 public abstract ArrayMap<String, ? extends Timer> getSyncStats();
725
726 /**
727 * Returns a mapping containing scheduled job statistics.
728 *
729 * @return a Map from Strings to Timer objects.
730 */
731 public abstract ArrayMap<String, ? extends Timer> getJobStats();
732
733 /**
734 * Returns statistics about how jobs have completed.
735 *
736 * @return A Map of String job names to completion type -> count mapping.
737 */
738 public abstract ArrayMap<String, SparseIntArray> getJobCompletionStats();
739
740 /**
741 * The statistics associated with a particular wake lock.
742 */
743 public static abstract class Wakelock {
744 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
745 public Wakelock() {}
746
747 @UnsupportedAppUsage
748 public abstract Timer getWakeTime(int type);
749 }
750
751 /**
752 * The cumulative time the uid spent holding any partial wakelocks. This will generally
753 * differ from summing over the Wakelocks in getWakelockStats since the latter may have
754 * wakelocks that overlap in time (and therefore over-counts).
755 */
756 public abstract Timer getAggregatedPartialWakelockTimer();
757
758 /**
759 * Returns a mapping containing sensor statistics.
760 *
761 * @return a Map from Integer sensor ids to Uid.Sensor objects.
762 */
763 @UnsupportedAppUsage
764 public abstract SparseArray<? extends Sensor> getSensorStats();
765
766 /**
767 * Returns a mapping containing active process data.
768 */
769 public abstract SparseArray<? extends Pid> getPidStats();
770
771 /**
772 * Returns a mapping containing process statistics.
773 *
774 * @return a Map from Strings to Uid.Proc objects.
775 */
776 @UnsupportedAppUsage
777 public abstract ArrayMap<String, ? extends Proc> getProcessStats();
778
779 /**
780 * Returns a mapping containing package statistics.
781 *
782 * @return a Map from Strings to Uid.Pkg objects.
783 */
784 @UnsupportedAppUsage
785 public abstract ArrayMap<String, ? extends Pkg> getPackageStats();
786
787 /**
788 * Returns the proportion of power consumed by the System Service
789 * calls made by this UID.
790 */
791 public abstract double getProportionalSystemServiceUsage();
792
793 public abstract ControllerActivityCounter getWifiControllerActivity();
794 public abstract ControllerActivityCounter getBluetoothControllerActivity();
795 public abstract ControllerActivityCounter getModemControllerActivity();
796
797 /**
798 * {@hide}
799 */
800 @UnsupportedAppUsage
801 public abstract int getUid();
802
803 public abstract void noteWifiRunningLocked(long elapsedRealtime);
804 public abstract void noteWifiStoppedLocked(long elapsedRealtime);
805 public abstract void noteFullWifiLockAcquiredLocked(long elapsedRealtime);
806 public abstract void noteFullWifiLockReleasedLocked(long elapsedRealtime);
807 public abstract void noteWifiScanStartedLocked(long elapsedRealtime);
808 public abstract void noteWifiScanStoppedLocked(long elapsedRealtime);
809 public abstract void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtime);
810 public abstract void noteWifiBatchedScanStoppedLocked(long elapsedRealtime);
811 public abstract void noteWifiMulticastEnabledLocked(long elapsedRealtime);
812 public abstract void noteWifiMulticastDisabledLocked(long elapsedRealtime);
813 public abstract void noteActivityResumedLocked(long elapsedRealtime);
814 public abstract void noteActivityPausedLocked(long elapsedRealtime);
815 @UnsupportedAppUsage
816 public abstract long getWifiRunningTime(long elapsedRealtimeUs, int which);
817 @UnsupportedAppUsage
818 public abstract long getFullWifiLockTime(long elapsedRealtimeUs, int which);
819 @UnsupportedAppUsage
820 public abstract long getWifiScanTime(long elapsedRealtimeUs, int which);
821 public abstract int getWifiScanCount(int which);
822 /**
823 * Returns the timer keeping track of wifi scans.
824 */
825 public abstract Timer getWifiScanTimer();
826 public abstract int getWifiScanBackgroundCount(int which);
827 public abstract long getWifiScanActualTime(long elapsedRealtimeUs);
828 public abstract long getWifiScanBackgroundTime(long elapsedRealtimeUs);
829 /**
830 * Returns the timer keeping track of background wifi scans.
831 */
832 public abstract Timer getWifiScanBackgroundTimer();
833 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
834 public abstract long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which);
835 public abstract int getWifiBatchedScanCount(int csphBin, int which);
836 @UnsupportedAppUsage
837 public abstract long getWifiMulticastTime(long elapsedRealtimeUs, int which);
838 @UnsupportedAppUsage
839 public abstract Timer getAudioTurnedOnTimer();
840 @UnsupportedAppUsage
841 public abstract Timer getVideoTurnedOnTimer();
842 public abstract Timer getFlashlightTurnedOnTimer();
843 public abstract Timer getCameraTurnedOnTimer();
844 public abstract Timer getForegroundActivityTimer();
845
846 /**
847 * Returns the timer keeping track of Foreground Service time
848 */
849 public abstract Timer getForegroundServiceTimer();
850 public abstract Timer getBluetoothScanTimer();
851 public abstract Timer getBluetoothScanBackgroundTimer();
852 public abstract Timer getBluetoothUnoptimizedScanTimer();
853 public abstract Timer getBluetoothUnoptimizedScanBackgroundTimer();
854 public abstract Counter getBluetoothScanResultCounter();
855 public abstract Counter getBluetoothScanResultBgCounter();
856
857 public abstract long[] getCpuFreqTimes(int which);
858 public abstract long[] getScreenOffCpuFreqTimes(int which);
859 /**
860 * Returns cpu active time of an uid.
861 */
862 public abstract long getCpuActiveTime();
863
864 /**
865 * Returns cpu active time of a UID while in the specified process state.
866 */
867 public abstract long getCpuActiveTime(int procState);
868
869 /**
870 * Returns cpu times of an uid on each cluster
871 */
872 public abstract long[] getCpuClusterTimes();
873
874 /**
875 * Returns cpu times of an uid at a particular process state.
876 */
877 public abstract boolean getCpuFreqTimes(@NonNull long[] timesInFreqMs, int procState);
878
879 /**
880 * Returns cpu times of an uid while the screen if off at a particular process state.
881 */
882 public abstract boolean getScreenOffCpuFreqTimes(@NonNull long[] timesInFreqMs,
883 int procState);
884
885 // Note: the following times are disjoint. They can be added together to find the
886 // total time a uid has had any processes running at all.
887
888 /**
889 * Time this uid has any processes in the top state.
890 */
891 public static final int PROCESS_STATE_TOP = 0;
892 /**
893 * Time this uid has any process with a started foreground service, but
894 * none in the "top" state.
895 */
896 public static final int PROCESS_STATE_FOREGROUND_SERVICE = 1;
897 /**
898 * Time this uid has any process in an active foreground state, but none in the
899 * "foreground service" or better state. Persistent and other foreground states go here.
900 */
901 public static final int PROCESS_STATE_FOREGROUND = 2;
902 /**
903 * Time this uid has any process in an active background state, but none in the
904 * "foreground" or better state.
905 */
906 public static final int PROCESS_STATE_BACKGROUND = 3;
907 /**
908 * Time this uid has any process that is top while the device is sleeping, but not
909 * active for any other reason. We kind-of consider it a kind of cached process
910 * for execution restrictions.
911 */
912 public static final int PROCESS_STATE_TOP_SLEEPING = 4;
913 /**
914 * Time this uid has any process that is in the background but it has an activity
915 * marked as "can't save state". This is essentially a cached process, though the
916 * system will try much harder than normal to avoid killing it.
917 */
918 public static final int PROCESS_STATE_HEAVY_WEIGHT = 5;
919 /**
920 * Time this uid has any processes that are sitting around cached, not in one of the
921 * other active states.
922 */
923 public static final int PROCESS_STATE_CACHED = 6;
924 /**
925 * Total number of process states we track.
926 */
927 public static final int NUM_PROCESS_STATE = 7;
928 /**
929 * State of the UID when it has no running processes. It is intentionally out of
930 * bounds 0..NUM_PROCESS_STATE.
931 */
932 public static final int PROCESS_STATE_NONEXISTENT = NUM_PROCESS_STATE;
933
934 // Used in dump
935 static final String[] PROCESS_STATE_NAMES = {
936 "Top", "Fg Service", "Foreground", "Background", "Top Sleeping", "Heavy Weight",
937 "Cached"
938 };
939
940 // Used in checkin dump
941 @VisibleForTesting
942 public static final String[] UID_PROCESS_TYPES = {
943 "T", // TOP
944 "FS", // FOREGROUND_SERVICE
945 "F", // FOREGROUND
946 "B", // BACKGROUND
947 "TS", // TOP_SLEEPING
948 "HW", // HEAVY_WEIGHT
949 "C" // CACHED
950 };
951
952 public abstract long getProcessStateTime(int state, long elapsedRealtimeUs, int which);
953 public abstract Timer getProcessStateTimer(int state);
954
955 public abstract Timer getVibratorOnTimer();
956
957 public static final int NUM_WIFI_BATCHED_SCAN_BINS = 5;
958
959 /**
960 * Note that these must match the constants in android.os.PowerManager.
961 * Also, if the user activity types change, the BatteryStatsImpl.VERSION must
962 * also be bumped.
963 */
964 static final String[] USER_ACTIVITY_TYPES = {
965 "other", "button", "touch", "accessibility", "attention", "faceDown", "deviceState"
966 };
967
968 public static final int NUM_USER_ACTIVITY_TYPES = USER_ACTIVITY_TYPES.length;
969
970 public abstract void noteUserActivityLocked(int type);
971 public abstract boolean hasUserActivity();
972 public abstract int getUserActivityCount(int type, int which);
973
974 public abstract boolean hasNetworkActivity();
975 @UnsupportedAppUsage
976 public abstract long getNetworkActivityBytes(int type, int which);
977 public abstract long getNetworkActivityPackets(int type, int which);
978 @UnsupportedAppUsage
979 public abstract long getMobileRadioActiveTime(int which);
980
981 /**
982 * Returns the amount of time (in microseconds) this UID was in the specified processState.
983 */
984 public abstract long getMobileRadioActiveTimeInProcessState(
985 @BatteryConsumer.ProcessState int processState);
986
987 public abstract int getMobileRadioActiveCount(int which);
988
989 /**
990 * Get the total cpu time (in microseconds) this UID had processes executing in userspace.
991 */
992 public abstract long getUserCpuTimeUs(int which);
993
994 /**
995 * Get the total cpu time (in microseconds) this UID had processes executing kernel syscalls.
996 */
997 public abstract long getSystemCpuTimeUs(int which);
998
999 /**
1000 * Returns the approximate cpu time (in microseconds) spent at a certain CPU speed for a
1001 * given CPU cluster.
1002 * @param cluster the index of the CPU cluster.
1003 * @param step the index of the CPU speed. This is not the actual speed of the CPU.
1004 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1005 * @see com.android.internal.os.PowerProfile#getNumCpuClusters()
1006 * @see com.android.internal.os.PowerProfile#getNumSpeedStepsInCpuCluster(int)
1007 */
1008 public abstract long getTimeAtCpuSpeed(int cluster, int step, int which);
1009
1010 /**
1011 * Returns the number of times this UID woke up the Application Processor to
1012 * process a mobile radio packet.
1013 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1014 */
1015 public abstract long getMobileRadioApWakeupCount(int which);
1016
1017 /**
1018 * Returns the number of times this UID woke up the Application Processor to
1019 * process a WiFi packet.
1020 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1021 */
1022 public abstract long getWifiRadioApWakeupCount(int which);
1023
1024 /**
1025 * Appends the deferred jobs data to the StringBuilder passed in, in checkin format
1026 * @param sb StringBuilder that can be overwritten with the deferred jobs data
1027 * @param which one of STATS_*
1028 */
1029 public abstract void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which);
1030
1031 /**
1032 * Appends the deferred jobs data to the StringBuilder passed in
1033 * @param sb StringBuilder that can be overwritten with the deferred jobs data
1034 * @param which one of STATS_*
1035 */
1036 public abstract void getDeferredJobsLineLocked(StringBuilder sb, int which);
1037
1038 /**
1039 * Returns the battery consumption (in microcoulombs) of bluetooth for this uid,
1040 * derived from on device power measurement data.
1041 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1042 *
1043 * {@hide}
1044 */
1045 public abstract long getBluetoothMeasuredBatteryConsumptionUC();
1046
1047 /**
1048 * Returns the battery consumption (in microcoulombs) of the uid's bluetooth usage
1049 * when in the specified process state.
1050 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1051 *
1052 * {@hide}
1053 */
1054 public abstract long getBluetoothMeasuredBatteryConsumptionUC(
1055 @BatteryConsumer.ProcessState int processState);
1056
1057 /**
1058 * Returns the battery consumption (in microcoulombs) of the uid's cpu usage, derived from
1059 * on device power measurement data.
1060 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1061 *
1062 * {@hide}
1063 */
1064 public abstract long getCpuMeasuredBatteryConsumptionUC();
1065
1066 /**
1067 * Returns the battery consumption (in microcoulombs) of the uid's cpu usage when in the
1068 * specified process state.
1069 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1070 *
1071 * {@hide}
1072 */
1073 public abstract long getCpuMeasuredBatteryConsumptionUC(
1074 @BatteryConsumer.ProcessState int processState);
1075
1076 /**
1077 * Returns the battery consumption (in microcoulombs) of the uid's GNSS usage, derived from
1078 * on device power measurement data.
1079 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1080 *
1081 * {@hide}
1082 */
1083 public abstract long getGnssMeasuredBatteryConsumptionUC();
1084
1085 /**
1086 * Returns the battery consumption (in microcoulombs) of the uid's radio usage, derived from
1087 * on device power measurement data.
1088 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1089 *
1090 * {@hide}
1091 */
1092 public abstract long getMobileRadioMeasuredBatteryConsumptionUC();
1093
1094 /**
1095 * Returns the battery consumption (in microcoulombs) of the uid's radio usage when in the
1096 * specified process state.
1097 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1098 *
1099 * {@hide}
1100 */
1101 public abstract long getMobileRadioMeasuredBatteryConsumptionUC(
1102 @BatteryConsumer.ProcessState int processState);
1103
1104 /**
1105 * Returns the battery consumption (in microcoulombs) of the screen while on and uid active,
1106 * derived from on device power measurement data.
1107 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1108 *
1109 * {@hide}
1110 */
1111 public abstract long getScreenOnMeasuredBatteryConsumptionUC();
1112
1113 /**
1114 * Returns the battery consumption (in microcoulombs) of wifi for this uid,
1115 * derived from on device power measurement data.
1116 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1117 *
1118 * {@hide}
1119 */
1120 public abstract long getWifiMeasuredBatteryConsumptionUC();
1121
1122 /**
1123 * Returns the battery consumption (in microcoulombs) of the uid's wifi usage when in the
1124 * specified process state.
1125 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
1126 *
1127 * {@hide}
1128 */
1129 public abstract long getWifiMeasuredBatteryConsumptionUC(
1130 @BatteryConsumer.ProcessState int processState);
1131
1132
1133 /**
1134 * Returns the battery consumption (in microcoulombs) used by this uid for each
1135 * {@link android.hardware.power.stats.EnergyConsumer.ordinal} of (custom) energy consumer
1136 * type {@link android.hardware.power.stats.EnergyConsumerType#OTHER}).
1137 *
1138 * @return charge (in microcoulombs) consumed since last reset for each (custom) energy
1139 * consumer of type OTHER, indexed by their ordinal. Returns null if no energy
1140 * reporting is supported.
1141 *
1142 * {@hide}
1143 */
1144 public abstract @Nullable long[] getCustomConsumerMeasuredBatteryConsumptionUC();
1145
1146 public static abstract class Sensor {
1147
1148 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1149 public Sensor() {}
1150
1151 /*
1152 * FIXME: it's not correct to use this magic value because it
1153 * could clash with a sensor handle (which are defined by
1154 * the sensor HAL, and therefore out of our control
1155 */
1156 // Magic sensor number for the GPS.
1157 @UnsupportedAppUsage
1158 public static final int GPS = -10000;
1159
1160 @UnsupportedAppUsage
1161 public abstract int getHandle();
1162
1163 @UnsupportedAppUsage
1164 public abstract Timer getSensorTime();
1165
1166 /** Returns a Timer for sensor usage when app is in the background. */
1167 public abstract Timer getSensorBackgroundTime();
1168 }
1169
1170 public class Pid {
1171 public int mWakeNesting;
1172 public long mWakeSumMs;
1173 public long mWakeStartMs;
1174 }
1175
1176 /**
1177 * The statistics associated with a particular process.
1178 */
1179 public static abstract class Proc {
1180
1181 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1182 public Proc() {}
1183
1184 public static class ExcessivePower {
1185
1186 @UnsupportedAppUsage
1187 public ExcessivePower() {
1188 }
1189
1190 public static final int TYPE_WAKE = 1;
1191 public static final int TYPE_CPU = 2;
1192
1193 @UnsupportedAppUsage
1194 public int type;
1195 @UnsupportedAppUsage
1196 public long overTime;
1197 @UnsupportedAppUsage
1198 public long usedTime;
1199 }
1200
1201 /**
1202 * Returns true if this process is still active in the battery stats.
1203 */
1204 public abstract boolean isActive();
1205
1206 /**
1207 * Returns the total time (in milliseconds) spent executing in user code.
1208 *
1209 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1210 */
1211 @UnsupportedAppUsage
1212 public abstract long getUserTime(int which);
1213
1214 /**
1215 * Returns the total time (in milliseconds) spent executing in system code.
1216 *
1217 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1218 */
1219 @UnsupportedAppUsage
1220 public abstract long getSystemTime(int which);
1221
1222 /**
1223 * Returns the number of times the process has been started.
1224 *
1225 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1226 */
1227 @UnsupportedAppUsage
1228 public abstract int getStarts(int which);
1229
1230 /**
1231 * Returns the number of times the process has crashed.
1232 *
1233 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1234 */
1235 public abstract int getNumCrashes(int which);
1236
1237 /**
1238 * Returns the number of times the process has ANRed.
1239 *
1240 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1241 */
1242 public abstract int getNumAnrs(int which);
1243
1244 /**
1245 * Returns the cpu time (milliseconds) spent while the process was in the foreground.
1246 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1247 * @return foreground cpu time in microseconds
1248 */
1249 @UnsupportedAppUsage
1250 public abstract long getForegroundTime(int which);
1251
1252 @UnsupportedAppUsage
1253 public abstract int countExcessivePowers();
1254
1255 @UnsupportedAppUsage
1256 public abstract ExcessivePower getExcessivePower(int i);
1257 }
1258
1259 /**
1260 * The statistics associated with a particular package.
1261 */
1262 public static abstract class Pkg {
1263
1264 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1265 public Pkg() {}
1266
1267 /**
1268 * Returns information about all wakeup alarms that have been triggered for this
1269 * package. The mapping keys are tag names for the alarms, the counter contains
1270 * the number of times the alarm was triggered while on battery.
1271 */
1272 @UnsupportedAppUsage
1273 public abstract ArrayMap<String, ? extends Counter> getWakeupAlarmStats();
1274
1275 /**
1276 * Returns a mapping containing service statistics.
1277 */
1278 @UnsupportedAppUsage
1279 public abstract ArrayMap<String, ? extends Serv> getServiceStats();
1280
1281 /**
1282 * The statistics associated with a particular service.
1283 */
1284 public static abstract class Serv {
1285
1286 /**
1287 * Returns the amount of time spent started.
1288 *
1289 * @param batteryUptime elapsed uptime on battery in microseconds.
1290 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1291 * @return
1292 */
1293 @UnsupportedAppUsage
1294 public abstract long getStartTime(long batteryUptime, int which);
1295
1296 /**
1297 * Returns the total number of times startService() has been called.
1298 *
1299 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1300 */
1301 @UnsupportedAppUsage
1302 public abstract int getStarts(int which);
1303
1304 /**
1305 * Returns the total number times the service has been launched.
1306 *
1307 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
1308 */
1309 @UnsupportedAppUsage
1310 public abstract int getLaunches(int which);
1311 }
1312 }
1313 }
1314
1315 public static final class LevelStepTracker {
1316 public long mLastStepTime = -1;
1317 public int mNumStepDurations;
1318 public final long[] mStepDurations;
1319
1320 public LevelStepTracker(int maxLevelSteps) {
1321 mStepDurations = new long[maxLevelSteps];
1322 }
1323
1324 public LevelStepTracker(int numSteps, long[] steps) {
1325 mNumStepDurations = numSteps;
1326 mStepDurations = new long[numSteps];
1327 System.arraycopy(steps, 0, mStepDurations, 0, numSteps);
1328 }
1329
1330 public long getDurationAt(int index) {
1331 return mStepDurations[index] & STEP_LEVEL_TIME_MASK;
1332 }
1333
1334 public int getLevelAt(int index) {
1335 return (int)((mStepDurations[index] & STEP_LEVEL_LEVEL_MASK)
1336 >> STEP_LEVEL_LEVEL_SHIFT);
1337 }
1338
1339 public int getInitModeAt(int index) {
1340 return (int)((mStepDurations[index] & STEP_LEVEL_INITIAL_MODE_MASK)
1341 >> STEP_LEVEL_INITIAL_MODE_SHIFT);
1342 }
1343
1344 public int getModModeAt(int index) {
1345 return (int)((mStepDurations[index] & STEP_LEVEL_MODIFIED_MODE_MASK)
1346 >> STEP_LEVEL_MODIFIED_MODE_SHIFT);
1347 }
1348
1349 private void appendHex(long val, int topOffset, StringBuilder out) {
1350 boolean hasData = false;
1351 while (topOffset >= 0) {
1352 int digit = (int)( (val>>topOffset) & 0xf );
1353 topOffset -= 4;
1354 if (!hasData && digit == 0) {
1355 continue;
1356 }
1357 hasData = true;
1358 if (digit >= 0 && digit <= 9) {
1359 out.append((char)('0' + digit));
1360 } else {
1361 out.append((char)('a' + digit - 10));
1362 }
1363 }
1364 }
1365
1366 public void encodeEntryAt(int index, StringBuilder out) {
1367 long item = mStepDurations[index];
1368 long duration = item & STEP_LEVEL_TIME_MASK;
1369 int level = (int)((item & STEP_LEVEL_LEVEL_MASK)
1370 >> STEP_LEVEL_LEVEL_SHIFT);
1371 int initMode = (int)((item & STEP_LEVEL_INITIAL_MODE_MASK)
1372 >> STEP_LEVEL_INITIAL_MODE_SHIFT);
1373 int modMode = (int)((item & STEP_LEVEL_MODIFIED_MODE_MASK)
1374 >> STEP_LEVEL_MODIFIED_MODE_SHIFT);
1375 switch ((initMode&STEP_LEVEL_MODE_SCREEN_STATE) + 1) {
1376 case Display.STATE_OFF: out.append('f'); break;
1377 case Display.STATE_ON: out.append('o'); break;
1378 case Display.STATE_DOZE: out.append('d'); break;
1379 case Display.STATE_DOZE_SUSPEND: out.append('z'); break;
1380 }
1381 if ((initMode&STEP_LEVEL_MODE_POWER_SAVE) != 0) {
1382 out.append('p');
1383 }
1384 if ((initMode&STEP_LEVEL_MODE_DEVICE_IDLE) != 0) {
1385 out.append('i');
1386 }
1387 switch ((modMode&STEP_LEVEL_MODE_SCREEN_STATE) + 1) {
1388 case Display.STATE_OFF: out.append('F'); break;
1389 case Display.STATE_ON: out.append('O'); break;
1390 case Display.STATE_DOZE: out.append('D'); break;
1391 case Display.STATE_DOZE_SUSPEND: out.append('Z'); break;
1392 }
1393 if ((modMode&STEP_LEVEL_MODE_POWER_SAVE) != 0) {
1394 out.append('P');
1395 }
1396 if ((modMode&STEP_LEVEL_MODE_DEVICE_IDLE) != 0) {
1397 out.append('I');
1398 }
1399 out.append('-');
1400 appendHex(level, 4, out);
1401 out.append('-');
1402 appendHex(duration, STEP_LEVEL_LEVEL_SHIFT-4, out);
1403 }
1404
1405 public void decodeEntryAt(int index, String value) {
1406 final int N = value.length();
1407 int i = 0;
1408 char c;
1409 long out = 0;
1410 while (i < N && (c=value.charAt(i)) != '-') {
1411 i++;
1412 switch (c) {
1413 case 'f': out |= (((long)Display.STATE_OFF-1)<<STEP_LEVEL_INITIAL_MODE_SHIFT);
1414 break;
1415 case 'o': out |= (((long)Display.STATE_ON-1)<<STEP_LEVEL_INITIAL_MODE_SHIFT);
1416 break;
1417 case 'd': out |= (((long)Display.STATE_DOZE-1)<<STEP_LEVEL_INITIAL_MODE_SHIFT);
1418 break;
1419 case 'z': out |= (((long)Display.STATE_DOZE_SUSPEND-1)
1420 << STEP_LEVEL_INITIAL_MODE_SHIFT);
1421 break;
1422 case 'p': out |= (((long)STEP_LEVEL_MODE_POWER_SAVE)
1423 << STEP_LEVEL_INITIAL_MODE_SHIFT);
1424 break;
1425 case 'i': out |= (((long)STEP_LEVEL_MODE_DEVICE_IDLE)
1426 << STEP_LEVEL_INITIAL_MODE_SHIFT);
1427 break;
1428 case 'F': out |= (((long)Display.STATE_OFF-1)<<STEP_LEVEL_MODIFIED_MODE_SHIFT);
1429 break;
1430 case 'O': out |= (((long)Display.STATE_ON-1)<<STEP_LEVEL_MODIFIED_MODE_SHIFT);
1431 break;
1432 case 'D': out |= (((long)Display.STATE_DOZE-1)<<STEP_LEVEL_MODIFIED_MODE_SHIFT);
1433 break;
1434 case 'Z': out |= (((long)Display.STATE_DOZE_SUSPEND-1)
1435 << STEP_LEVEL_MODIFIED_MODE_SHIFT);
1436 break;
1437 case 'P': out |= (((long)STEP_LEVEL_MODE_POWER_SAVE)
1438 << STEP_LEVEL_MODIFIED_MODE_SHIFT);
1439 break;
1440 case 'I': out |= (((long)STEP_LEVEL_MODE_DEVICE_IDLE)
1441 << STEP_LEVEL_MODIFIED_MODE_SHIFT);
1442 break;
1443 }
1444 }
1445 i++;
1446 long level = 0;
1447 while (i < N && (c=value.charAt(i)) != '-') {
1448 i++;
1449 level <<= 4;
1450 if (c >= '0' && c <= '9') {
1451 level += c - '0';
1452 } else if (c >= 'a' && c <= 'f') {
1453 level += c - 'a' + 10;
1454 } else if (c >= 'A' && c <= 'F') {
1455 level += c - 'A' + 10;
1456 }
1457 }
1458 i++;
1459 out |= (level << STEP_LEVEL_LEVEL_SHIFT) & STEP_LEVEL_LEVEL_MASK;
1460 long duration = 0;
1461 while (i < N && (c=value.charAt(i)) != '-') {
1462 i++;
1463 duration <<= 4;
1464 if (c >= '0' && c <= '9') {
1465 duration += c - '0';
1466 } else if (c >= 'a' && c <= 'f') {
1467 duration += c - 'a' + 10;
1468 } else if (c >= 'A' && c <= 'F') {
1469 duration += c - 'A' + 10;
1470 }
1471 }
1472 mStepDurations[index] = out | (duration & STEP_LEVEL_TIME_MASK);
1473 }
1474
1475 public void init() {
1476 mLastStepTime = -1;
1477 mNumStepDurations = 0;
1478 }
1479
1480 public void clearTime() {
1481 mLastStepTime = -1;
1482 }
1483
1484 public long computeTimePerLevel() {
1485 final long[] steps = mStepDurations;
1486 final int numSteps = mNumStepDurations;
1487
1488 // For now we'll do a simple average across all steps.
1489 if (numSteps <= 0) {
1490 return -1;
1491 }
1492 long total = 0;
1493 for (int i=0; i<numSteps; i++) {
1494 total += steps[i] & STEP_LEVEL_TIME_MASK;
1495 }
1496 return total / numSteps;
1497 /*
1498 long[] buckets = new long[numSteps];
1499 int numBuckets = 0;
1500 int numToAverage = 4;
1501 int i = 0;
1502 while (i < numSteps) {
1503 long totalTime = 0;
1504 int num = 0;
1505 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
1506 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
1507 num++;
1508 }
1509 buckets[numBuckets] = totalTime / num;
1510 numBuckets++;
1511 numToAverage *= 2;
1512 i += num;
1513 }
1514 if (numBuckets < 1) {
1515 return -1;
1516 }
1517 long averageTime = buckets[numBuckets-1];
1518 for (i=numBuckets-2; i>=0; i--) {
1519 averageTime = (averageTime + buckets[i]) / 2;
1520 }
1521 return averageTime;
1522 */
1523 }
1524
1525 public long computeTimeEstimate(long modesOfInterest, long modeValues,
1526 int[] outNumOfInterest) {
1527 final long[] steps = mStepDurations;
1528 final int count = mNumStepDurations;
1529 if (count <= 0) {
1530 return -1;
1531 }
1532 long total = 0;
1533 int numOfInterest = 0;
1534 for (int i=0; i<count; i++) {
1535 long initMode = (steps[i] & STEP_LEVEL_INITIAL_MODE_MASK)
1536 >> STEP_LEVEL_INITIAL_MODE_SHIFT;
1537 long modMode = (steps[i] & STEP_LEVEL_MODIFIED_MODE_MASK)
1538 >> STEP_LEVEL_MODIFIED_MODE_SHIFT;
1539 // If the modes of interest didn't change during this step period...
1540 if ((modMode&modesOfInterest) == 0) {
1541 // And the mode values during this period match those we are measuring...
1542 if ((initMode&modesOfInterest) == modeValues) {
1543 // Then this can be used to estimate the total time!
1544 numOfInterest++;
1545 total += steps[i] & STEP_LEVEL_TIME_MASK;
1546 }
1547 }
1548 }
1549 if (numOfInterest <= 0) {
1550 return -1;
1551 }
1552
1553 if (outNumOfInterest != null) {
1554 outNumOfInterest[0] = numOfInterest;
1555 }
1556
1557 // The estimated time is the average time we spend in each level, multipled
1558 // by 100 -- the total number of battery levels
1559 return (total / numOfInterest) * 100;
1560 }
1561
1562 public void addLevelSteps(int numStepLevels, long modeBits, long elapsedRealtime) {
1563 int stepCount = mNumStepDurations;
1564 final long lastStepTime = mLastStepTime;
1565 if (lastStepTime >= 0 && numStepLevels > 0) {
1566 final long[] steps = mStepDurations;
1567 long duration = elapsedRealtime - lastStepTime;
1568 for (int i=0; i<numStepLevels; i++) {
1569 System.arraycopy(steps, 0, steps, 1, steps.length-1);
1570 long thisDuration = duration / (numStepLevels-i);
1571 duration -= thisDuration;
1572 if (thisDuration > STEP_LEVEL_TIME_MASK) {
1573 thisDuration = STEP_LEVEL_TIME_MASK;
1574 }
1575 steps[0] = thisDuration | modeBits;
1576 }
1577 stepCount += numStepLevels;
1578 if (stepCount > steps.length) {
1579 stepCount = steps.length;
1580 }
1581 }
1582 mNumStepDurations = stepCount;
1583 mLastStepTime = elapsedRealtime;
1584 }
1585
1586 public void readFromParcel(Parcel in) {
1587 final int N = in.readInt();
1588 if (N > mStepDurations.length) {
1589 throw new ParcelFormatException("more step durations than available: " + N);
1590 }
1591 mNumStepDurations = N;
1592 for (int i=0; i<N; i++) {
1593 mStepDurations[i] = in.readLong();
1594 }
1595 }
1596
1597 public void writeToParcel(Parcel out) {
1598 final int N = mNumStepDurations;
1599 out.writeInt(N);
1600 for (int i=0; i<N; i++) {
1601 out.writeLong(mStepDurations[i]);
1602 }
1603 }
1604 }
1605
1606 public static final class PackageChange {
1607 public String mPackageName;
1608 public boolean mUpdate;
1609 public long mVersionCode;
1610 }
1611
1612 public static final class DailyItem {
1613 public long mStartTime;
1614 public long mEndTime;
1615 public LevelStepTracker mDischargeSteps;
1616 public LevelStepTracker mChargeSteps;
1617 public ArrayList<PackageChange> mPackageChanges;
1618 }
1619
1620 public abstract DailyItem getDailyItemLocked(int daysAgo);
1621
1622 public abstract long getCurrentDailyStartTime();
1623
1624 public abstract long getNextMinDailyDeadline();
1625
1626 public abstract long getNextMaxDailyDeadline();
1627
1628 /**
1629 * Returns the total number of frequencies across all CPU clusters.
1630 */
1631 public abstract int getCpuFreqCount();
1632
1633 public abstract long[] getCpuFreqs();
1634
1635 public final static class HistoryTag {
1636 public String string;
1637 public int uid;
1638
1639 public int poolIdx;
1640
1641 public void setTo(HistoryTag o) {
1642 string = o.string;
1643 uid = o.uid;
1644 poolIdx = o.poolIdx;
1645 }
1646
1647 public void setTo(String _string, int _uid) {
1648 string = _string;
1649 uid = _uid;
1650 poolIdx = -1;
1651 }
1652
1653 public void writeToParcel(Parcel dest, int flags) {
1654 dest.writeString(string);
1655 dest.writeInt(uid);
1656 }
1657
1658 public void readFromParcel(Parcel src) {
1659 string = src.readString();
1660 uid = src.readInt();
1661 poolIdx = -1;
1662 }
1663
1664 @Override
1665 public boolean equals(@Nullable Object o) {
1666 if (this == o) return true;
1667 if (o == null || getClass() != o.getClass()) return false;
1668
1669 HistoryTag that = (HistoryTag) o;
1670
1671 if (uid != that.uid) return false;
1672 if (!string.equals(that.string)) return false;
1673
1674 return true;
1675 }
1676
1677 @Override
1678 public int hashCode() {
1679 int result = string.hashCode();
1680 result = 31 * result + uid;
1681 return result;
1682 }
1683 }
1684
1685 /**
1686 * Optional detailed information that can go into a history step. This is typically
1687 * generated each time the battery level changes.
1688 */
1689 public final static class HistoryStepDetails {
1690 // Time (in 1/100 second) spent in user space and the kernel since the last step.
1691 public int userTime;
1692 public int systemTime;
1693
1694 // Top three apps using CPU in the last step, with times in 1/100 second.
1695 public int appCpuUid1;
1696 public int appCpuUTime1;
1697 public int appCpuSTime1;
1698 public int appCpuUid2;
1699 public int appCpuUTime2;
1700 public int appCpuSTime2;
1701 public int appCpuUid3;
1702 public int appCpuUTime3;
1703 public int appCpuSTime3;
1704
1705 // Information from /proc/stat
1706 public int statUserTime;
1707 public int statSystemTime;
1708 public int statIOWaitTime;
1709 public int statIrqTime;
1710 public int statSoftIrqTime;
1711 public int statIdlTime;
1712
1713 // Low power state stats
1714 public String statSubsystemPowerState;
1715
1716 public HistoryStepDetails() {
1717 clear();
1718 }
1719
1720 public void clear() {
1721 userTime = systemTime = 0;
1722 appCpuUid1 = appCpuUid2 = appCpuUid3 = -1;
1723 appCpuUTime1 = appCpuSTime1 = appCpuUTime2 = appCpuSTime2
1724 = appCpuUTime3 = appCpuSTime3 = 0;
1725 }
1726
1727 public void writeToParcel(Parcel out) {
1728 out.writeInt(userTime);
1729 out.writeInt(systemTime);
1730 out.writeInt(appCpuUid1);
1731 out.writeInt(appCpuUTime1);
1732 out.writeInt(appCpuSTime1);
1733 out.writeInt(appCpuUid2);
1734 out.writeInt(appCpuUTime2);
1735 out.writeInt(appCpuSTime2);
1736 out.writeInt(appCpuUid3);
1737 out.writeInt(appCpuUTime3);
1738 out.writeInt(appCpuSTime3);
1739 out.writeInt(statUserTime);
1740 out.writeInt(statSystemTime);
1741 out.writeInt(statIOWaitTime);
1742 out.writeInt(statIrqTime);
1743 out.writeInt(statSoftIrqTime);
1744 out.writeInt(statIdlTime);
1745 out.writeString(statSubsystemPowerState);
1746 }
1747
1748 public void readFromParcel(Parcel in) {
1749 userTime = in.readInt();
1750 systemTime = in.readInt();
1751 appCpuUid1 = in.readInt();
1752 appCpuUTime1 = in.readInt();
1753 appCpuSTime1 = in.readInt();
1754 appCpuUid2 = in.readInt();
1755 appCpuUTime2 = in.readInt();
1756 appCpuSTime2 = in.readInt();
1757 appCpuUid3 = in.readInt();
1758 appCpuUTime3 = in.readInt();
1759 appCpuSTime3 = in.readInt();
1760 statUserTime = in.readInt();
1761 statSystemTime = in.readInt();
1762 statIOWaitTime = in.readInt();
1763 statIrqTime = in.readInt();
1764 statSoftIrqTime = in.readInt();
1765 statIdlTime = in.readInt();
1766 statSubsystemPowerState = in.readString();
1767 }
1768 }
1769
1770 /**
1771 * Battery history record.
1772 */
1773 public static final class HistoryItem {
1774 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1775 public HistoryItem next;
1776
1777 // The time of this event in milliseconds, as per SystemClock.elapsedRealtime().
1778 @UnsupportedAppUsage
1779 public long time;
1780
1781 @UnsupportedAppUsage
1782 public static final byte CMD_UPDATE = 0; // These can be written as deltas
1783 public static final byte CMD_NULL = -1;
1784 public static final byte CMD_START = 4;
1785 public static final byte CMD_CURRENT_TIME = 5;
1786 public static final byte CMD_OVERFLOW = 6;
1787 public static final byte CMD_RESET = 7;
1788 public static final byte CMD_SHUTDOWN = 8;
1789
1790 @UnsupportedAppUsage
1791 public byte cmd = CMD_NULL;
1792
1793 /**
1794 * Return whether the command code is a delta data update.
1795 */
1796 public boolean isDeltaData() {
1797 return cmd == CMD_UPDATE;
1798 }
1799
1800 @UnsupportedAppUsage
1801 public byte batteryLevel;
1802 @UnsupportedAppUsage
1803 public byte batteryStatus;
1804 @UnsupportedAppUsage
1805 public byte batteryHealth;
1806 @UnsupportedAppUsage
1807 public byte batteryPlugType;
1808
1809 public short batteryTemperature;
1810 // Battery voltage in millivolts (mV).
1811 @UnsupportedAppUsage
1812 public char batteryVoltage;
1813
1814 // The charge of the battery in micro-Ampere-hours.
1815 public int batteryChargeUah;
1816
1817 public double modemRailChargeMah;
1818 public double wifiRailChargeMah;
1819
1820 // Constants from SCREEN_BRIGHTNESS_*
1821 public static final int STATE_BRIGHTNESS_SHIFT = 0;
1822 public static final int STATE_BRIGHTNESS_MASK = 0x7;
1823 // Constants from SIGNAL_STRENGTH_*
1824 public static final int STATE_PHONE_SIGNAL_STRENGTH_SHIFT = 3;
1825 public static final int STATE_PHONE_SIGNAL_STRENGTH_MASK = 0x7 << STATE_PHONE_SIGNAL_STRENGTH_SHIFT;
1826 // Constants from ServiceState.STATE_*
1827 public static final int STATE_PHONE_STATE_SHIFT = 6;
1828 public static final int STATE_PHONE_STATE_MASK = 0x7 << STATE_PHONE_STATE_SHIFT;
1829 // Constants from DATA_CONNECTION_*
1830 public static final int STATE_DATA_CONNECTION_SHIFT = 9;
1831 public static final int STATE_DATA_CONNECTION_MASK = 0x1f << STATE_DATA_CONNECTION_SHIFT;
1832
1833 // These states always appear directly in the first int token
1834 // of a delta change; they should be ones that change relatively
1835 // frequently.
1836 public static final int STATE_CPU_RUNNING_FLAG = 1<<31;
1837 public static final int STATE_WAKE_LOCK_FLAG = 1<<30;
1838 public static final int STATE_GPS_ON_FLAG = 1<<29;
1839 public static final int STATE_WIFI_FULL_LOCK_FLAG = 1<<28;
1840 public static final int STATE_WIFI_SCAN_FLAG = 1<<27;
1841 public static final int STATE_WIFI_RADIO_ACTIVE_FLAG = 1<<26;
1842 public static final int STATE_MOBILE_RADIO_ACTIVE_FLAG = 1<<25;
1843 // Do not use, this is used for coulomb delta count.
1844 private static final int STATE_RESERVED_0 = 1<<24;
1845 // These are on the lower bits used for the command; if they change
1846 // we need to write another int of data.
1847 public static final int STATE_SENSOR_ON_FLAG = 1<<23;
1848 public static final int STATE_AUDIO_ON_FLAG = 1<<22;
1849 public static final int STATE_PHONE_SCANNING_FLAG = 1<<21;
1850 public static final int STATE_SCREEN_ON_FLAG = 1<<20; // consider moving to states2
1851 public static final int STATE_BATTERY_PLUGGED_FLAG = 1<<19; // consider moving to states2
1852 public static final int STATE_SCREEN_DOZE_FLAG = 1 << 18;
1853 // empty slot
1854 public static final int STATE_WIFI_MULTICAST_ON_FLAG = 1<<16;
1855
1856 public static final int MOST_INTERESTING_STATES =
1857 STATE_BATTERY_PLUGGED_FLAG | STATE_SCREEN_ON_FLAG | STATE_SCREEN_DOZE_FLAG;
1858
1859 public static final int SETTLE_TO_ZERO_STATES = 0xffff0000 & ~MOST_INTERESTING_STATES;
1860
1861 @UnsupportedAppUsage
1862 public int states;
1863
1864 // Constants from WIFI_SUPPL_STATE_*
1865 public static final int STATE2_WIFI_SUPPL_STATE_SHIFT = 0;
1866 public static final int STATE2_WIFI_SUPPL_STATE_MASK = 0xf;
1867 // Values for NUM_WIFI_SIGNAL_STRENGTH_BINS
1868 public static final int STATE2_WIFI_SIGNAL_STRENGTH_SHIFT = 4;
1869 public static final int STATE2_WIFI_SIGNAL_STRENGTH_MASK =
1870 0x7 << STATE2_WIFI_SIGNAL_STRENGTH_SHIFT;
1871 // Values for NUM_GPS_SIGNAL_QUALITY_LEVELS
1872 public static final int STATE2_GPS_SIGNAL_QUALITY_SHIFT = 7;
1873 public static final int STATE2_GPS_SIGNAL_QUALITY_MASK =
1874 0x1 << STATE2_GPS_SIGNAL_QUALITY_SHIFT;
1875
1876 public static final int STATE2_POWER_SAVE_FLAG = 1<<31;
1877 public static final int STATE2_VIDEO_ON_FLAG = 1<<30;
1878 public static final int STATE2_WIFI_RUNNING_FLAG = 1<<29;
1879 public static final int STATE2_WIFI_ON_FLAG = 1<<28;
1880 public static final int STATE2_FLASHLIGHT_FLAG = 1<<27;
1881 public static final int STATE2_DEVICE_IDLE_SHIFT = 25;
1882 public static final int STATE2_DEVICE_IDLE_MASK = 0x3 << STATE2_DEVICE_IDLE_SHIFT;
1883 public static final int STATE2_CHARGING_FLAG = 1<<24;
1884 public static final int STATE2_PHONE_IN_CALL_FLAG = 1<<23;
1885 public static final int STATE2_BLUETOOTH_ON_FLAG = 1<<22;
1886 public static final int STATE2_CAMERA_FLAG = 1<<21;
1887 public static final int STATE2_BLUETOOTH_SCAN_FLAG = 1 << 20;
1888 public static final int STATE2_CELLULAR_HIGH_TX_POWER_FLAG = 1 << 19;
1889 public static final int STATE2_USB_DATA_LINK_FLAG = 1 << 18;
1890
1891 public static final int MOST_INTERESTING_STATES2 =
1892 STATE2_POWER_SAVE_FLAG | STATE2_WIFI_ON_FLAG | STATE2_DEVICE_IDLE_MASK
1893 | STATE2_CHARGING_FLAG | STATE2_PHONE_IN_CALL_FLAG | STATE2_BLUETOOTH_ON_FLAG;
1894
1895 public static final int SETTLE_TO_ZERO_STATES2 = 0xffff0000 & ~MOST_INTERESTING_STATES2;
1896
1897 @UnsupportedAppUsage
1898 public int states2;
1899
1900 // The wake lock that was acquired at this point.
1901 public HistoryTag wakelockTag;
1902
1903 // Kernel wakeup reason at this point.
1904 public HistoryTag wakeReasonTag;
1905
1906 // Non-null when there is more detailed information at this step.
1907 public HistoryStepDetails stepDetails;
1908
1909 public static final int EVENT_FLAG_START = 0x8000;
1910 public static final int EVENT_FLAG_FINISH = 0x4000;
1911
1912 // No event in this item.
1913 public static final int EVENT_NONE = 0x0000;
1914 // Event is about a process that is running.
1915 public static final int EVENT_PROC = 0x0001;
1916 // Event is about an application package that is in the foreground.
1917 public static final int EVENT_FOREGROUND = 0x0002;
1918 // Event is about an application package that is at the top of the screen.
1919 public static final int EVENT_TOP = 0x0003;
1920 // Event is about active sync operations.
1921 public static final int EVENT_SYNC = 0x0004;
1922 // Events for all additional wake locks aquired/release within a wake block.
1923 // These are not generated by default.
1924 public static final int EVENT_WAKE_LOCK = 0x0005;
1925 // Event is about an application executing a scheduled job.
1926 public static final int EVENT_JOB = 0x0006;
1927 // Events for users running.
1928 public static final int EVENT_USER_RUNNING = 0x0007;
1929 // Events for foreground user.
1930 public static final int EVENT_USER_FOREGROUND = 0x0008;
1931 // Event for connectivity changed.
1932 public static final int EVENT_CONNECTIVITY_CHANGED = 0x0009;
1933 // Event for becoming active taking us out of idle mode.
1934 public static final int EVENT_ACTIVE = 0x000a;
1935 // Event for a package being installed.
1936 public static final int EVENT_PACKAGE_INSTALLED = 0x000b;
1937 // Event for a package being uninstalled.
1938 public static final int EVENT_PACKAGE_UNINSTALLED = 0x000c;
1939 // Event for a package being uninstalled.
1940 public static final int EVENT_ALARM = 0x000d;
1941 // Record that we have decided we need to collect new stats data.
1942 public static final int EVENT_COLLECT_EXTERNAL_STATS = 0x000e;
1943 // Event for a package becoming inactive due to being unused for a period of time.
1944 public static final int EVENT_PACKAGE_INACTIVE = 0x000f;
1945 // Event for a package becoming active due to an interaction.
1946 public static final int EVENT_PACKAGE_ACTIVE = 0x0010;
1947 // Event for a package being on the temporary allowlist.
1948 public static final int EVENT_TEMP_WHITELIST = 0x0011;
1949 // Event for the screen waking up.
1950 public static final int EVENT_SCREEN_WAKE_UP = 0x0012;
1951 // Event for the UID that woke up the application processor.
1952 // Used for wakeups coming from WiFi, modem, etc.
1953 public static final int EVENT_WAKEUP_AP = 0x0013;
1954 // Event for reporting that a specific partial wake lock has been held for a long duration.
1955 public static final int EVENT_LONG_WAKE_LOCK = 0x0014;
1956
1957 // Number of event types.
1958 public static final int EVENT_COUNT = 0x0016;
1959 // Mask to extract out only the type part of the event.
1960 public static final int EVENT_TYPE_MASK = ~(EVENT_FLAG_START|EVENT_FLAG_FINISH);
1961
1962 public static final int EVENT_PROC_START = EVENT_PROC | EVENT_FLAG_START;
1963 public static final int EVENT_PROC_FINISH = EVENT_PROC | EVENT_FLAG_FINISH;
1964 public static final int EVENT_FOREGROUND_START = EVENT_FOREGROUND | EVENT_FLAG_START;
1965 public static final int EVENT_FOREGROUND_FINISH = EVENT_FOREGROUND | EVENT_FLAG_FINISH;
1966 public static final int EVENT_TOP_START = EVENT_TOP | EVENT_FLAG_START;
1967 public static final int EVENT_TOP_FINISH = EVENT_TOP | EVENT_FLAG_FINISH;
1968 public static final int EVENT_SYNC_START = EVENT_SYNC | EVENT_FLAG_START;
1969 public static final int EVENT_SYNC_FINISH = EVENT_SYNC | EVENT_FLAG_FINISH;
1970 public static final int EVENT_WAKE_LOCK_START = EVENT_WAKE_LOCK | EVENT_FLAG_START;
1971 public static final int EVENT_WAKE_LOCK_FINISH = EVENT_WAKE_LOCK | EVENT_FLAG_FINISH;
1972 public static final int EVENT_JOB_START = EVENT_JOB | EVENT_FLAG_START;
1973 public static final int EVENT_JOB_FINISH = EVENT_JOB | EVENT_FLAG_FINISH;
1974 public static final int EVENT_USER_RUNNING_START = EVENT_USER_RUNNING | EVENT_FLAG_START;
1975 public static final int EVENT_USER_RUNNING_FINISH = EVENT_USER_RUNNING | EVENT_FLAG_FINISH;
1976 public static final int EVENT_USER_FOREGROUND_START =
1977 EVENT_USER_FOREGROUND | EVENT_FLAG_START;
1978 public static final int EVENT_USER_FOREGROUND_FINISH =
1979 EVENT_USER_FOREGROUND | EVENT_FLAG_FINISH;
1980 public static final int EVENT_ALARM_START = EVENT_ALARM | EVENT_FLAG_START;
1981 public static final int EVENT_ALARM_FINISH = EVENT_ALARM | EVENT_FLAG_FINISH;
1982 public static final int EVENT_TEMP_WHITELIST_START =
1983 EVENT_TEMP_WHITELIST | EVENT_FLAG_START;
1984 public static final int EVENT_TEMP_WHITELIST_FINISH =
1985 EVENT_TEMP_WHITELIST | EVENT_FLAG_FINISH;
1986 public static final int EVENT_LONG_WAKE_LOCK_START =
1987 EVENT_LONG_WAKE_LOCK | EVENT_FLAG_START;
1988 public static final int EVENT_LONG_WAKE_LOCK_FINISH =
1989 EVENT_LONG_WAKE_LOCK | EVENT_FLAG_FINISH;
1990
1991 // For CMD_EVENT.
1992 public int eventCode;
1993 public HistoryTag eventTag;
1994
1995 // Only set for CMD_CURRENT_TIME or CMD_RESET, as per System.currentTimeMillis().
1996 public long currentTime;
1997
1998 // Meta-data when reading.
1999 public int numReadInts;
2000
2001 // Pre-allocated objects.
2002 public final HistoryTag localWakelockTag = new HistoryTag();
2003 public final HistoryTag localWakeReasonTag = new HistoryTag();
2004 public final HistoryTag localEventTag = new HistoryTag();
2005
2006 // Includes a tag's first occurrence in the parcel, so the value of the tag is written
2007 // rather than just its index in the history tag pool.
2008 public boolean tagsFirstOccurrence;
2009
2010 @UnsupportedAppUsage
2011 public HistoryItem() {
2012 }
2013
2014 public HistoryItem(Parcel src) {
2015 readFromParcel(src);
2016 }
2017
2018 public void writeToParcel(Parcel dest, int flags) {
2019 dest.writeLong(time);
2020 int bat = (((int)cmd)&0xff)
2021 | ((((int)batteryLevel)<<8)&0xff00)
2022 | ((((int)batteryStatus)<<16)&0xf0000)
2023 | ((((int)batteryHealth)<<20)&0xf00000)
2024 | ((((int)batteryPlugType)<<24)&0xf000000)
2025 | (wakelockTag != null ? 0x10000000 : 0)
2026 | (wakeReasonTag != null ? 0x20000000 : 0)
2027 | (eventCode != EVENT_NONE ? 0x40000000 : 0);
2028 dest.writeInt(bat);
2029 bat = (((int)batteryTemperature)&0xffff)
2030 | ((((int)batteryVoltage)<<16)&0xffff0000);
2031 dest.writeInt(bat);
2032 dest.writeInt(batteryChargeUah);
2033 dest.writeDouble(modemRailChargeMah);
2034 dest.writeDouble(wifiRailChargeMah);
2035 dest.writeInt(states);
2036 dest.writeInt(states2);
2037 if (wakelockTag != null) {
2038 wakelockTag.writeToParcel(dest, flags);
2039 }
2040 if (wakeReasonTag != null) {
2041 wakeReasonTag.writeToParcel(dest, flags);
2042 }
2043 if (eventCode != EVENT_NONE) {
2044 dest.writeInt(eventCode);
2045 eventTag.writeToParcel(dest, flags);
2046 }
2047 if (cmd == CMD_CURRENT_TIME || cmd == CMD_RESET) {
2048 dest.writeLong(currentTime);
2049 }
2050 }
2051
2052 public void readFromParcel(Parcel src) {
2053 int start = src.dataPosition();
2054 time = src.readLong();
2055 int bat = src.readInt();
2056 cmd = (byte)(bat&0xff);
2057 batteryLevel = (byte)((bat>>8)&0xff);
2058 batteryStatus = (byte)((bat>>16)&0xf);
2059 batteryHealth = (byte)((bat>>20)&0xf);
2060 batteryPlugType = (byte)((bat>>24)&0xf);
2061 int bat2 = src.readInt();
2062 batteryTemperature = (short)(bat2&0xffff);
2063 batteryVoltage = (char)((bat2>>16)&0xffff);
2064 batteryChargeUah = src.readInt();
2065 modemRailChargeMah = src.readDouble();
2066 wifiRailChargeMah = src.readDouble();
2067 states = src.readInt();
2068 states2 = src.readInt();
2069 if ((bat&0x10000000) != 0) {
2070 wakelockTag = localWakelockTag;
2071 wakelockTag.readFromParcel(src);
2072 } else {
2073 wakelockTag = null;
2074 }
2075 if ((bat&0x20000000) != 0) {
2076 wakeReasonTag = localWakeReasonTag;
2077 wakeReasonTag.readFromParcel(src);
2078 } else {
2079 wakeReasonTag = null;
2080 }
2081 if ((bat&0x40000000) != 0) {
2082 eventCode = src.readInt();
2083 eventTag = localEventTag;
2084 eventTag.readFromParcel(src);
2085 } else {
2086 eventCode = EVENT_NONE;
2087 eventTag = null;
2088 }
2089 if (cmd == CMD_CURRENT_TIME || cmd == CMD_RESET) {
2090 currentTime = src.readLong();
2091 } else {
2092 currentTime = 0;
2093 }
2094 numReadInts += (src.dataPosition()-start)/4;
2095 }
2096
2097 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
2098 public void clear() {
2099 time = 0;
2100 cmd = CMD_NULL;
2101 batteryLevel = 0;
2102 batteryStatus = 0;
2103 batteryHealth = 0;
2104 batteryPlugType = 0;
2105 batteryTemperature = 0;
2106 batteryVoltage = 0;
2107 batteryChargeUah = 0;
2108 modemRailChargeMah = 0;
2109 wifiRailChargeMah = 0;
2110 states = 0;
2111 states2 = 0;
2112 wakelockTag = null;
2113 wakeReasonTag = null;
2114 eventCode = EVENT_NONE;
2115 eventTag = null;
2116 tagsFirstOccurrence = false;
2117 }
2118
2119 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
2120 public void setTo(HistoryItem o) {
2121 time = o.time;
2122 cmd = o.cmd;
2123 setToCommon(o);
2124 }
2125
2126 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
2127 public void setTo(long time, byte cmd, HistoryItem o) {
2128 this.time = time;
2129 this.cmd = cmd;
2130 setToCommon(o);
2131 }
2132
2133 private void setToCommon(HistoryItem o) {
2134 batteryLevel = o.batteryLevel;
2135 batteryStatus = o.batteryStatus;
2136 batteryHealth = o.batteryHealth;
2137 batteryPlugType = o.batteryPlugType;
2138 batteryTemperature = o.batteryTemperature;
2139 batteryVoltage = o.batteryVoltage;
2140 batteryChargeUah = o.batteryChargeUah;
2141 modemRailChargeMah = o.modemRailChargeMah;
2142 wifiRailChargeMah = o.wifiRailChargeMah;
2143 states = o.states;
2144 states2 = o.states2;
2145 if (o.wakelockTag != null) {
2146 wakelockTag = localWakelockTag;
2147 wakelockTag.setTo(o.wakelockTag);
2148 } else {
2149 wakelockTag = null;
2150 }
2151 if (o.wakeReasonTag != null) {
2152 wakeReasonTag = localWakeReasonTag;
2153 wakeReasonTag.setTo(o.wakeReasonTag);
2154 } else {
2155 wakeReasonTag = null;
2156 }
2157 eventCode = o.eventCode;
2158 if (o.eventTag != null) {
2159 eventTag = localEventTag;
2160 eventTag.setTo(o.eventTag);
2161 } else {
2162 eventTag = null;
2163 }
2164 tagsFirstOccurrence = o.tagsFirstOccurrence;
2165 currentTime = o.currentTime;
2166 }
2167
2168 public boolean sameNonEvent(HistoryItem o) {
2169 return batteryLevel == o.batteryLevel
2170 && batteryStatus == o.batteryStatus
2171 && batteryHealth == o.batteryHealth
2172 && batteryPlugType == o.batteryPlugType
2173 && batteryTemperature == o.batteryTemperature
2174 && batteryVoltage == o.batteryVoltage
2175 && batteryChargeUah == o.batteryChargeUah
2176 && modemRailChargeMah == o.modemRailChargeMah
2177 && wifiRailChargeMah == o.wifiRailChargeMah
2178 && states == o.states
2179 && states2 == o.states2
2180 && currentTime == o.currentTime;
2181 }
2182
2183 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
2184 public boolean same(HistoryItem o) {
2185 if (!sameNonEvent(o) || eventCode != o.eventCode) {
2186 return false;
2187 }
2188 if (wakelockTag != o.wakelockTag) {
2189 if (wakelockTag == null || o.wakelockTag == null) {
2190 return false;
2191 }
2192 if (!wakelockTag.equals(o.wakelockTag)) {
2193 return false;
2194 }
2195 }
2196 if (wakeReasonTag != o.wakeReasonTag) {
2197 if (wakeReasonTag == null || o.wakeReasonTag == null) {
2198 return false;
2199 }
2200 if (!wakeReasonTag.equals(o.wakeReasonTag)) {
2201 return false;
2202 }
2203 }
2204 if (eventTag != o.eventTag) {
2205 if (eventTag == null || o.eventTag == null) {
2206 return false;
2207 }
2208 if (!eventTag.equals(o.eventTag)) {
2209 return false;
2210 }
2211 }
2212 return true;
2213 }
2214 }
2215
2216 public final static class HistoryEventTracker {
2217 private final HashMap<String, SparseIntArray>[] mActiveEvents
2218 = (HashMap<String, SparseIntArray>[]) new HashMap[HistoryItem.EVENT_COUNT];
2219
2220 public boolean updateState(int code, String name, int uid, int poolIdx) {
2221 if ((code&HistoryItem.EVENT_FLAG_START) != 0) {
2222 int idx = code&HistoryItem.EVENT_TYPE_MASK;
2223 HashMap<String, SparseIntArray> active = mActiveEvents[idx];
2224 if (active == null) {
2225 active = new HashMap<>();
2226 mActiveEvents[idx] = active;
2227 }
2228 SparseIntArray uids = active.get(name);
2229 if (uids == null) {
2230 uids = new SparseIntArray();
2231 active.put(name, uids);
2232 }
2233 if (uids.indexOfKey(uid) >= 0) {
2234 // Already set, nothing to do!
2235 return false;
2236 }
2237 uids.put(uid, poolIdx);
2238 } else if ((code&HistoryItem.EVENT_FLAG_FINISH) != 0) {
2239 int idx = code&HistoryItem.EVENT_TYPE_MASK;
2240 HashMap<String, SparseIntArray> active = mActiveEvents[idx];
2241 if (active == null) {
2242 // not currently active, nothing to do.
2243 return false;
2244 }
2245 SparseIntArray uids = active.get(name);
2246 if (uids == null) {
2247 // not currently active, nothing to do.
2248 return false;
2249 }
2250 idx = uids.indexOfKey(uid);
2251 if (idx < 0) {
2252 // not currently active, nothing to do.
2253 return false;
2254 }
2255 uids.removeAt(idx);
2256 if (uids.size() <= 0) {
2257 active.remove(name);
2258 }
2259 }
2260 return true;
2261 }
2262
2263 public void removeEvents(int code) {
2264 int idx = code&HistoryItem.EVENT_TYPE_MASK;
2265 mActiveEvents[idx] = null;
2266 }
2267
2268 public HashMap<String, SparseIntArray> getStateForEvent(int code) {
2269 return mActiveEvents[code];
2270 }
2271 }
2272
2273 public static final class BitDescription {
2274 public final int mask;
2275 public final int shift;
2276 public final String name;
2277 public final String shortName;
2278 public final String[] values;
2279 public final String[] shortValues;
2280
2281 public BitDescription(int mask, String name, String shortName) {
2282 this.mask = mask;
2283 this.shift = -1;
2284 this.name = name;
2285 this.shortName = shortName;
2286 this.values = null;
2287 this.shortValues = null;
2288 }
2289
2290 public BitDescription(int mask, int shift, String name, String shortName,
2291 String[] values, String[] shortValues) {
2292 this.mask = mask;
2293 this.shift = shift;
2294 this.name = name;
2295 this.shortName = shortName;
2296 this.values = values;
2297 this.shortValues = shortValues;
2298 }
2299 }
2300
2301 /**
2302 * Don't allow any more batching in to the current history event. This
2303 * is called when printing partial histories, so to ensure that the next
2304 * history event will go in to a new batch after what was printed in the
2305 * last partial history.
2306 */
2307 public abstract void commitCurrentHistoryBatchLocked();
2308
2309 public abstract int getHistoryTotalSize();
2310
2311 public abstract int getHistoryUsedSize();
2312
2313 @UnsupportedAppUsage
2314 public abstract boolean startIteratingHistoryLocked();
2315
2316 public abstract int getHistoryStringPoolSize();
2317
2318 public abstract int getHistoryStringPoolBytes();
2319
2320 public abstract String getHistoryTagPoolString(int index);
2321
2322 public abstract int getHistoryTagPoolUid(int index);
2323
2324 @UnsupportedAppUsage
2325 public abstract boolean getNextHistoryLocked(HistoryItem out);
2326
2327 public abstract void finishIteratingHistoryLocked();
2328
2329 /**
2330 * Return the base time offset for the battery history.
2331 */
2332 public abstract long getHistoryBaseTime();
2333
2334 /**
2335 * Returns the number of times the device has been started.
2336 */
2337 public abstract int getStartCount();
2338
2339 /**
2340 * Returns the time in microseconds that the screen has been on while the device was
2341 * running on battery.
2342 *
2343 * {@hide}
2344 */
2345 @UnsupportedAppUsage
2346 public abstract long getScreenOnTime(long elapsedRealtimeUs, int which);
2347
2348 /**
2349 * Returns the number of times the screen was turned on.
2350 *
2351 * {@hide}
2352 */
2353 public abstract int getScreenOnCount(int which);
2354
2355 /**
2356 * Returns the time in microseconds that the screen has been dozing while the device was
2357 * running on battery.
2358 *
2359 * {@hide}
2360 */
2361 public abstract long getScreenDozeTime(long elapsedRealtimeUs, int which);
2362
2363 /**
2364 * Returns the number of times the screen was turned dozing.
2365 *
2366 * {@hide}
2367 */
2368 public abstract int getScreenDozeCount(int which);
2369
2370 public abstract long getInteractiveTime(long elapsedRealtimeUs, int which);
2371
2372 public static final int SCREEN_BRIGHTNESS_DARK = 0;
2373 public static final int SCREEN_BRIGHTNESS_DIM = 1;
2374 public static final int SCREEN_BRIGHTNESS_MEDIUM = 2;
2375 public static final int SCREEN_BRIGHTNESS_LIGHT = 3;
2376 public static final int SCREEN_BRIGHTNESS_BRIGHT = 4;
2377
2378 static final String[] SCREEN_BRIGHTNESS_NAMES = {
2379 "dark", "dim", "medium", "light", "bright"
2380 };
2381
2382 static final String[] SCREEN_BRIGHTNESS_SHORT_NAMES = {
2383 "0", "1", "2", "3", "4"
2384 };
2385
2386 @UnsupportedAppUsage
2387 public static final int NUM_SCREEN_BRIGHTNESS_BINS = 5;
2388
2389 /**
2390 * Returns the time in microseconds that the screen has been on with
2391 * the given brightness
2392 *
2393 * {@hide}
2394 */
2395 @UnsupportedAppUsage
2396 public abstract long getScreenBrightnessTime(int brightnessBin,
2397 long elapsedRealtimeUs, int which);
2398
2399 /**
2400 * Returns the {@link Timer} object that tracks the given screen brightness.
2401 *
2402 * {@hide}
2403 */
2404 public abstract Timer getScreenBrightnessTimer(int brightnessBin);
2405
2406 /**
2407 * Returns the number of physical displays on the device.
2408 *
2409 * {@hide}
2410 */
2411 public abstract int getDisplayCount();
2412
2413 /**
2414 * Returns the time in microseconds that the screen has been on for a display while the
2415 * device was running on battery.
2416 *
2417 * {@hide}
2418 */
2419 public abstract long getDisplayScreenOnTime(int display, long elapsedRealtimeUs);
2420
2421 /**
2422 * Returns the time in microseconds that a display has been dozing while the device was
2423 * running on battery.
2424 *
2425 * {@hide}
2426 */
2427 public abstract long getDisplayScreenDozeTime(int display, long elapsedRealtimeUs);
2428
2429 /**
2430 * Returns the time in microseconds that a display has been on with the given brightness
2431 * level while the device was running on battery.
2432 *
2433 * {@hide}
2434 */
2435 public abstract long getDisplayScreenBrightnessTime(int display, int brightnessBin,
2436 long elapsedRealtimeUs);
2437
2438 /**
2439 * Returns the time in microseconds that power save mode has been enabled while the device was
2440 * running on battery.
2441 *
2442 * {@hide}
2443 */
2444 public abstract long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which);
2445
2446 /**
2447 * Returns the number of times that power save mode was enabled.
2448 *
2449 * {@hide}
2450 */
2451 public abstract int getPowerSaveModeEnabledCount(int which);
2452
2453 /**
2454 * Constant for device idle mode: not active.
2455 */
2456 public static final int DEVICE_IDLE_MODE_OFF = ServerProtoEnums.DEVICE_IDLE_MODE_OFF; // 0
2457
2458 /**
2459 * Constant for device idle mode: active in lightweight mode.
2460 */
2461 public static final int DEVICE_IDLE_MODE_LIGHT = ServerProtoEnums.DEVICE_IDLE_MODE_LIGHT; // 1
2462
2463 /**
2464 * Constant for device idle mode: active in full mode.
2465 */
2466 public static final int DEVICE_IDLE_MODE_DEEP = ServerProtoEnums.DEVICE_IDLE_MODE_DEEP; // 2
2467
2468 /**
2469 * Returns the time in microseconds that device has been in idle mode while
2470 * running on battery.
2471 *
2472 * {@hide}
2473 */
2474 public abstract long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs, int which);
2475
2476 /**
2477 * Returns the number of times that the devie has gone in to idle mode.
2478 *
2479 * {@hide}
2480 */
2481 public abstract int getDeviceIdleModeCount(int mode, int which);
2482
2483 /**
2484 * Return the longest duration we spent in a particular device idle mode (fully in the
2485 * mode, not in idle maintenance etc).
2486 */
2487 public abstract long getLongestDeviceIdleModeTime(int mode);
2488
2489 /**
2490 * Returns the time in microseconds that device has been in idling while on
2491 * battery. This is broader than {@link #getDeviceIdleModeTime} -- it
2492 * counts all of the time that we consider the device to be idle, whether or not
2493 * it is currently in the actual device idle mode.
2494 *
2495 * {@hide}
2496 */
2497 public abstract long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which);
2498
2499 /**
2500 * Returns the number of times that the device has started idling.
2501 *
2502 * {@hide}
2503 */
2504 public abstract int getDeviceIdlingCount(int mode, int which);
2505
2506 /**
2507 * Returns the number of times that connectivity state changed.
2508 *
2509 * {@hide}
2510 */
2511 public abstract int getNumConnectivityChange(int which);
2512
2513
2514 /**
2515 * Returns the time in microseconds that the phone has been running with
2516 * the given GPS signal quality level
2517 *
2518 * {@hide}
2519 */
2520 public abstract long getGpsSignalQualityTime(int strengthBin,
2521 long elapsedRealtimeUs, int which);
2522
2523 /**
2524 * Returns the GPS battery drain in mA-ms
2525 *
2526 * {@hide}
2527 */
2528 public abstract long getGpsBatteryDrainMaMs();
2529
2530 /**
2531 * Returns the time in microseconds that the phone has been on while the device was
2532 * running on battery.
2533 *
2534 * {@hide}
2535 */
2536 @UnsupportedAppUsage
2537 public abstract long getPhoneOnTime(long elapsedRealtimeUs, int which);
2538
2539 /**
2540 * Returns the number of times a phone call was activated.
2541 *
2542 * {@hide}
2543 */
2544 public abstract int getPhoneOnCount(int which);
2545
2546 /**
2547 * Returns the time in microseconds that the phone has been running with
2548 * the given signal strength.
2549 *
2550 * {@hide}
2551 */
2552 @UnsupportedAppUsage
2553 public abstract long getPhoneSignalStrengthTime(int strengthBin,
2554 long elapsedRealtimeUs, int which);
2555
2556 /**
2557 * Returns the time in microseconds that the phone has been trying to
2558 * acquire a signal.
2559 *
2560 * {@hide}
2561 */
2562 public abstract long getPhoneSignalScanningTime(
2563 long elapsedRealtimeUs, int which);
2564
2565 /**
2566 * Returns the {@link Timer} object that tracks how much the phone has been trying to
2567 * acquire a signal.
2568 *
2569 * {@hide}
2570 */
2571 public abstract Timer getPhoneSignalScanningTimer();
2572
2573 /**
2574 * Returns the number of times the phone has entered the given signal strength.
2575 *
2576 * {@hide}
2577 */
2578 public abstract int getPhoneSignalStrengthCount(int strengthBin, int which);
2579
2580 /**
2581 * Return the {@link Timer} object used to track the given signal strength's duration and
2582 * counts.
2583 */
2584 protected abstract Timer getPhoneSignalStrengthTimer(int strengthBin);
2585
2586 /**
2587 * Returns the time in microseconds that the mobile network has been active
2588 * (in a high power state).
2589 *
2590 * {@hide}
2591 */
2592 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
2593 public abstract long getMobileRadioActiveTime(long elapsedRealtimeUs, int which);
2594
2595 /**
2596 * Returns the number of times that the mobile network has transitioned to the
2597 * active state.
2598 *
2599 * {@hide}
2600 */
2601 public abstract int getMobileRadioActiveCount(int which);
2602
2603 /**
2604 * Returns the time in microseconds that is the difference between the mobile radio
2605 * time we saw based on the elapsed timestamp when going down vs. the given time stamp
2606 * from the radio.
2607 *
2608 * {@hide}
2609 */
2610 public abstract long getMobileRadioActiveAdjustedTime(int which);
2611
2612 /**
2613 * Returns the time in microseconds that the mobile network has been active
2614 * (in a high power state) but not being able to blame on an app.
2615 *
2616 * {@hide}
2617 */
2618 public abstract long getMobileRadioActiveUnknownTime(int which);
2619
2620 /**
2621 * Return count of number of times radio was up that could not be blamed on apps.
2622 *
2623 * {@hide}
2624 */
2625 public abstract int getMobileRadioActiveUnknownCount(int which);
2626
2627 public static final int DATA_CONNECTION_OUT_OF_SERVICE = 0;
2628 public static final int DATA_CONNECTION_EMERGENCY_SERVICE =
2629 TelephonyManager.getAllNetworkTypes().length + 1;
2630 public static final int DATA_CONNECTION_OTHER = DATA_CONNECTION_EMERGENCY_SERVICE + 1;
2631
2632
2633 static final String[] DATA_CONNECTION_NAMES = {
2634 "oos", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A",
2635 "1xrtt", "hsdpa", "hsupa", "hspa", "iden", "evdo_b", "lte",
2636 "ehrpd", "hspap", "gsm", "td_scdma", "iwlan", "lte_ca", "nr",
2637 "emngcy", "other"
2638 };
2639
2640 @UnsupportedAppUsage
2641 public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER + 1;
2642
2643 /**
2644 * Returns the time in microseconds that the phone has been running with
2645 * the given data connection.
2646 *
2647 * {@hide}
2648 */
2649 public abstract long getPhoneDataConnectionTime(int dataType,
2650 long elapsedRealtimeUs, int which);
2651
2652 /**
2653 * Returns the number of times the phone has entered the given data
2654 * connection type.
2655 *
2656 * {@hide}
2657 */
2658 public abstract int getPhoneDataConnectionCount(int dataType, int which);
2659
2660 /**
2661 * Returns the {@link Timer} object that tracks the phone's data connection type stats.
2662 */
2663 public abstract Timer getPhoneDataConnectionTimer(int dataType);
2664
2665 /** @hide */
2666 public static final int RADIO_ACCESS_TECHNOLOGY_OTHER = 0;
2667 /** @hide */
2668 public static final int RADIO_ACCESS_TECHNOLOGY_LTE = 1;
2669 /** @hide */
2670 public static final int RADIO_ACCESS_TECHNOLOGY_NR = 2;
2671 /** @hide */
2672 public static final int RADIO_ACCESS_TECHNOLOGY_COUNT = 3;
2673
2674 /** @hide */
2675 @Retention(RetentionPolicy.SOURCE)
2676 @IntDef(prefix = "RADIO_ACCESS_TECHNOLOGY_",
2677 value = {RADIO_ACCESS_TECHNOLOGY_OTHER, RADIO_ACCESS_TECHNOLOGY_LTE,
2678 RADIO_ACCESS_TECHNOLOGY_NR})
2679 public @interface RadioAccessTechnology {
2680 }
2681
2682 /** @hide */
2683 public static final String[] RADIO_ACCESS_TECHNOLOGY_NAMES = {"Other", "LTE", "NR"};
2684
2685 /**
2686 * Returns the time in milliseconds that the mobile radio has been active on a
2687 * given Radio Access Technology (RAT), at a given frequency (NR RAT only), for a given
2688 * transmission power level.
2689 *
2690 * @param rat Radio Access Technology {@see RadioAccessTechnology}
2691 * @param frequencyRange frequency range {@see ServiceState.FrequencyRange}, only needed for
2692 * RADIO_ACCESS_TECHNOLOGY_NR. Use
2693 * {@link ServiceState.FREQUENCY_RANGE_UNKNOWN} for other Radio Access
2694 * Technologies.
2695 * @param signalStrength the cellular signal strength. {@see CellSignalStrength#getLevel()}
2696 * @param elapsedRealtimeMs current elapsed realtime
2697 * @return time (in milliseconds) the mobile radio spent active in the specified state,
2698 * while on battery.
2699 * @hide
2700 */
2701 public abstract long getActiveRadioDurationMs(@RadioAccessTechnology int rat,
2702 @ServiceState.FrequencyRange int frequencyRange, int signalStrength,
2703 long elapsedRealtimeMs);
2704
2705 /**
2706 * Returns the time in milliseconds that the mobile radio has been actively transmitting data on
2707 * a given Radio Access Technology (RAT), at a given frequency (NR RAT only), for a given
2708 * transmission power level.
2709 *
2710 * @param rat Radio Access Technology {@see RadioAccessTechnology}
2711 * @param frequencyRange frequency range {@see ServiceState.FrequencyRange}, only needed for
2712 * RADIO_ACCESS_TECHNOLOGY_NR. Use
2713 * {@link ServiceState.FREQUENCY_RANGE_UNKNOWN} for other Radio Access
2714 * Technologies.
2715 * @param signalStrength the cellular signal strength. {@see CellSignalStrength#getLevel()}
2716 * @param elapsedRealtimeMs current elapsed realtime
2717 * @return time (in milliseconds) the mobile radio spent actively transmitting data in the
2718 * specified state, while on battery. Returns {@link DURATION_UNAVAILABLE} if
2719 * data unavailable.
2720 * @hide
2721 */
2722 public abstract long getActiveTxRadioDurationMs(@RadioAccessTechnology int rat,
2723 @ServiceState.FrequencyRange int frequencyRange, int signalStrength,
2724 long elapsedRealtimeMs);
2725
2726 /**
2727 * Returns the time in milliseconds that the mobile radio has been actively receiving data on a
2728 * given Radio Access Technology (RAT), at a given frequency (NR RAT only), for a given
2729 * transmission power level.
2730 *
2731 * @param rat Radio Access Technology {@see RadioAccessTechnology}
2732 * @param frequencyRange frequency range {@see ServiceState.FrequencyRange}, only needed for
2733 * RADIO_ACCESS_TECHNOLOGY_NR. Use
2734 * {@link ServiceState.FREQUENCY_RANGE_UNKNOWN} for other Radio Access
2735 * Technologies.
2736 * @param elapsedRealtimeMs current elapsed realtime
2737 * @return time (in milliseconds) the mobile radio spent actively receiving data in the
2738 * specified state, while on battery. Returns {@link DURATION_UNAVAILABLE} if
2739 * data unavailable.
2740 * @hide
2741 */
2742 public abstract long getActiveRxRadioDurationMs(@RadioAccessTechnology int rat,
2743 @ServiceState.FrequencyRange int frequencyRange, long elapsedRealtimeMs);
2744
2745 static final String[] WIFI_SUPPL_STATE_NAMES = {
2746 "invalid", "disconn", "disabled", "inactive", "scanning",
2747 "authenticating", "associating", "associated", "4-way-handshake",
2748 "group-handshake", "completed", "dormant", "uninit"
2749 };
2750
2751 static final String[] WIFI_SUPPL_STATE_SHORT_NAMES = {
2752 "inv", "dsc", "dis", "inact", "scan",
2753 "auth", "ascing", "asced", "4-way",
2754 "group", "compl", "dorm", "uninit"
2755 };
2756
2757 /**
2758 * Returned value if power data is unavailable.
2759 *
2760 * {@hide}
2761 */
2762 public static final long POWER_DATA_UNAVAILABLE = -1L;
2763
2764 /**
2765 * Returned value if duration data is unavailable.
2766 *
2767 * {@hide}
2768 */
2769 public static final long DURATION_UNAVAILABLE = -1L;
2770
2771 /**
2772 * Returns the battery consumption (in microcoulombs) of bluetooth, derived from on
2773 * device power measurement data.
2774 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2775 *
2776 * {@hide}
2777 */
2778 public abstract long getBluetoothMeasuredBatteryConsumptionUC();
2779
2780 /**
2781 * Returns the battery consumption (in microcoulombs) of the cpu, derived from on device power
2782 * measurement data.
2783 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2784 *
2785 * {@hide}
2786 */
2787 public abstract long getCpuMeasuredBatteryConsumptionUC();
2788
2789 /**
2790 * Returns the battery consumption (in microcoulombs) of the GNSS, derived from on device power
2791 * measurement data.
2792 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2793 *
2794 * {@hide}
2795 */
2796 public abstract long getGnssMeasuredBatteryConsumptionUC();
2797
2798 /**
2799 * Returns the battery consumption (in microcoulombs) of the radio, derived from on device power
2800 * measurement data.
2801 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2802 *
2803 * {@hide}
2804 */
2805 public abstract long getMobileRadioMeasuredBatteryConsumptionUC();
2806
2807 /**
2808 * Returns the battery consumption (in microcoulombs) of the screen while on, derived from on
2809 * device power measurement data.
2810 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2811 *
2812 * {@hide}
2813 */
2814 public abstract long getScreenOnMeasuredBatteryConsumptionUC();
2815
2816 /**
2817 * Returns the battery consumption (in microcoulombs) of the screen in doze, derived from on
2818 * device power measurement data.
2819 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2820 *
2821 * {@hide}
2822 */
2823 public abstract long getScreenDozeMeasuredBatteryConsumptionUC();
2824
2825 /**
2826 * Returns the battery consumption (in microcoulombs) of wifi, derived from on
2827 * device power measurement data.
2828 * Will return {@link #POWER_DATA_UNAVAILABLE} if data is unavailable.
2829 *
2830 * {@hide}
2831 */
2832 public abstract long getWifiMeasuredBatteryConsumptionUC();
2833
2834 /**
2835 * Returns the battery consumption (in microcoulombs) that each
2836 * {@link android.hardware.power.stats.EnergyConsumer.ordinal} of (custom) energy consumer
2837 * type {@link android.hardware.power.stats.EnergyConsumerType#OTHER}) consumed.
2838 *
2839 * @return charge (in microcoulombs) used by each (custom) energy consumer of type OTHER,
2840 * indexed by their ordinal. Returns null if no energy reporting is supported.
2841 *
2842 * {@hide}
2843 */
2844 public abstract @Nullable long[] getCustomConsumerMeasuredBatteryConsumptionUC();
2845
2846 /**
2847 * Returns the names of all {@link android.hardware.power.stats.EnergyConsumer}'s
2848 * of (custom) energy consumer type
2849 * {@link android.hardware.power.stats.EnergyConsumerType#OTHER}).
2850 *
2851 * {@hide}
2852 */
2853 public abstract @NonNull String[] getCustomEnergyConsumerNames();
2854
2855 public static final BitDescription[] HISTORY_STATE_DESCRIPTIONS = new BitDescription[] {
2856 new BitDescription(HistoryItem.STATE_CPU_RUNNING_FLAG, "running", "r"),
2857 new BitDescription(HistoryItem.STATE_WAKE_LOCK_FLAG, "wake_lock", "w"),
2858 new BitDescription(HistoryItem.STATE_SENSOR_ON_FLAG, "sensor", "s"),
2859 new BitDescription(HistoryItem.STATE_GPS_ON_FLAG, "gps", "g"),
2860 new BitDescription(HistoryItem.STATE_WIFI_FULL_LOCK_FLAG, "wifi_full_lock", "Wl"),
2861 new BitDescription(HistoryItem.STATE_WIFI_SCAN_FLAG, "wifi_scan", "Ws"),
2862 new BitDescription(HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG, "wifi_multicast", "Wm"),
2863 new BitDescription(HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG, "wifi_radio", "Wr"),
2864 new BitDescription(HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG, "mobile_radio", "Pr"),
2865 new BitDescription(HistoryItem.STATE_PHONE_SCANNING_FLAG, "phone_scanning", "Psc"),
2866 new BitDescription(HistoryItem.STATE_AUDIO_ON_FLAG, "audio", "a"),
2867 new BitDescription(HistoryItem.STATE_SCREEN_ON_FLAG, "screen", "S"),
2868 new BitDescription(HistoryItem.STATE_BATTERY_PLUGGED_FLAG, "plugged", "BP"),
2869 new BitDescription(HistoryItem.STATE_SCREEN_DOZE_FLAG, "screen_doze", "Sd"),
2870 new BitDescription(HistoryItem.STATE_DATA_CONNECTION_MASK,
2871 HistoryItem.STATE_DATA_CONNECTION_SHIFT, "data_conn", "Pcn",
2872 DATA_CONNECTION_NAMES, DATA_CONNECTION_NAMES),
2873 new BitDescription(HistoryItem.STATE_PHONE_STATE_MASK,
2874 HistoryItem.STATE_PHONE_STATE_SHIFT, "phone_state", "Pst",
2875 new String[] {"in", "out", "emergency", "off"},
2876 new String[] {"in", "out", "em", "off"}),
2877 new BitDescription(HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK,
2878 HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT, "phone_signal_strength", "Pss",
2879 new String[] { "none", "poor", "moderate", "good", "great" },
2880 new String[] { "0", "1", "2", "3", "4" }),
2881 new BitDescription(HistoryItem.STATE_BRIGHTNESS_MASK,
2882 HistoryItem.STATE_BRIGHTNESS_SHIFT, "brightness", "Sb",
2883 SCREEN_BRIGHTNESS_NAMES, SCREEN_BRIGHTNESS_SHORT_NAMES),
2884 };
2885
2886 public static final BitDescription[] HISTORY_STATE2_DESCRIPTIONS = new BitDescription[] {
2887 new BitDescription(HistoryItem.STATE2_POWER_SAVE_FLAG, "power_save", "ps"),
2888 new BitDescription(HistoryItem.STATE2_VIDEO_ON_FLAG, "video", "v"),
2889 new BitDescription(HistoryItem.STATE2_WIFI_RUNNING_FLAG, "wifi_running", "Ww"),
2890 new BitDescription(HistoryItem.STATE2_WIFI_ON_FLAG, "wifi", "W"),
2891 new BitDescription(HistoryItem.STATE2_FLASHLIGHT_FLAG, "flashlight", "fl"),
2892 new BitDescription(HistoryItem.STATE2_DEVICE_IDLE_MASK,
2893 HistoryItem.STATE2_DEVICE_IDLE_SHIFT, "device_idle", "di",
2894 new String[] { "off", "light", "full", "???" },
2895 new String[] { "off", "light", "full", "???" }),
2896 new BitDescription(HistoryItem.STATE2_CHARGING_FLAG, "charging", "ch"),
2897 new BitDescription(HistoryItem.STATE2_USB_DATA_LINK_FLAG, "usb_data", "Ud"),
2898 new BitDescription(HistoryItem.STATE2_PHONE_IN_CALL_FLAG, "phone_in_call", "Pcl"),
2899 new BitDescription(HistoryItem.STATE2_BLUETOOTH_ON_FLAG, "bluetooth", "b"),
2900 new BitDescription(HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK,
2901 HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT, "wifi_signal_strength", "Wss",
2902 new String[] { "0", "1", "2", "3", "4" },
2903 new String[] { "0", "1", "2", "3", "4" }),
2904 new BitDescription(HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK,
2905 HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT, "wifi_suppl", "Wsp",
2906 WIFI_SUPPL_STATE_NAMES, WIFI_SUPPL_STATE_SHORT_NAMES),
2907 new BitDescription(HistoryItem.STATE2_CAMERA_FLAG, "camera", "ca"),
2908 new BitDescription(HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG, "ble_scan", "bles"),
2909 new BitDescription(HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG,
2910 "cellular_high_tx_power", "Chtp"),
2911 new BitDescription(HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK,
2912 HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT, "gps_signal_quality", "Gss",
2913 new String[] { "poor", "good"}, new String[] { "poor", "good"})
2914 };
2915
2916 public static final String[] HISTORY_EVENT_NAMES = new String[] {
2917 "null", "proc", "fg", "top", "sync", "wake_lock_in", "job", "user", "userfg", "conn",
2918 "active", "pkginst", "pkgunin", "alarm", "stats", "pkginactive", "pkgactive",
2919 "tmpwhitelist", "screenwake", "wakeupap", "longwake", "est_capacity"
2920 };
2921
2922 public static final String[] HISTORY_EVENT_CHECKIN_NAMES = new String[] {
2923 "Enl", "Epr", "Efg", "Etp", "Esy", "Ewl", "Ejb", "Eur", "Euf", "Ecn",
2924 "Eac", "Epi", "Epu", "Eal", "Est", "Eai", "Eaa", "Etw",
2925 "Esw", "Ewa", "Elw", "Eec"
2926 };
2927
2928 @FunctionalInterface
2929 public interface IntToString {
2930 String applyAsString(int val);
2931 }
2932
2933 private static final IntToString sUidToString = UserHandle::formatUid;
2934 private static final IntToString sIntToString = Integer::toString;
2935
2936 public static final IntToString[] HISTORY_EVENT_INT_FORMATTERS = new IntToString[] {
2937 sUidToString, sUidToString, sUidToString, sUidToString, sUidToString, sUidToString,
2938 sUidToString, sUidToString, sUidToString, sUidToString, sUidToString, sIntToString,
2939 sUidToString, sUidToString, sUidToString, sUidToString, sUidToString, sUidToString,
2940 sUidToString, sUidToString, sUidToString, sIntToString
2941 };
2942
2943 /**
2944 * Returns total time for WiFi Multicast Wakelock timer.
2945 * Note that this may be different from the sum of per uid timer values.
2946 *
2947 * {@hide}
2948 */
2949 public abstract long getWifiMulticastWakelockTime(long elapsedRealtimeUs, int which);
2950
2951 /**
2952 * Returns total time for WiFi Multicast Wakelock timer
2953 * Note that this may be different from the sum of per uid timer values.
2954 *
2955 * {@hide}
2956 */
2957 public abstract int getWifiMulticastWakelockCount(int which);
2958
2959 /**
2960 * Returns the time in microseconds that wifi has been on while the device was
2961 * running on battery.
2962 *
2963 * {@hide}
2964 */
2965 @UnsupportedAppUsage
2966 public abstract long getWifiOnTime(long elapsedRealtimeUs, int which);
2967
2968 /**
2969 * Returns the time in microseconds that wifi has been active while the device was
2970 * running on battery.
2971 *
2972 * {@hide}
2973 */
2974 public abstract long getWifiActiveTime(long elapsedRealtimeUs, int which);
2975
2976 /**
2977 * Returns the time in microseconds that wifi has been on and the driver has
2978 * been in the running state while the device was running on battery.
2979 *
2980 * {@hide}
2981 */
2982 @UnsupportedAppUsage
2983 public abstract long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which);
2984
2985 static final String[] WIFI_STATE_NAMES = {
2986 "off", "scanning", "no_net", "disconn",
2987 "sta", "p2p", "sta_p2p", "soft_ap"
2988 };
2989
2990 /**
2991 * Returns the time in microseconds that WiFi has been running in the given state.
2992 *
2993 * {@hide}
2994 */
2995 public abstract long getWifiStateTime(@WifiState int wifiState,
2996 long elapsedRealtimeUs, @StatName int which);
2997
2998 /**
2999 * Returns the number of times that WiFi has entered the given state.
3000 *
3001 * {@hide}
3002 */
3003 public abstract int getWifiStateCount(@WifiState int wifiState, @StatName int which);
3004
3005 /**
3006 * Returns the {@link Timer} object that tracks the given WiFi state.
3007 *
3008 * {@hide}
3009 */
3010 public abstract Timer getWifiStateTimer(@WifiState int wifiState);
3011
3012 /**
3013 * Returns the time in microseconds that the wifi supplicant has been
3014 * in a given state.
3015 *
3016 * {@hide}
3017 */
3018 public abstract long getWifiSupplStateTime(@WifiSupplState int state, long elapsedRealtimeUs,
3019 @StatName int which);
3020
3021 /**
3022 * Returns the number of times that the wifi supplicant has transitioned
3023 * to a given state.
3024 *
3025 * {@hide}
3026 */
3027 public abstract int getWifiSupplStateCount(@WifiSupplState int state, @StatName int which);
3028
3029 /**
3030 * Returns the {@link Timer} object that tracks the given wifi supplicant state.
3031 *
3032 * {@hide}
3033 */
3034 public abstract Timer getWifiSupplStateTimer(@WifiSupplState int state);
3035
3036 public static final int NUM_WIFI_SIGNAL_STRENGTH_BINS = 5;
3037
3038 /**
3039 * Returns the time in microseconds that WIFI has been running with
3040 * the given signal strength.
3041 *
3042 * {@hide}
3043 */
3044 public abstract long getWifiSignalStrengthTime(int strengthBin,
3045 long elapsedRealtimeUs, int which);
3046
3047 /**
3048 * Returns the number of times WIFI has entered the given signal strength.
3049 *
3050 * {@hide}
3051 */
3052 public abstract int getWifiSignalStrengthCount(int strengthBin, int which);
3053
3054 /**
3055 * Returns the {@link Timer} object that tracks the given WIFI signal strength.
3056 *
3057 * {@hide}
3058 */
3059 public abstract Timer getWifiSignalStrengthTimer(int strengthBin);
3060
3061 /**
3062 * Returns the time in microseconds that the flashlight has been on while the device was
3063 * running on battery.
3064 *
3065 * {@hide}
3066 */
3067 public abstract long getFlashlightOnTime(long elapsedRealtimeUs, int which);
3068
3069 /**
3070 * Returns the number of times that the flashlight has been turned on while the device was
3071 * running on battery.
3072 *
3073 * {@hide}
3074 */
3075 public abstract long getFlashlightOnCount(int which);
3076
3077 /**
3078 * Returns the time in microseconds that the camera has been on while the device was
3079 * running on battery.
3080 *
3081 * {@hide}
3082 */
3083 public abstract long getCameraOnTime(long elapsedRealtimeUs, int which);
3084
3085 /**
3086 * Returns the time in microseconds that bluetooth scans were running while the device was
3087 * on battery.
3088 *
3089 * {@hide}
3090 */
3091 public abstract long getBluetoothScanTime(long elapsedRealtimeUs, int which);
3092
3093 public static final int NETWORK_MOBILE_RX_DATA = 0;
3094 public static final int NETWORK_MOBILE_TX_DATA = 1;
3095 public static final int NETWORK_WIFI_RX_DATA = 2;
3096 public static final int NETWORK_WIFI_TX_DATA = 3;
3097 public static final int NETWORK_BT_RX_DATA = 4;
3098 public static final int NETWORK_BT_TX_DATA = 5;
3099 public static final int NETWORK_MOBILE_BG_RX_DATA = 6;
3100 public static final int NETWORK_MOBILE_BG_TX_DATA = 7;
3101 public static final int NETWORK_WIFI_BG_RX_DATA = 8;
3102 public static final int NETWORK_WIFI_BG_TX_DATA = 9;
3103 public static final int NUM_NETWORK_ACTIVITY_TYPES = NETWORK_WIFI_BG_TX_DATA + 1;
3104
3105 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
3106 public abstract long getNetworkActivityBytes(int type, int which);
3107 public abstract long getNetworkActivityPackets(int type, int which);
3108
3109 /**
3110 * Returns true if the BatteryStats object has detailed WiFi power reports.
3111 * When true, calling {@link #getWifiControllerActivity()} will yield the
3112 * actual power data.
3113 */
3114 public abstract boolean hasWifiActivityReporting();
3115
3116 /**
3117 * Returns a {@link ControllerActivityCounter} which is an aggregate of the times spent
3118 * in various radio controller states, such as transmit, receive, and idle.
3119 * @return non-null {@link ControllerActivityCounter}
3120 */
3121 public abstract ControllerActivityCounter getWifiControllerActivity();
3122
3123 /**
3124 * Returns true if the BatteryStats object has detailed bluetooth power reports.
3125 * When true, calling {@link #getBluetoothControllerActivity()} will yield the
3126 * actual power data.
3127 */
3128 public abstract boolean hasBluetoothActivityReporting();
3129
3130 /**
3131 * Returns a {@link ControllerActivityCounter} which is an aggregate of the times spent
3132 * in various radio controller states, such as transmit, receive, and idle.
3133 * @return non-null {@link ControllerActivityCounter}
3134 */
3135 public abstract ControllerActivityCounter getBluetoothControllerActivity();
3136
3137 /**
3138 * Returns true if the BatteryStats object has detailed modem power reports.
3139 * When true, calling {@link #getModemControllerActivity()} will yield the
3140 * actual power data.
3141 */
3142 public abstract boolean hasModemActivityReporting();
3143
3144 /**
3145 * Returns a {@link ControllerActivityCounter} which is an aggregate of the times spent
3146 * in various radio controller states, such as transmit, receive, and idle.
3147 * @return non-null {@link ControllerActivityCounter}
3148 */
3149 public abstract ControllerActivityCounter getModemControllerActivity();
3150
3151 /**
3152 * Return the wall clock time when battery stats data collection started.
3153 */
3154 public abstract long getStartClockTime();
3155
3156 /**
3157 * Return platform version tag that we were running in when the battery stats started.
3158 */
3159 public abstract String getStartPlatformVersion();
3160
3161 /**
3162 * Return platform version tag that we were running in when the battery stats ended.
3163 */
3164 public abstract String getEndPlatformVersion();
3165
3166 /**
3167 * Return the internal version code of the parcelled format.
3168 */
3169 public abstract int getParcelVersion();
3170
3171 /**
3172 * Return whether we are currently running on battery.
3173 */
3174 public abstract boolean getIsOnBattery();
3175
3176 /**
3177 * Returns the timestamp of when battery stats collection started, in microseconds.
3178 */
3179 public abstract long getStatsStartRealtime();
3180
3181 /**
3182 * Returns a SparseArray containing the statistics for each uid.
3183 */
3184 @UnsupportedAppUsage
3185 public abstract SparseArray<? extends Uid> getUidStats();
3186
3187 /**
3188 * Returns the current battery uptime in microseconds.
3189 *
3190 * @param curTime the amount of elapsed realtime in microseconds.
3191 */
3192 @UnsupportedAppUsage
3193 public abstract long getBatteryUptime(long curTime);
3194
3195 /**
3196 * Returns the current battery realtime in microseconds.
3197 *
3198 * @param curTime the amount of elapsed realtime in microseconds.
3199 */
3200 public abstract long getBatteryRealtime(long curTime);
3201
3202 /**
3203 * Returns the battery percentage level at the last time the device was unplugged from power, or
3204 * the last time it booted on battery power.
3205 */
3206 public abstract int getDischargeStartLevel();
3207
3208 /**
3209 * Returns the current battery percentage level if we are in a discharge cycle, otherwise
3210 * returns the level at the last plug event.
3211 */
3212 public abstract int getDischargeCurrentLevel();
3213
3214 /**
3215 * Get the amount the battery has discharged since the stats were
3216 * last reset after charging, as a lower-end approximation.
3217 */
3218 public abstract int getLowDischargeAmountSinceCharge();
3219
3220 /**
3221 * Get the amount the battery has discharged since the stats were
3222 * last reset after charging, as an upper-end approximation.
3223 */
3224 public abstract int getHighDischargeAmountSinceCharge();
3225
3226 /**
3227 * Retrieve the discharge amount over the selected discharge period <var>which</var>.
3228 */
3229 public abstract int getDischargeAmount(int which);
3230
3231 /**
3232 * Get the amount the battery has discharged while the screen was on,
3233 * since the last time power was unplugged.
3234 */
3235 public abstract int getDischargeAmountScreenOn();
3236
3237 /**
3238 * Get the amount the battery has discharged while the screen was on,
3239 * since the last time the device was charged.
3240 */
3241 public abstract int getDischargeAmountScreenOnSinceCharge();
3242
3243 /**
3244 * Get the amount the battery has discharged while the screen was off,
3245 * since the last time power was unplugged.
3246 */
3247 public abstract int getDischargeAmountScreenOff();
3248
3249 /**
3250 * Get the amount the battery has discharged while the screen was off,
3251 * since the last time the device was charged.
3252 */
3253 public abstract int getDischargeAmountScreenOffSinceCharge();
3254
3255 /**
3256 * Get the amount the battery has discharged while the screen was dozing,
3257 * since the last time power was unplugged.
3258 */
3259 public abstract int getDischargeAmountScreenDoze();
3260
3261 /**
3262 * Get the amount the battery has discharged while the screen was dozing,
3263 * since the last time the device was charged.
3264 */
3265 public abstract int getDischargeAmountScreenDozeSinceCharge();
3266
3267 /**
3268 * Returns the approximate CPU time (in microseconds) spent by the system server handling
3269 * incoming service calls from apps. The result is returned as an array of longs,
3270 * organized as a sequence like this:
3271 * <pre>
3272 * cluster1-speeed1, cluster1-speed2, ..., cluster2-speed1, cluster2-speed2, ...
3273 * </pre>
3274 *
3275 * @see com.android.internal.os.PowerProfile#getNumCpuClusters()
3276 * @see com.android.internal.os.PowerProfile#getNumSpeedStepsInCpuCluster(int)
3277 */
3278 @Nullable
3279 public abstract long[] getSystemServiceTimeAtCpuSpeeds();
3280
3281 /**
3282 * Returns the total, last, or current battery uptime in microseconds.
3283 *
3284 * @param curTime the elapsed realtime in microseconds.
3285 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3286 */
3287 @UnsupportedAppUsage
3288 public abstract long computeBatteryUptime(long curTime, int which);
3289
3290 /**
3291 * Returns the total, last, or current battery realtime in microseconds.
3292 *
3293 * @param curTime the current elapsed realtime in microseconds.
3294 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3295 */
3296 @UnsupportedAppUsage
3297 public abstract long computeBatteryRealtime(long curTime, int which);
3298
3299 /**
3300 * Returns the total, last, or current battery screen off/doze uptime in microseconds.
3301 *
3302 * @param curTime the elapsed realtime in microseconds.
3303 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3304 */
3305 public abstract long computeBatteryScreenOffUptime(long curTime, int which);
3306
3307 /**
3308 * Returns the total, last, or current battery screen off/doze realtime in microseconds.
3309 *
3310 * @param curTime the current elapsed realtime in microseconds.
3311 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3312 */
3313 public abstract long computeBatteryScreenOffRealtime(long curTime, int which);
3314
3315 /**
3316 * Returns the total, last, or current uptime in microseconds.
3317 *
3318 * @param curTime the current elapsed realtime in microseconds.
3319 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3320 */
3321 public abstract long computeUptime(long curTime, int which);
3322
3323 /**
3324 * Returns the total, last, or current realtime in microseconds.
3325 *
3326 * @param curTime the current elapsed realtime in microseconds.
3327 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3328 */
3329 public abstract long computeRealtime(long curTime, int which);
3330
3331 /**
3332 * Compute an approximation for how much run time (in microseconds) is remaining on
3333 * the battery. Returns -1 if no time can be computed: either there is not
3334 * enough current data to make a decision, or the battery is currently
3335 * charging.
3336 *
3337 * @param curTime The current elapsed realtime in microseconds.
3338 */
3339 @UnsupportedAppUsage
3340 public abstract long computeBatteryTimeRemaining(long curTime);
3341
3342 // The part of a step duration that is the actual time.
3343 public static final long STEP_LEVEL_TIME_MASK = 0x000000ffffffffffL;
3344
3345 // Bits in a step duration that are the new battery level we are at.
3346 public static final long STEP_LEVEL_LEVEL_MASK = 0x0000ff0000000000L;
3347 public static final int STEP_LEVEL_LEVEL_SHIFT = 40;
3348
3349 // Bits in a step duration that are the initial mode we were in at that step.
3350 public static final long STEP_LEVEL_INITIAL_MODE_MASK = 0x00ff000000000000L;
3351 public static final int STEP_LEVEL_INITIAL_MODE_SHIFT = 48;
3352
3353 // Bits in a step duration that indicate which modes changed during that step.
3354 public static final long STEP_LEVEL_MODIFIED_MODE_MASK = 0xff00000000000000L;
3355 public static final int STEP_LEVEL_MODIFIED_MODE_SHIFT = 56;
3356
3357 // Step duration mode: the screen is on, off, dozed, etc; value is Display.STATE_* - 1.
3358 public static final int STEP_LEVEL_MODE_SCREEN_STATE = 0x03;
3359
3360 // The largest value for screen state that is tracked in battery states. Any values above
3361 // this should be mapped back to one of the tracked values before being tracked here.
3362 public static final int MAX_TRACKED_SCREEN_STATE = Display.STATE_DOZE_SUSPEND;
3363
3364 // Step duration mode: power save is on.
3365 public static final int STEP_LEVEL_MODE_POWER_SAVE = 0x04;
3366
3367 // Step duration mode: device is currently in idle mode.
3368 public static final int STEP_LEVEL_MODE_DEVICE_IDLE = 0x08;
3369
3370 public static final int[] STEP_LEVEL_MODES_OF_INTEREST = new int[] {
3371 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE,
3372 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE|STEP_LEVEL_MODE_DEVICE_IDLE,
3373 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_DEVICE_IDLE,
3374 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE,
3375 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE,
3376 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE,
3377 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE,
3378 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE,
3379 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_POWER_SAVE|STEP_LEVEL_MODE_DEVICE_IDLE,
3380 STEP_LEVEL_MODE_SCREEN_STATE|STEP_LEVEL_MODE_DEVICE_IDLE,
3381 };
3382 public static final int[] STEP_LEVEL_MODE_VALUES = new int[] {
3383 (Display.STATE_OFF-1),
3384 (Display.STATE_OFF-1)|STEP_LEVEL_MODE_POWER_SAVE,
3385 (Display.STATE_OFF-1)|STEP_LEVEL_MODE_DEVICE_IDLE,
3386 (Display.STATE_ON-1),
3387 (Display.STATE_ON-1)|STEP_LEVEL_MODE_POWER_SAVE,
3388 (Display.STATE_DOZE-1),
3389 (Display.STATE_DOZE-1)|STEP_LEVEL_MODE_POWER_SAVE,
3390 (Display.STATE_DOZE_SUSPEND-1),
3391 (Display.STATE_DOZE_SUSPEND-1)|STEP_LEVEL_MODE_POWER_SAVE,
3392 (Display.STATE_DOZE_SUSPEND-1)|STEP_LEVEL_MODE_DEVICE_IDLE,
3393 };
3394 public static final String[] STEP_LEVEL_MODE_LABELS = new String[] {
3395 "screen off",
3396 "screen off power save",
3397 "screen off device idle",
3398 "screen on",
3399 "screen on power save",
3400 "screen doze",
3401 "screen doze power save",
3402 "screen doze-suspend",
3403 "screen doze-suspend power save",
3404 "screen doze-suspend device idle",
3405 };
3406
3407 /**
3408 * Return the amount of battery discharge while the screen was off, measured in
3409 * micro-Ampere-hours. This will be non-zero only if the device's battery has
3410 * a coulomb counter.
3411 */
3412 public abstract long getUahDischargeScreenOff(int which);
3413
3414 /**
3415 * Return the amount of battery discharge while the screen was in doze mode, measured in
3416 * micro-Ampere-hours. This will be non-zero only if the device's battery has
3417 * a coulomb counter.
3418 */
3419 public abstract long getUahDischargeScreenDoze(int which);
3420
3421 /**
3422 * Return the amount of battery discharge measured in micro-Ampere-hours. This will be
3423 * non-zero only if the device's battery has a coulomb counter.
3424 */
3425 public abstract long getUahDischarge(int which);
3426
3427 /**
3428 * @return the amount of battery discharge while the device is in light idle mode, measured in
3429 * micro-Ampere-hours.
3430 */
3431 public abstract long getUahDischargeLightDoze(int which);
3432
3433 /**
3434 * @return the amount of battery discharge while the device is in deep idle mode, measured in
3435 * micro-Ampere-hours.
3436 */
3437 public abstract long getUahDischargeDeepDoze(int which);
3438
3439 /**
3440 * Returns the estimated real battery capacity, which may be less than the capacity
3441 * declared by the PowerProfile.
3442 * @return The estimated battery capacity in mAh.
3443 */
3444 public abstract int getEstimatedBatteryCapacity();
3445
3446 /**
3447 * @return The minimum learned battery capacity in uAh.
3448 */
3449 public abstract int getMinLearnedBatteryCapacity();
3450
3451 /**
3452 * @return The maximum learned battery capacity in uAh.
3453 */
3454 public abstract int getMaxLearnedBatteryCapacity() ;
3455
3456 /**
3457 * @return The latest learned battery capacity in uAh.
3458 */
3459 public abstract int getLearnedBatteryCapacity();
3460
3461 /**
3462 * Return the array of discharge step durations.
3463 */
3464 public abstract LevelStepTracker getDischargeLevelStepTracker();
3465
3466 /**
3467 * Return the array of daily discharge step durations.
3468 */
3469 public abstract LevelStepTracker getDailyDischargeLevelStepTracker();
3470
3471 /**
3472 * Compute an approximation for how much time (in microseconds) remains until the battery
3473 * is fully charged. Returns -1 if no time can be computed: either there is not
3474 * enough current data to make a decision, or the battery is currently
3475 * discharging.
3476 *
3477 * @param curTime The current elepsed realtime in microseconds.
3478 */
3479 @UnsupportedAppUsage
3480 public abstract long computeChargeTimeRemaining(long curTime);
3481
3482 /**
3483 * Return the array of charge step durations.
3484 */
3485 public abstract LevelStepTracker getChargeLevelStepTracker();
3486
3487 /**
3488 * Return the array of daily charge step durations.
3489 */
3490 public abstract LevelStepTracker getDailyChargeLevelStepTracker();
3491
3492 public abstract ArrayList<PackageChange> getDailyPackageChanges();
3493
3494 public abstract Map<String, ? extends Timer> getWakeupReasonStats();
3495
3496 public abstract Map<String, ? extends Timer> getKernelWakelockStats();
3497
3498 /**
3499 * Returns aggregated wake lock stats.
3500 */
3501 public abstract WakeLockStats getWakeLockStats();
3502
3503 /**
3504 * Returns aggregated Bluetooth stats.
3505 */
3506 public abstract BluetoothBatteryStats getBluetoothBatteryStats();
3507
3508 /**
3509 * Returns Timers tracking the total time of each Resource Power Manager state and voter.
3510 */
3511 public abstract Map<String, ? extends Timer> getRpmStats();
3512 /**
3513 * Returns Timers tracking the screen-off time of each Resource Power Manager state and voter.
3514 */
3515 public abstract Map<String, ? extends Timer> getScreenOffRpmStats();
3516
3517
3518 public abstract LongSparseArray<? extends Timer> getKernelMemoryStats();
3519
3520 public abstract void writeToParcelWithoutUids(Parcel out, int flags);
3521
3522 private final static void formatTimeRaw(StringBuilder out, long seconds) {
3523 long days = seconds / (60 * 60 * 24);
3524 if (days != 0) {
3525 out.append(days);
3526 out.append("d ");
3527 }
3528 long used = days * 60 * 60 * 24;
3529
3530 long hours = (seconds - used) / (60 * 60);
3531 if (hours != 0 || used != 0) {
3532 out.append(hours);
3533 out.append("h ");
3534 }
3535 used += hours * 60 * 60;
3536
3537 long mins = (seconds-used) / 60;
3538 if (mins != 0 || used != 0) {
3539 out.append(mins);
3540 out.append("m ");
3541 }
3542 used += mins * 60;
3543
3544 if (seconds != 0 || used != 0) {
3545 out.append(seconds-used);
3546 out.append("s ");
3547 }
3548 }
3549
3550 public final static void formatTimeMs(StringBuilder sb, long time) {
3551 long sec = time / 1000;
3552 formatTimeRaw(sb, sec);
3553 sb.append(time - (sec * 1000));
3554 sb.append("ms ");
3555 }
3556
3557 public final static void formatTimeMsNoSpace(StringBuilder sb, long time) {
3558 long sec = time / 1000;
3559 formatTimeRaw(sb, sec);
3560 sb.append(time - (sec * 1000));
3561 sb.append("ms");
3562 }
3563
3564 public final String formatRatioLocked(long num, long den) {
3565 if (den == 0L) {
3566 return "--%";
3567 }
3568 float perc = ((float)num) / ((float)den) * 100;
3569 mFormatBuilder.setLength(0);
3570 mFormatter.format("%.1f%%", perc);
3571 return mFormatBuilder.toString();
3572 }
3573
3574 final String formatBytesLocked(long bytes) {
3575 mFormatBuilder.setLength(0);
3576
3577 if (bytes < BYTES_PER_KB) {
3578 return bytes + "B";
3579 } else if (bytes < BYTES_PER_MB) {
3580 mFormatter.format("%.2fKB", bytes / (double) BYTES_PER_KB);
3581 return mFormatBuilder.toString();
3582 } else if (bytes < BYTES_PER_GB){
3583 mFormatter.format("%.2fMB", bytes / (double) BYTES_PER_MB);
3584 return mFormatBuilder.toString();
3585 } else {
3586 mFormatter.format("%.2fGB", bytes / (double) BYTES_PER_GB);
3587 return mFormatBuilder.toString();
3588 }
3589 }
3590
3591 /**
3592 * Converts charge in mAh to string.
3593 */
3594 public static String formatCharge(double power) {
3595 return formatValue(power);
3596 }
3597
3598 /**
3599 * Converts double to string, limiting small values to 3 significant figures.
3600 */
3601 private static String formatValue(double value) {
3602 if (value == 0) return "0";
3603
3604 final String format;
3605 if (value < .00001) {
3606 format = "%.8f";
3607 } else if (value < .0001) {
3608 format = "%.7f";
3609 } else if (value < .001) {
3610 format = "%.6f";
3611 } else if (value < .01) {
3612 format = "%.5f";
3613 } else if (value < .1) {
3614 format = "%.4f";
3615 } else if (value < 1) {
3616 format = "%.3f";
3617 } else if (value < 10) {
3618 format = "%.2f";
3619 } else if (value < 100) {
3620 format = "%.1f";
3621 } else {
3622 format = "%.0f";
3623 }
3624
3625 // Use English locale because this is never used in UI (only in checkin and dump).
3626 return String.format(Locale.ENGLISH, format, value);
3627 }
3628
3629 private static long roundUsToMs(long timeUs) {
3630 return (timeUs + 500) / 1000;
3631 }
3632
3633 private static long computeWakeLock(Timer timer, long elapsedRealtimeUs, int which) {
3634 if (timer != null) {
3635 // Convert from microseconds to milliseconds with rounding
3636 long totalTimeMicros = timer.getTotalTimeLocked(elapsedRealtimeUs, which);
3637 long totalTimeMillis = (totalTimeMicros + 500) / 1000;
3638 return totalTimeMillis;
3639 }
3640 return 0;
3641 }
3642
3643 /**
3644 *
3645 * @param sb a StringBuilder object.
3646 * @param timer a Timer object contining the wakelock times.
3647 * @param elapsedRealtimeUs the current on-battery time in microseconds.
3648 * @param name the name of the wakelock.
3649 * @param which which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3650 * @param linePrefix a String to be prepended to each line of output.
3651 * @return the line prefix
3652 */
3653 private static final String printWakeLock(StringBuilder sb, Timer timer,
3654 long elapsedRealtimeUs, String name, int which, String linePrefix) {
3655
3656 if (timer != null) {
3657 long totalTimeMillis = computeWakeLock(timer, elapsedRealtimeUs, which);
3658
3659 int count = timer.getCountLocked(which);
3660 if (totalTimeMillis != 0) {
3661 sb.append(linePrefix);
3662 formatTimeMs(sb, totalTimeMillis);
3663 if (name != null) {
3664 sb.append(name);
3665 sb.append(' ');
3666 }
3667 sb.append('(');
3668 sb.append(count);
3669 sb.append(" times)");
3670 final long maxDurationMs = timer.getMaxDurationMsLocked(elapsedRealtimeUs/1000);
3671 if (maxDurationMs >= 0) {
3672 sb.append(" max=");
3673 sb.append(maxDurationMs);
3674 }
3675 // Put actual time if it is available and different from totalTimeMillis.
3676 final long totalDurMs = timer.getTotalDurationMsLocked(elapsedRealtimeUs/1000);
3677 if (totalDurMs > totalTimeMillis) {
3678 sb.append(" actual=");
3679 sb.append(totalDurMs);
3680 }
3681 if (timer.isRunningLocked()) {
3682 final long currentMs = timer.getCurrentDurationMsLocked(elapsedRealtimeUs/1000);
3683 if (currentMs >= 0) {
3684 sb.append(" (running for ");
3685 sb.append(currentMs);
3686 sb.append("ms)");
3687 } else {
3688 sb.append(" (running)");
3689 }
3690 }
3691
3692 return ", ";
3693 }
3694 }
3695 return linePrefix;
3696 }
3697
3698 /**
3699 * Prints details about a timer, if its total time was greater than 0.
3700 *
3701 * @param pw a PrintWriter object to print to.
3702 * @param sb a StringBuilder object.
3703 * @param timer a Timer object contining the wakelock times.
3704 * @param rawRealtimeUs the current on-battery time in microseconds.
3705 * @param which which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3706 * @param prefix a String to be prepended to each line of output.
3707 * @param type the name of the timer.
3708 * @return true if anything was printed.
3709 */
3710 private static final boolean printTimer(PrintWriter pw, StringBuilder sb, Timer timer,
3711 long rawRealtimeUs, int which, String prefix, String type) {
3712 if (timer != null) {
3713 // Convert from microseconds to milliseconds with rounding
3714 final long totalTimeMs = (timer.getTotalTimeLocked(
3715 rawRealtimeUs, which) + 500) / 1000;
3716 final int count = timer.getCountLocked(which);
3717 if (totalTimeMs != 0) {
3718 sb.setLength(0);
3719 sb.append(prefix);
3720 sb.append(" ");
3721 sb.append(type);
3722 sb.append(": ");
3723 formatTimeMs(sb, totalTimeMs);
3724 sb.append("realtime (");
3725 sb.append(count);
3726 sb.append(" times)");
3727 final long maxDurationMs = timer.getMaxDurationMsLocked(rawRealtimeUs/1000);
3728 if (maxDurationMs >= 0) {
3729 sb.append(" max=");
3730 sb.append(maxDurationMs);
3731 }
3732 if (timer.isRunningLocked()) {
3733 final long currentMs = timer.getCurrentDurationMsLocked(rawRealtimeUs/1000);
3734 if (currentMs >= 0) {
3735 sb.append(" (running for ");
3736 sb.append(currentMs);
3737 sb.append("ms)");
3738 } else {
3739 sb.append(" (running)");
3740 }
3741 }
3742 pw.println(sb.toString());
3743 return true;
3744 }
3745 }
3746 return false;
3747 }
3748
3749 /**
3750 * Checkin version of wakelock printer. Prints simple comma-separated list.
3751 *
3752 * @param sb a StringBuilder object.
3753 * @param timer a Timer object contining the wakelock times.
3754 * @param elapsedRealtimeUs the current time in microseconds.
3755 * @param name the name of the wakelock.
3756 * @param which which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT.
3757 * @param linePrefix a String to be prepended to each line of output.
3758 * @return the line prefix
3759 */
3760 private static final String printWakeLockCheckin(StringBuilder sb, Timer timer,
3761 long elapsedRealtimeUs, String name, int which, String linePrefix) {
3762 long totalTimeMicros = 0;
3763 int count = 0;
3764 long max = 0;
3765 long current = 0;
3766 long totalDuration = 0;
3767 if (timer != null) {
3768 totalTimeMicros = timer.getTotalTimeLocked(elapsedRealtimeUs, which);
3769 count = timer.getCountLocked(which);
3770 current = timer.getCurrentDurationMsLocked(elapsedRealtimeUs/1000);
3771 max = timer.getMaxDurationMsLocked(elapsedRealtimeUs/1000);
3772 totalDuration = timer.getTotalDurationMsLocked(elapsedRealtimeUs/1000);
3773 }
3774 sb.append(linePrefix);
3775 sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding
3776 sb.append(',');
3777 sb.append(name != null ? name + "," : "");
3778 sb.append(count);
3779 sb.append(',');
3780 sb.append(current);
3781 sb.append(',');
3782 sb.append(max);
3783 // Partial, full, and window wakelocks are pooled, so totalDuration is meaningful (albeit
3784 // not always tracked). Kernel wakelocks (which have name == null) have no notion of
3785 // totalDuration independent of totalTimeMicros (since they are not pooled).
3786 if (name != null) {
3787 sb.append(',');
3788 sb.append(totalDuration);
3789 }
3790 return ",";
3791 }
3792
3793 private static final void dumpLineHeader(PrintWriter pw, int uid, String category,
3794 String type) {
3795 pw.print(BATTERY_STATS_CHECKIN_VERSION);
3796 pw.print(',');
3797 pw.print(uid);
3798 pw.print(',');
3799 pw.print(category);
3800 pw.print(',');
3801 pw.print(type);
3802 }
3803
3804 /**
3805 * Dump a comma-separated line of values for terse checkin mode.
3806 *
3807 * @param pw the PageWriter to dump log to
3808 * @param category category of data (e.g. "total", "last", "unplugged", "current" )
3809 * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" , "process", "network")
3810 * @param args type-dependent data arguments
3811 */
3812 @UnsupportedAppUsage
3813 private static final void dumpLine(PrintWriter pw, int uid, String category, String type,
3814 Object... args ) {
3815 dumpLineHeader(pw, uid, category, type);
3816 for (Object arg : args) {
3817 pw.print(',');
3818 pw.print(arg);
3819 }
3820 pw.println();
3821 }
3822
3823 /**
3824 * Dump a given timer stat for terse checkin mode.
3825 *
3826 * @param pw the PageWriter to dump log to
3827 * @param uid the UID to log
3828 * @param category category of data (e.g. "total", "last", "unplugged", "current" )
3829 * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" , "process", "network")
3830 * @param timer a {@link Timer} to dump stats for
3831 * @param rawRealtime the current elapsed realtime of the system in microseconds
3832 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
3833 */
3834 private static final void dumpTimer(PrintWriter pw, int uid, String category, String type,
3835 Timer timer, long rawRealtime, int which) {
3836 if (timer != null) {
3837 // Convert from microseconds to milliseconds with rounding
3838 final long totalTime = roundUsToMs(timer.getTotalTimeLocked(rawRealtime, which));
3839 final int count = timer.getCountLocked(which);
3840 if (totalTime != 0 || count != 0) {
3841 dumpLine(pw, uid, category, type, totalTime, count);
3842 }
3843 }
3844 }
3845
3846 /**
3847 * Dump a given timer stat to the proto stream.
3848 *
3849 * @param proto the ProtoOutputStream to log to
3850 * @param fieldId type of data, the field to save to (e.g. AggregatedBatteryStats.WAKELOCK)
3851 * @param timer a {@link Timer} to dump stats for
3852 * @param rawRealtimeUs the current elapsed realtime of the system in microseconds
3853 * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT
3854 */
3855 private static void dumpTimer(ProtoOutputStream proto, long fieldId,
3856 Timer timer, long rawRealtimeUs, int which) {
3857 if (timer == null) {
3858 return;
3859 }
3860 // Convert from microseconds to milliseconds with rounding
3861 final long timeMs = roundUsToMs(timer.getTotalTimeLocked(rawRealtimeUs, which));
3862 final int count = timer.getCountLocked(which);
3863 final long maxDurationMs = timer.getMaxDurationMsLocked(rawRealtimeUs / 1000);
3864 final long curDurationMs = timer.getCurrentDurationMsLocked(rawRealtimeUs / 1000);
3865 final long totalDurationMs = timer.getTotalDurationMsLocked(rawRealtimeUs / 1000);
3866 if (timeMs != 0 || count != 0 || maxDurationMs != -1 || curDurationMs != -1
3867 || totalDurationMs != -1) {
3868 final long token = proto.start(fieldId);
3869 proto.write(TimerProto.DURATION_MS, timeMs);
3870 proto.write(TimerProto.COUNT, count);
3871 // These values will be -1 for timers that don't implement the functionality.
3872 if (maxDurationMs != -1) {
3873 proto.write(TimerProto.MAX_DURATION_MS, maxDurationMs);
3874 }
3875 if (curDurationMs != -1) {
3876 proto.write(TimerProto.CURRENT_DURATION_MS, curDurationMs);
3877 }
3878 if (totalDurationMs != -1) {
3879 proto.write(TimerProto.TOTAL_DURATION_MS, totalDurationMs);
3880 }
3881 proto.end(token);
3882 }
3883 }
3884
3885 /**
3886 * Checks if the ControllerActivityCounter has any data worth dumping.
3887 */
3888 private static boolean controllerActivityHasData(ControllerActivityCounter counter, int which) {
3889 if (counter == null) {
3890 return false;
3891 }
3892
3893 if (counter.getIdleTimeCounter().getCountLocked(which) != 0
3894 || counter.getRxTimeCounter().getCountLocked(which) != 0
3895 || counter.getPowerCounter().getCountLocked(which) != 0
3896 || counter.getMonitoredRailChargeConsumedMaMs().getCountLocked(which) != 0) {
3897 return true;
3898 }
3899
3900 for (LongCounter c : counter.getTxTimeCounters()) {
3901 if (c.getCountLocked(which) != 0) {
3902 return true;
3903 }
3904 }
3905 return false;
3906 }
3907
3908 /**
3909 * Dumps the ControllerActivityCounter if it has any data worth dumping.
3910 * The order of the arguments in the final check in line is:
3911 *
3912 * idle, rx, power, tx...
3913 *
3914 * where tx... is one or more transmit level times.
3915 */
3916 private static final void dumpControllerActivityLine(PrintWriter pw, int uid, String category,
3917 String type,
3918 ControllerActivityCounter counter,
3919 int which) {
3920 if (!controllerActivityHasData(counter, which)) {
3921 return;
3922 }
3923
3924 dumpLineHeader(pw, uid, category, type);
3925 pw.print(",");
3926 pw.print(counter.getIdleTimeCounter().getCountLocked(which));
3927 pw.print(",");
3928 pw.print(counter.getRxTimeCounter().getCountLocked(which));
3929 pw.print(",");
3930 pw.print(counter.getPowerCounter().getCountLocked(which) / (MILLISECONDS_IN_HOUR));
3931 pw.print(",");
3932 pw.print(counter.getMonitoredRailChargeConsumedMaMs().getCountLocked(which)
3933 / (MILLISECONDS_IN_HOUR));
3934 for (LongCounter c : counter.getTxTimeCounters()) {
3935 pw.print(",");
3936 pw.print(c.getCountLocked(which));
3937 }
3938 pw.println();
3939 }
3940
3941 /**
3942 * Dumps the ControllerActivityCounter if it has any data worth dumping.
3943 */
3944 private static void dumpControllerActivityProto(ProtoOutputStream proto, long fieldId,
3945 ControllerActivityCounter counter,
3946 int which) {
3947 if (!controllerActivityHasData(counter, which)) {
3948 return;
3949 }
3950
3951 final long cToken = proto.start(fieldId);
3952
3953 proto.write(ControllerActivityProto.IDLE_DURATION_MS,
3954 counter.getIdleTimeCounter().getCountLocked(which));
3955 proto.write(ControllerActivityProto.RX_DURATION_MS,
3956 counter.getRxTimeCounter().getCountLocked(which));
3957 proto.write(ControllerActivityProto.POWER_MAH,
3958 counter.getPowerCounter().getCountLocked(which) / (MILLISECONDS_IN_HOUR));
3959 proto.write(ControllerActivityProto.MONITORED_RAIL_CHARGE_MAH,
3960 counter.getMonitoredRailChargeConsumedMaMs().getCountLocked(which)
3961 / (MILLISECONDS_IN_HOUR));
3962
3963 long tToken;
3964 LongCounter[] txCounters = counter.getTxTimeCounters();
3965 for (int i = 0; i < txCounters.length; ++i) {
3966 LongCounter c = txCounters[i];
3967 tToken = proto.start(ControllerActivityProto.TX);
3968 proto.write(ControllerActivityProto.TxLevel.LEVEL, i);
3969 proto.write(ControllerActivityProto.TxLevel.DURATION_MS, c.getCountLocked(which));
3970 proto.end(tToken);
3971 }
3972
3973 proto.end(cToken);
3974 }
3975
3976 private final void printControllerActivityIfInteresting(PrintWriter pw, StringBuilder sb,
3977 String prefix, String controllerName,
3978 ControllerActivityCounter counter,
3979 int which) {
3980 if (controllerActivityHasData(counter, which)) {
3981 printControllerActivity(pw, sb, prefix, controllerName, counter, which);
3982 }
3983 }
3984
3985 private final void printControllerActivity(PrintWriter pw, StringBuilder sb, String prefix,
3986 String controllerName,
3987 ControllerActivityCounter counter, int which) {
3988 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
3989 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
3990 final long powerDrainMaMs = counter.getPowerCounter().getCountLocked(which);
3991 final long monitoredRailChargeConsumedMaMs =
3992 counter.getMonitoredRailChargeConsumedMaMs().getCountLocked(which);
3993 // Battery real time
3994 final long totalControllerActivityTimeMs
3995 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
3996 long totalTxTimeMs = 0;
3997 for (LongCounter txState : counter.getTxTimeCounters()) {
3998 totalTxTimeMs += txState.getCountLocked(which);
3999 }
4000
4001 if (controllerName.equals(WIFI_CONTROLLER_NAME)) {
4002 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
4003 sb.setLength(0);
4004 sb.append(prefix);
4005 sb.append(" ");
4006 sb.append(controllerName);
4007 sb.append(" Scan time: ");
4008 formatTimeMs(sb, scanTimeMs);
4009 sb.append("(");
4010 sb.append(formatRatioLocked(scanTimeMs, totalControllerActivityTimeMs));
4011 sb.append(")");
4012 pw.println(sb.toString());
4013
4014 final long sleepTimeMs
4015 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
4016 sb.setLength(0);
4017 sb.append(prefix);
4018 sb.append(" ");
4019 sb.append(controllerName);
4020 sb.append(" Sleep time: ");
4021 formatTimeMs(sb, sleepTimeMs);
4022 sb.append("(");
4023 sb.append(formatRatioLocked(sleepTimeMs, totalControllerActivityTimeMs));
4024 sb.append(")");
4025 pw.println(sb.toString());
4026 }
4027
4028 if (controllerName.equals(CELLULAR_CONTROLLER_NAME)) {
4029 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
4030 sb.setLength(0);
4031 sb.append(prefix);
4032 sb.append(" ");
4033 sb.append(controllerName);
4034 sb.append(" Sleep time: ");
4035 formatTimeMs(sb, sleepTimeMs);
4036 sb.append("(");
4037 sb.append(formatRatioLocked(sleepTimeMs, totalControllerActivityTimeMs));
4038 sb.append(")");
4039 pw.println(sb.toString());
4040 }
4041
4042 sb.setLength(0);
4043 sb.append(prefix);
4044 sb.append(" ");
4045 sb.append(controllerName);
4046 sb.append(" Idle time: ");
4047 formatTimeMs(sb, idleTimeMs);
4048 sb.append("(");
4049 sb.append(formatRatioLocked(idleTimeMs, totalControllerActivityTimeMs));
4050 sb.append(")");
4051 pw.println(sb.toString());
4052
4053 sb.setLength(0);
4054 sb.append(prefix);
4055 sb.append(" ");
4056 sb.append(controllerName);
4057 sb.append(" Rx time: ");
4058 formatTimeMs(sb, rxTimeMs);
4059 sb.append("(");
4060 sb.append(formatRatioLocked(rxTimeMs, totalControllerActivityTimeMs));
4061 sb.append(")");
4062 pw.println(sb.toString());
4063
4064 sb.setLength(0);
4065 sb.append(prefix);
4066 sb.append(" ");
4067 sb.append(controllerName);
4068 sb.append(" Tx time: ");
4069
4070 String [] powerLevel;
4071 switch(controllerName) {
4072 case CELLULAR_CONTROLLER_NAME:
4073 powerLevel = new String[] {
4074 " less than 0dBm: ",
4075 " 0dBm to 8dBm: ",
4076 " 8dBm to 15dBm: ",
4077 " 15dBm to 20dBm: ",
4078 " above 20dBm: "};
4079 break;
4080 default:
4081 powerLevel = new String[] {"[0]", "[1]", "[2]", "[3]", "[4]"};
4082 break;
4083 }
4084 final int numTxLvls = Math.min(counter.getTxTimeCounters().length, powerLevel.length);
4085 if (numTxLvls > 1) {
4086 pw.println(sb.toString());
4087 for (int lvl = 0; lvl < numTxLvls; lvl++) {
4088 final long txLvlTimeMs = counter.getTxTimeCounters()[lvl].getCountLocked(which);
4089 sb.setLength(0);
4090 sb.append(prefix);
4091 sb.append(" ");
4092 sb.append(powerLevel[lvl]);
4093 sb.append(" ");
4094 formatTimeMs(sb, txLvlTimeMs);
4095 sb.append("(");
4096 sb.append(formatRatioLocked(txLvlTimeMs, totalControllerActivityTimeMs));
4097 sb.append(")");
4098 pw.println(sb.toString());
4099 }
4100 } else {
4101 final long txLvlTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
4102 formatTimeMs(sb, txLvlTimeMs);
4103 sb.append("(");
4104 sb.append(formatRatioLocked(txLvlTimeMs, totalControllerActivityTimeMs));
4105 sb.append(")");
4106 pw.println(sb.toString());
4107 }
4108
4109 if (powerDrainMaMs > 0) {
4110 sb.setLength(0);
4111 sb.append(prefix);
4112 sb.append(" ");
4113 sb.append(controllerName);
4114 sb.append(" Battery drain: ").append(
4115 formatCharge(powerDrainMaMs / MILLISECONDS_IN_HOUR));
4116 sb.append("mAh");
4117 pw.println(sb.toString());
4118 }
4119
4120 if (monitoredRailChargeConsumedMaMs > 0) {
4121 sb.setLength(0);
4122 sb.append(prefix);
4123 sb.append(" ");
4124 sb.append(controllerName);
4125 sb.append(" Monitored rail energy drain: ").append(
4126 new DecimalFormat("#.##").format(
4127 monitoredRailChargeConsumedMaMs / MILLISECONDS_IN_HOUR));
4128 sb.append(" mAh");
4129 pw.println(sb.toString());
4130 }
4131 }
4132
4133 private void printCellularPerRatBreakdown(PrintWriter pw, StringBuilder sb, String prefix,
4134 long rawRealtimeMs) {
4135 final String allFrequenciesHeader =
4136 " All frequencies:\n";
4137 final String[] nrFrequencyRangeDescription = new String[]{
4138 " Unknown frequency:\n",
4139 " Low frequency (less than 1GHz):\n",
4140 " Middle frequency (1GHz to 3GHz):\n",
4141 " High frequency (3GHz to 6GHz):\n",
4142 " Mmwave frequency (greater than 6GHz):\n"};
4143 final String signalStrengthHeader =
4144 " Signal Strength Time:\n";
4145 final String txHeader =
4146 " Tx Time:\n";
4147 final String rxHeader =
4148 " Rx Time: ";
4149 final String[] signalStrengthDescription = new String[]{
4150 " unknown: ",
4151 " poor: ",
4152 " moderate: ",
4153 " good: ",
4154 " great: "};
4155
4156 final long totalActiveTimesMs = getMobileRadioActiveTime(rawRealtimeMs * 1000,
4157 STATS_SINCE_CHARGED) / 1000;
4158
4159 sb.setLength(0);
4160 sb.append(prefix);
4161 sb.append("Active Cellular Radio Access Technology Breakdown:");
4162 pw.println(sb);
4163
4164 boolean hasData = false;
4165 final int numSignalStrength = CellSignalStrength.getNumSignalStrengthLevels();
4166 for (int rat = RADIO_ACCESS_TECHNOLOGY_COUNT - 1; rat >= 0; rat--) {
4167 sb.setLength(0);
4168 sb.append(prefix);
4169 sb.append(" ");
4170 sb.append(RADIO_ACCESS_TECHNOLOGY_NAMES[rat]);
4171 sb.append(":\n");
4172 sb.append(prefix);
4173
4174 final int numFreqLvl =
4175 rat == RADIO_ACCESS_TECHNOLOGY_NR ? nrFrequencyRangeDescription.length : 1;
4176 for (int freqLvl = numFreqLvl - 1; freqLvl >= 0; freqLvl--) {
4177 final int freqDescriptionStart = sb.length();
4178 boolean hasFreqData = false;
4179 if (rat == RADIO_ACCESS_TECHNOLOGY_NR) {
4180 sb.append(nrFrequencyRangeDescription[freqLvl]);
4181 } else {
4182 sb.append(allFrequenciesHeader);
4183 }
4184
4185 sb.append(prefix);
4186 sb.append(signalStrengthHeader);
4187 for (int strength = 0; strength < numSignalStrength; strength++) {
4188 final long timeMs = getActiveRadioDurationMs(rat, freqLvl, strength,
4189 rawRealtimeMs);
4190 if (timeMs <= 0) continue;
4191 hasFreqData = true;
4192 sb.append(prefix);
4193 sb.append(signalStrengthDescription[strength]);
4194 formatTimeMs(sb, timeMs);
4195 sb.append("(");
4196 sb.append(formatRatioLocked(timeMs, totalActiveTimesMs));
4197 sb.append(")\n");
4198 }
4199
4200 sb.append(prefix);
4201 sb.append(txHeader);
4202 for (int strength = 0; strength < numSignalStrength; strength++) {
4203 final long timeMs = getActiveTxRadioDurationMs(rat, freqLvl, strength,
4204 rawRealtimeMs);
4205 if (timeMs <= 0) continue;
4206 hasFreqData = true;
4207 sb.append(prefix);
4208 sb.append(signalStrengthDescription[strength]);
4209 formatTimeMs(sb, timeMs);
4210 sb.append("(");
4211 sb.append(formatRatioLocked(timeMs, totalActiveTimesMs));
4212 sb.append(")\n");
4213 }
4214
4215 sb.append(prefix);
4216 sb.append(rxHeader);
4217 final long rxTimeMs = getActiveRxRadioDurationMs(rat, freqLvl, rawRealtimeMs);
4218 formatTimeMs(sb, rxTimeMs);
4219 sb.append("(");
4220 sb.append(formatRatioLocked(rxTimeMs, totalActiveTimesMs));
4221 sb.append(")\n");
4222
4223 if (hasFreqData) {
4224 hasData = true;
4225 pw.print(sb);
4226 sb.setLength(0);
4227 sb.append(prefix);
4228 } else {
4229 // No useful data was printed, rewind sb to before the start of this frequency.
4230 sb.setLength(freqDescriptionStart);
4231 }
4232 }
4233 }
4234
4235 if (!hasData) {
4236 sb.setLength(0);
4237 sb.append(prefix);
4238 sb.append(" (no activity)");
4239 pw.println(sb);
4240 }
4241 }
4242
4243 /**
4244 * Temporary for settings.
4245 */
4246 public final void dumpCheckinLocked(Context context, PrintWriter pw, int which, int reqUid) {
4247 dumpCheckinLocked(context, pw, which, reqUid, checkWifiOnly(context));
4248 }
4249
4250 private static final String[] CHECKIN_POWER_COMPONENT_LABELS =
4251 new String[BatteryConsumer.POWER_COMPONENT_COUNT];
4252 static {
4253 // Assign individually to avoid future mismatch of indices
4254 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_SCREEN] = "scrn";
4255 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_CPU] = "cpu";
4256 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_BLUETOOTH] = "blue";
4257 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_CAMERA] = "camera";
4258 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_AUDIO] = "audio";
4259 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_VIDEO] = "video";
4260 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_FLASHLIGHT] = "flashlight";
4261 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_MOBILE_RADIO] = "cell";
4262 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_SENSORS] = "sensors";
4263 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_GNSS] = "gnss";
4264 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_WIFI] = "wifi";
4265 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_MEMORY] = "memory";
4266 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_PHONE] = "phone";
4267 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY] = "ambi";
4268 CHECKIN_POWER_COMPONENT_LABELS[BatteryConsumer.POWER_COMPONENT_IDLE] = "idle";
4269 }
4270
4271 /**
4272 * Checkin server version of dump to produce more compact, computer-readable log.
4273 *
4274 * NOTE: all times are expressed in microseconds, unless specified otherwise.
4275 */
4276 public final void dumpCheckinLocked(Context context, PrintWriter pw, int which, int reqUid,
4277 boolean wifiOnly) {
4278
4279 if (which != BatteryStats.STATS_SINCE_CHARGED) {
4280 dumpLine(pw, 0, STAT_NAMES[which], "err",
4281 "ERROR: BatteryStats.dumpCheckin called for which type " + which
4282 + " but only STATS_SINCE_CHARGED is supported.");
4283 return;
4284 }
4285
4286 final long rawUptime = SystemClock.uptimeMillis() * 1000;
4287 final long rawRealtimeMs = SystemClock.elapsedRealtime();
4288 final long rawRealtime = rawRealtimeMs * 1000;
4289 final long batteryUptime = getBatteryUptime(rawUptime);
4290 final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
4291 final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
4292 final long whichBatteryScreenOffUptime = computeBatteryScreenOffUptime(rawUptime, which);
4293 final long whichBatteryScreenOffRealtime = computeBatteryScreenOffRealtime(rawRealtime,
4294 which);
4295 final long totalRealtime = computeRealtime(rawRealtime, which);
4296 final long totalUptime = computeUptime(rawUptime, which);
4297 final long screenOnTime = getScreenOnTime(rawRealtime, which);
4298 final long screenDozeTime = getScreenDozeTime(rawRealtime, which);
4299 final long interactiveTime = getInteractiveTime(rawRealtime, which);
4300 final long powerSaveModeEnabledTime = getPowerSaveModeEnabledTime(rawRealtime, which);
4301 final long deviceIdleModeLightTime = getDeviceIdleModeTime(DEVICE_IDLE_MODE_LIGHT,
4302 rawRealtime, which);
4303 final long deviceIdleModeFullTime = getDeviceIdleModeTime(DEVICE_IDLE_MODE_DEEP,
4304 rawRealtime, which);
4305 final long deviceLightIdlingTime = getDeviceIdlingTime(DEVICE_IDLE_MODE_LIGHT,
4306 rawRealtime, which);
4307 final long deviceIdlingTime = getDeviceIdlingTime(DEVICE_IDLE_MODE_DEEP,
4308 rawRealtime, which);
4309 final int connChanges = getNumConnectivityChange(which);
4310 final long phoneOnTime = getPhoneOnTime(rawRealtime, which);
4311 final long dischargeCount = getUahDischarge(which);
4312 final long dischargeScreenOffCount = getUahDischargeScreenOff(which);
4313 final long dischargeScreenDozeCount = getUahDischargeScreenDoze(which);
4314 final long dischargeLightDozeCount = getUahDischargeLightDoze(which);
4315 final long dischargeDeepDozeCount = getUahDischargeDeepDoze(which);
4316
4317 final StringBuilder sb = new StringBuilder(128);
4318
4319 final SparseArray<? extends Uid> uidStats = getUidStats();
4320 final int NU = uidStats.size();
4321
4322 final String category = STAT_NAMES[which];
4323
4324 // Dump "battery" stat
4325 dumpLine(pw, 0 /* uid */, category, BATTERY_DATA,
4326 which == STATS_SINCE_CHARGED ? getStartCount() : "N/A",
4327 whichBatteryRealtime / 1000, whichBatteryUptime / 1000,
4328 totalRealtime / 1000, totalUptime / 1000,
4329 getStartClockTime(),
4330 whichBatteryScreenOffRealtime / 1000, whichBatteryScreenOffUptime / 1000,
4331 getEstimatedBatteryCapacity(),
4332 getMinLearnedBatteryCapacity(),
4333 getMaxLearnedBatteryCapacity(),
4334 screenDozeTime / 1000);
4335
4336
4337 // Calculate wakelock times across all uids.
4338 long fullWakeLockTimeTotal = 0;
4339 long partialWakeLockTimeTotal = 0;
4340
4341 for (int iu = 0; iu < NU; iu++) {
4342 final Uid u = uidStats.valueAt(iu);
4343
4344 final ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> wakelocks
4345 = u.getWakelockStats();
4346 for (int iw=wakelocks.size()-1; iw>=0; iw--) {
4347 final Uid.Wakelock wl = wakelocks.valueAt(iw);
4348
4349 final Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
4350 if (fullWakeTimer != null) {
4351 fullWakeLockTimeTotal += fullWakeTimer.getTotalTimeLocked(rawRealtime,
4352 which);
4353 }
4354
4355 final Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
4356 if (partialWakeTimer != null) {
4357 partialWakeLockTimeTotal += partialWakeTimer.getTotalTimeLocked(
4358 rawRealtime, which);
4359 }
4360 }
4361 }
4362
4363 // Dump network stats
4364 final long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
4365 final long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
4366 final long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
4367 final long wifiTxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
4368 final long mobileRxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
4369 final long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
4370 final long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
4371 final long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
4372 final long btRxTotalBytes = getNetworkActivityBytes(NETWORK_BT_RX_DATA, which);
4373 final long btTxTotalBytes = getNetworkActivityBytes(NETWORK_BT_TX_DATA, which);
4374 dumpLine(pw, 0 /* uid */, category, GLOBAL_NETWORK_DATA,
4375 mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes,
4376 mobileRxTotalPackets, mobileTxTotalPackets, wifiRxTotalPackets, wifiTxTotalPackets,
4377 btRxTotalBytes, btTxTotalBytes);
4378
4379 // Dump Modem controller stats
4380 dumpControllerActivityLine(pw, 0 /* uid */, category, GLOBAL_MODEM_CONTROLLER_DATA,
4381 getModemControllerActivity(), which);
4382
4383 // Dump Wifi controller stats
4384 final long wifiOnTime = getWifiOnTime(rawRealtime, which);
4385 final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which);
4386 dumpLine(pw, 0 /* uid */, category, GLOBAL_WIFI_DATA, wifiOnTime / 1000,
4387 wifiRunningTime / 1000, /* legacy fields follow, keep at 0 */ 0, 0, 0);
4388
4389 dumpControllerActivityLine(pw, 0 /* uid */, category, GLOBAL_WIFI_CONTROLLER_DATA,
4390 getWifiControllerActivity(), which);
4391
4392 // Dump Bluetooth controller stats
4393 dumpControllerActivityLine(pw, 0 /* uid */, category, GLOBAL_BLUETOOTH_CONTROLLER_DATA,
4394 getBluetoothControllerActivity(), which);
4395
4396 // Dump misc stats
4397 dumpLine(pw, 0 /* uid */, category, MISC_DATA,
4398 screenOnTime / 1000, phoneOnTime / 1000,
4399 fullWakeLockTimeTotal / 1000, partialWakeLockTimeTotal / 1000,
4400 getMobileRadioActiveTime(rawRealtime, which) / 1000,
4401 getMobileRadioActiveAdjustedTime(which) / 1000, interactiveTime / 1000,
4402 powerSaveModeEnabledTime / 1000, connChanges, deviceIdleModeFullTime / 1000,
4403 getDeviceIdleModeCount(DEVICE_IDLE_MODE_DEEP, which), deviceIdlingTime / 1000,
4404 getDeviceIdlingCount(DEVICE_IDLE_MODE_DEEP, which),
4405 getMobileRadioActiveCount(which),
4406 getMobileRadioActiveUnknownTime(which) / 1000, deviceIdleModeLightTime / 1000,
4407 getDeviceIdleModeCount(DEVICE_IDLE_MODE_LIGHT, which), deviceLightIdlingTime / 1000,
4408 getDeviceIdlingCount(DEVICE_IDLE_MODE_LIGHT, which),
4409 getLongestDeviceIdleModeTime(DEVICE_IDLE_MODE_LIGHT),
4410 getLongestDeviceIdleModeTime(DEVICE_IDLE_MODE_DEEP));
4411
4412 // Dump screen brightness stats
4413 Object[] args = new Object[NUM_SCREEN_BRIGHTNESS_BINS];
4414 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
4415 args[i] = getScreenBrightnessTime(i, rawRealtime, which) / 1000;
4416 }
4417 dumpLine(pw, 0 /* uid */, category, SCREEN_BRIGHTNESS_DATA, args);
4418
4419 // Dump signal strength stats
4420 args = new Object[CellSignalStrength.getNumSignalStrengthLevels()];
4421 for (int i = 0; i < CellSignalStrength.getNumSignalStrengthLevels(); i++) {
4422 args[i] = getPhoneSignalStrengthTime(i, rawRealtime, which) / 1000;
4423 }
4424 dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_TIME_DATA, args);
4425 dumpLine(pw, 0 /* uid */, category, SIGNAL_SCANNING_TIME_DATA,
4426 getPhoneSignalScanningTime(rawRealtime, which) / 1000);
4427 for (int i = 0; i < CellSignalStrength.getNumSignalStrengthLevels(); i++) {
4428 args[i] = getPhoneSignalStrengthCount(i, which);
4429 }
4430 dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_COUNT_DATA, args);
4431
4432 // Dump network type stats
4433 args = new Object[NUM_DATA_CONNECTION_TYPES];
4434 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
4435 args[i] = getPhoneDataConnectionTime(i, rawRealtime, which) / 1000;
4436 }
4437 dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_TIME_DATA, args);
4438 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
4439 args[i] = getPhoneDataConnectionCount(i, which);
4440 }
4441 dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_COUNT_DATA, args);
4442
4443 // Dump wifi state stats
4444 args = new Object[NUM_WIFI_STATES];
4445 for (int i=0; i<NUM_WIFI_STATES; i++) {
4446 args[i] = getWifiStateTime(i, rawRealtime, which) / 1000;
4447 }
4448 dumpLine(pw, 0 /* uid */, category, WIFI_STATE_TIME_DATA, args);
4449 for (int i=0; i<NUM_WIFI_STATES; i++) {
4450 args[i] = getWifiStateCount(i, which);
4451 }
4452 dumpLine(pw, 0 /* uid */, category, WIFI_STATE_COUNT_DATA, args);
4453
4454 // Dump wifi suppl state stats
4455 args = new Object[NUM_WIFI_SUPPL_STATES];
4456 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
4457 args[i] = getWifiSupplStateTime(i, rawRealtime, which) / 1000;
4458 }
4459 dumpLine(pw, 0 /* uid */, category, WIFI_SUPPL_STATE_TIME_DATA, args);
4460 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
4461 args[i] = getWifiSupplStateCount(i, which);
4462 }
4463 dumpLine(pw, 0 /* uid */, category, WIFI_SUPPL_STATE_COUNT_DATA, args);
4464
4465 // Dump wifi signal strength stats
4466 args = new Object[NUM_WIFI_SIGNAL_STRENGTH_BINS];
4467 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
4468 args[i] = getWifiSignalStrengthTime(i, rawRealtime, which) / 1000;
4469 }
4470 dumpLine(pw, 0 /* uid */, category, WIFI_SIGNAL_STRENGTH_TIME_DATA, args);
4471 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
4472 args[i] = getWifiSignalStrengthCount(i, which);
4473 }
4474 dumpLine(pw, 0 /* uid */, category, WIFI_SIGNAL_STRENGTH_COUNT_DATA, args);
4475
4476 // Dump Multicast total stats
4477 final long multicastWakeLockTimeTotalMicros =
4478 getWifiMulticastWakelockTime(rawRealtime, which);
4479 final int multicastWakeLockCountTotal = getWifiMulticastWakelockCount(which);
4480 dumpLine(pw, 0 /* uid */, category, WIFI_MULTICAST_TOTAL_DATA,
4481 multicastWakeLockTimeTotalMicros / 1000,
4482 multicastWakeLockCountTotal);
4483
4484 dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
4485 getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(),
4486 getDischargeAmountScreenOnSinceCharge(),
4487 getDischargeAmountScreenOffSinceCharge(),
4488 dischargeCount / 1000, dischargeScreenOffCount / 1000,
4489 getDischargeAmountScreenDozeSinceCharge(), dischargeScreenDozeCount / 1000,
4490 dischargeLightDozeCount / 1000, dischargeDeepDozeCount / 1000);
4491
4492 if (reqUid < 0) {
4493 final Map<String, ? extends Timer> kernelWakelocks = getKernelWakelockStats();
4494 if (kernelWakelocks.size() > 0) {
4495 for (Map.Entry<String, ? extends Timer> ent : kernelWakelocks.entrySet()) {
4496 sb.setLength(0);
4497 printWakeLockCheckin(sb, ent.getValue(), rawRealtime, null, which, "");
4498 dumpLine(pw, 0 /* uid */, category, KERNEL_WAKELOCK_DATA,
4499 "\"" + ent.getKey() + "\"", sb.toString());
4500 }
4501 }
4502 final Map<String, ? extends Timer> wakeupReasons = getWakeupReasonStats();
4503 if (wakeupReasons.size() > 0) {
4504 for (Map.Entry<String, ? extends Timer> ent : wakeupReasons.entrySet()) {
4505 // Not doing the regular wake lock formatting to remain compatible
4506 // with the old checkin format.
4507 long totalTimeMicros = ent.getValue().getTotalTimeLocked(rawRealtime, which);
4508 int count = ent.getValue().getCountLocked(which);
4509 dumpLine(pw, 0 /* uid */, category, WAKEUP_REASON_DATA,
4510 "\"" + ent.getKey() + "\"", (totalTimeMicros + 500) / 1000, count);
4511 }
4512 }
4513 }
4514
4515 final Map<String, ? extends Timer> rpmStats = getRpmStats();
4516 final Map<String, ? extends Timer> screenOffRpmStats = getScreenOffRpmStats();
4517 if (rpmStats.size() > 0) {
4518 for (Map.Entry<String, ? extends Timer> ent : rpmStats.entrySet()) {
4519 sb.setLength(0);
4520 Timer totalTimer = ent.getValue();
4521 long timeMs = (totalTimer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000;
4522 int count = totalTimer.getCountLocked(which);
4523 Timer screenOffTimer = screenOffRpmStats.get(ent.getKey());
4524 long screenOffTimeMs = screenOffTimer != null
4525 ? (screenOffTimer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000 : 0;
4526 int screenOffCount = screenOffTimer != null
4527 ? screenOffTimer.getCountLocked(which) : 0;
4528 if (SCREEN_OFF_RPM_STATS_ENABLED) {
4529 dumpLine(pw, 0 /* uid */, category, RESOURCE_POWER_MANAGER_DATA,
4530 "\"" + ent.getKey() + "\"", timeMs, count, screenOffTimeMs,
4531 screenOffCount);
4532 } else {
4533 dumpLine(pw, 0 /* uid */, category, RESOURCE_POWER_MANAGER_DATA,
4534 "\"" + ent.getKey() + "\"", timeMs, count);
4535 }
4536 }
4537 }
4538
4539 final BatteryUsageStats stats = getBatteryUsageStats(context);
4540 dumpLine(pw, 0 /* uid */, category, POWER_USE_SUMMARY_DATA,
4541 formatCharge(stats.getBatteryCapacity()),
4542 formatCharge(stats.getConsumedPower()),
4543 formatCharge(stats.getDischargedPowerRange().getLower()),
4544 formatCharge(stats.getDischargedPowerRange().getUpper()));
4545 final BatteryConsumer deviceConsumer = stats.getAggregateBatteryConsumer(
4546 BatteryUsageStats.AGGREGATE_BATTERY_CONSUMER_SCOPE_DEVICE);
4547 for (@BatteryConsumer.PowerComponent int powerComponent = 0;
4548 powerComponent < BatteryConsumer.POWER_COMPONENT_COUNT; powerComponent++) {
4549 String label = CHECKIN_POWER_COMPONENT_LABELS[powerComponent];
4550 if (label == null) {
4551 label = "???";
4552 }
4553 dumpLine(pw, 0 /* uid */, category, POWER_USE_ITEM_DATA, label,
4554 formatCharge(deviceConsumer.getConsumedPower(powerComponent)),
4555 shouldHidePowerComponent(powerComponent) ? 1 : 0, "0", "0");
4556 }
4557
4558 final ProportionalAttributionCalculator proportionalAttributionCalculator =
4559 new ProportionalAttributionCalculator(context, stats);
4560 final List<UidBatteryConsumer> uidBatteryConsumers = stats.getUidBatteryConsumers();
4561 for (int i = 0; i < uidBatteryConsumers.size(); i++) {
4562 UidBatteryConsumer consumer = uidBatteryConsumers.get(i);
4563 dumpLine(pw, consumer.getUid(), category, POWER_USE_ITEM_DATA, "uid",
4564 formatCharge(consumer.getConsumedPower()),
4565 proportionalAttributionCalculator.isSystemBatteryConsumer(consumer) ? 1 : 0,
4566 formatCharge(consumer.getConsumedPower(BatteryConsumer.POWER_COMPONENT_SCREEN)),
4567 formatCharge(
4568 proportionalAttributionCalculator.getProportionalPowerMah(consumer)));
4569 }
4570
4571 final long[] cpuFreqs = getCpuFreqs();
4572 if (cpuFreqs != null) {
4573 sb.setLength(0);
4574 for (int i = 0; i < cpuFreqs.length; ++i) {
4575 if (i != 0) sb.append(',');
4576 sb.append(cpuFreqs[i]);
4577 }
4578 dumpLine(pw, 0 /* uid */, category, GLOBAL_CPU_FREQ_DATA, sb.toString());
4579 }
4580
4581 // Dump stats per UID.
4582 for (int iu = 0; iu < NU; iu++) {
4583 final int uid = uidStats.keyAt(iu);
4584 if (reqUid >= 0 && uid != reqUid) {
4585 continue;
4586 }
4587 final Uid u = uidStats.valueAt(iu);
4588
4589 // Dump Network stats per uid, if any
4590 final long mobileBytesRx = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
4591 final long mobileBytesTx = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
4592 final long wifiBytesRx = u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
4593 final long wifiBytesTx = u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
4594 final long mobilePacketsRx = u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
4595 final long mobilePacketsTx = u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
4596 final long mobileActiveTime = u.getMobileRadioActiveTime(which);
4597 final int mobileActiveCount = u.getMobileRadioActiveCount(which);
4598 final long mobileWakeup = u.getMobileRadioApWakeupCount(which);
4599 final long wifiPacketsRx = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
4600 final long wifiPacketsTx = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
4601 final long wifiWakeup = u.getWifiRadioApWakeupCount(which);
4602 final long btBytesRx = u.getNetworkActivityBytes(NETWORK_BT_RX_DATA, which);
4603 final long btBytesTx = u.getNetworkActivityBytes(NETWORK_BT_TX_DATA, which);
4604 // Background data transfers
4605 final long mobileBytesBgRx = u.getNetworkActivityBytes(NETWORK_MOBILE_BG_RX_DATA,
4606 which);
4607 final long mobileBytesBgTx = u.getNetworkActivityBytes(NETWORK_MOBILE_BG_TX_DATA,
4608 which);
4609 final long wifiBytesBgRx = u.getNetworkActivityBytes(NETWORK_WIFI_BG_RX_DATA, which);
4610 final long wifiBytesBgTx = u.getNetworkActivityBytes(NETWORK_WIFI_BG_TX_DATA, which);
4611 final long mobilePacketsBgRx = u.getNetworkActivityPackets(NETWORK_MOBILE_BG_RX_DATA,
4612 which);
4613 final long mobilePacketsBgTx = u.getNetworkActivityPackets(NETWORK_MOBILE_BG_TX_DATA,
4614 which);
4615 final long wifiPacketsBgRx = u.getNetworkActivityPackets(NETWORK_WIFI_BG_RX_DATA,
4616 which);
4617 final long wifiPacketsBgTx = u.getNetworkActivityPackets(NETWORK_WIFI_BG_TX_DATA,
4618 which);
4619
4620 if (mobileBytesRx > 0 || mobileBytesTx > 0 || wifiBytesRx > 0 || wifiBytesTx > 0
4621 || mobilePacketsRx > 0 || mobilePacketsTx > 0 || wifiPacketsRx > 0
4622 || wifiPacketsTx > 0 || mobileActiveTime > 0 || mobileActiveCount > 0
4623 || btBytesRx > 0 || btBytesTx > 0 || mobileWakeup > 0 || wifiWakeup > 0
4624 || mobileBytesBgRx > 0 || mobileBytesBgTx > 0 || wifiBytesBgRx > 0
4625 || wifiBytesBgTx > 0
4626 || mobilePacketsBgRx > 0 || mobilePacketsBgTx > 0 || wifiPacketsBgRx > 0
4627 || wifiPacketsBgTx > 0) {
4628 dumpLine(pw, uid, category, NETWORK_DATA, mobileBytesRx, mobileBytesTx,
4629 wifiBytesRx, wifiBytesTx,
4630 mobilePacketsRx, mobilePacketsTx,
4631 wifiPacketsRx, wifiPacketsTx,
4632 mobileActiveTime, mobileActiveCount,
4633 btBytesRx, btBytesTx, mobileWakeup, wifiWakeup,
4634 mobileBytesBgRx, mobileBytesBgTx, wifiBytesBgRx, wifiBytesBgTx,
4635 mobilePacketsBgRx, mobilePacketsBgTx, wifiPacketsBgRx, wifiPacketsBgTx
4636 );
4637 }
4638
4639 // Dump modem controller data, per UID.
4640 dumpControllerActivityLine(pw, uid, category, MODEM_CONTROLLER_DATA,
4641 u.getModemControllerActivity(), which);
4642
4643 // Dump Wifi controller data, per UID.
4644 final long fullWifiLockOnTime = u.getFullWifiLockTime(rawRealtime, which);
4645 final long wifiScanTime = u.getWifiScanTime(rawRealtime, which);
4646 final int wifiScanCount = u.getWifiScanCount(which);
4647 final int wifiScanCountBg = u.getWifiScanBackgroundCount(which);
4648 // Note that 'ActualTime' are unpooled and always since reset (regardless of 'which')
4649 final long wifiScanActualTimeMs = (u.getWifiScanActualTime(rawRealtime) + 500) / 1000;
4650 final long wifiScanActualTimeMsBg = (u.getWifiScanBackgroundTime(rawRealtime) + 500)
4651 / 1000;
4652 final long uidWifiRunningTime = u.getWifiRunningTime(rawRealtime, which);
4653 if (fullWifiLockOnTime != 0 || wifiScanTime != 0 || wifiScanCount != 0
4654 || wifiScanCountBg != 0 || wifiScanActualTimeMs != 0
4655 || wifiScanActualTimeMsBg != 0 || uidWifiRunningTime != 0) {
4656 dumpLine(pw, uid, category, WIFI_DATA, fullWifiLockOnTime, wifiScanTime,
4657 uidWifiRunningTime, wifiScanCount,
4658 /* legacy fields follow, keep at 0 */ 0, 0, 0,
4659 wifiScanCountBg, wifiScanActualTimeMs, wifiScanActualTimeMsBg);
4660 }
4661
4662 dumpControllerActivityLine(pw, uid, category, WIFI_CONTROLLER_DATA,
4663 u.getWifiControllerActivity(), which);
4664
4665 final Timer bleTimer = u.getBluetoothScanTimer();
4666 if (bleTimer != null) {
4667 // Convert from microseconds to milliseconds with rounding
4668 final long totalTime = (bleTimer.getTotalTimeLocked(rawRealtime, which) + 500)
4669 / 1000;
4670 if (totalTime != 0) {
4671 final int count = bleTimer.getCountLocked(which);
4672 final Timer bleTimerBg = u.getBluetoothScanBackgroundTimer();
4673 final int countBg = bleTimerBg != null ? bleTimerBg.getCountLocked(which) : 0;
4674 // 'actualTime' are unpooled and always since reset (regardless of 'which')
4675 final long actualTime = bleTimer.getTotalDurationMsLocked(rawRealtimeMs);
4676 final long actualTimeBg = bleTimerBg != null ?
4677 bleTimerBg.getTotalDurationMsLocked(rawRealtimeMs) : 0;
4678 // Result counters
4679 final int resultCount = u.getBluetoothScanResultCounter() != null ?
4680 u.getBluetoothScanResultCounter().getCountLocked(which) : 0;
4681 final int resultCountBg = u.getBluetoothScanResultBgCounter() != null ?
4682 u.getBluetoothScanResultBgCounter().getCountLocked(which) : 0;
4683 // Unoptimized scan timer. Unpooled and since reset (regardless of 'which').
4684 final Timer unoptimizedScanTimer = u.getBluetoothUnoptimizedScanTimer();
4685 final long unoptimizedScanTotalTime = unoptimizedScanTimer != null ?
4686 unoptimizedScanTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
4687 final long unoptimizedScanMaxTime = unoptimizedScanTimer != null ?
4688 unoptimizedScanTimer.getMaxDurationMsLocked(rawRealtimeMs) : 0;
4689 // Unoptimized bg scan timer. Unpooled and since reset (regardless of 'which').
4690 final Timer unoptimizedScanTimerBg =
4691 u.getBluetoothUnoptimizedScanBackgroundTimer();
4692 final long unoptimizedScanTotalTimeBg = unoptimizedScanTimerBg != null ?
4693 unoptimizedScanTimerBg.getTotalDurationMsLocked(rawRealtimeMs) : 0;
4694 final long unoptimizedScanMaxTimeBg = unoptimizedScanTimerBg != null ?
4695 unoptimizedScanTimerBg.getMaxDurationMsLocked(rawRealtimeMs) : 0;
4696
4697 dumpLine(pw, uid, category, BLUETOOTH_MISC_DATA, totalTime, count,
4698 countBg, actualTime, actualTimeBg, resultCount, resultCountBg,
4699 unoptimizedScanTotalTime, unoptimizedScanTotalTimeBg,
4700 unoptimizedScanMaxTime, unoptimizedScanMaxTimeBg);
4701 }
4702 }
4703
4704 dumpControllerActivityLine(pw, uid, category, BLUETOOTH_CONTROLLER_DATA,
4705 u.getBluetoothControllerActivity(), which);
4706
4707 if (u.hasUserActivity()) {
4708 args = new Object[Uid.NUM_USER_ACTIVITY_TYPES];
4709 boolean hasData = false;
4710 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
4711 int val = u.getUserActivityCount(i, which);
4712 args[i] = val;
4713 if (val != 0) hasData = true;
4714 }
4715 if (hasData) {
4716 dumpLine(pw, uid /* uid */, category, USER_ACTIVITY_DATA, args);
4717 }
4718 }
4719
4720 if (u.getAggregatedPartialWakelockTimer() != null) {
4721 final Timer timer = u.getAggregatedPartialWakelockTimer();
4722 // Times are since reset (regardless of 'which')
4723 final long totTimeMs = timer.getTotalDurationMsLocked(rawRealtimeMs);
4724 final Timer bgTimer = timer.getSubTimer();
4725 final long bgTimeMs = bgTimer != null ?
4726 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
4727 dumpLine(pw, uid, category, AGGREGATED_WAKELOCK_DATA, totTimeMs, bgTimeMs);
4728 }
4729
4730 final ArrayMap<String, ? extends Uid.Wakelock> wakelocks = u.getWakelockStats();
4731 for (int iw=wakelocks.size()-1; iw>=0; iw--) {
4732 final Uid.Wakelock wl = wakelocks.valueAt(iw);
4733 String linePrefix = "";
4734 sb.setLength(0);
4735 linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL),
4736 rawRealtime, "f", which, linePrefix);
4737 final Timer pTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
4738 linePrefix = printWakeLockCheckin(sb, pTimer,
4739 rawRealtime, "p", which, linePrefix);
4740 linePrefix = printWakeLockCheckin(sb, pTimer != null ? pTimer.getSubTimer() : null,
4741 rawRealtime, "bp", which, linePrefix);
4742 linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW),
4743 rawRealtime, "w", which, linePrefix);
4744
4745 // Only log if we had at least one wakelock...
4746 if (sb.length() > 0) {
4747 String name = wakelocks.keyAt(iw);
4748 if (name.indexOf(',') >= 0) {
4749 name = name.replace(',', '_');
4750 }
4751 if (name.indexOf('\n') >= 0) {
4752 name = name.replace('\n', '_');
4753 }
4754 if (name.indexOf('\r') >= 0) {
4755 name = name.replace('\r', '_');
4756 }
4757 dumpLine(pw, uid, category, WAKELOCK_DATA, name, sb.toString());
4758 }
4759 }
4760
4761 // WiFi Multicast Wakelock Statistics
4762 final Timer mcTimer = u.getMulticastWakelockStats();
4763 if (mcTimer != null) {
4764 final long totalMcWakelockTimeMs =
4765 mcTimer.getTotalTimeLocked(rawRealtime, which) / 1000 ;
4766 final int countMcWakelock = mcTimer.getCountLocked(which);
4767 if(totalMcWakelockTimeMs > 0) {
4768 dumpLine(pw, uid, category, WIFI_MULTICAST_DATA,
4769 totalMcWakelockTimeMs, countMcWakelock);
4770 }
4771 }
4772
4773 final ArrayMap<String, ? extends Timer> syncs = u.getSyncStats();
4774 for (int isy=syncs.size()-1; isy>=0; isy--) {
4775 final Timer timer = syncs.valueAt(isy);
4776 // Convert from microseconds to milliseconds with rounding
4777 final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000;
4778 final int count = timer.getCountLocked(which);
4779 final Timer bgTimer = timer.getSubTimer();
4780 final long bgTime = bgTimer != null ?
4781 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : -1;
4782 final int bgCount = bgTimer != null ? bgTimer.getCountLocked(which) : -1;
4783 if (totalTime != 0) {
4784 dumpLine(pw, uid, category, SYNC_DATA, "\"" + syncs.keyAt(isy) + "\"",
4785 totalTime, count, bgTime, bgCount);
4786 }
4787 }
4788
4789 final ArrayMap<String, ? extends Timer> jobs = u.getJobStats();
4790 for (int ij=jobs.size()-1; ij>=0; ij--) {
4791 final Timer timer = jobs.valueAt(ij);
4792 // Convert from microseconds to milliseconds with rounding
4793 final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000;
4794 final int count = timer.getCountLocked(which);
4795 final Timer bgTimer = timer.getSubTimer();
4796 final long bgTime = bgTimer != null ?
4797 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : -1;
4798 final int bgCount = bgTimer != null ? bgTimer.getCountLocked(which) : -1;
4799 if (totalTime != 0) {
4800 dumpLine(pw, uid, category, JOB_DATA, "\"" + jobs.keyAt(ij) + "\"",
4801 totalTime, count, bgTime, bgCount);
4802 }
4803 }
4804
4805 final int[] jobStopReasonCodes = JobParameters.getJobStopReasonCodes();
4806 final Object[] jobCompletionArgs = new Object[jobStopReasonCodes.length + 1];
4807
4808 final ArrayMap<String, SparseIntArray> completions = u.getJobCompletionStats();
4809 for (int ic=completions.size()-1; ic>=0; ic--) {
4810 SparseIntArray types = completions.valueAt(ic);
4811 if (types != null) {
4812 jobCompletionArgs[0] = "\"" + completions.keyAt(ic) + "\"";
4813 for (int i = 0; i < jobStopReasonCodes.length; i++) {
4814 jobCompletionArgs[i + 1] = types.get(jobStopReasonCodes[i], 0);
4815 }
4816
4817 dumpLine(pw, uid, category, JOB_COMPLETION_DATA, jobCompletionArgs);
4818 }
4819 }
4820
4821 // Dump deferred jobs stats
4822 u.getDeferredJobsCheckinLineLocked(sb, which);
4823 if (sb.length() > 0) {
4824 dumpLine(pw, uid, category, JOBS_DEFERRED_DATA, sb.toString());
4825 }
4826
4827 dumpTimer(pw, uid, category, FLASHLIGHT_DATA, u.getFlashlightTurnedOnTimer(),
4828 rawRealtime, which);
4829 dumpTimer(pw, uid, category, CAMERA_DATA, u.getCameraTurnedOnTimer(),
4830 rawRealtime, which);
4831 dumpTimer(pw, uid, category, VIDEO_DATA, u.getVideoTurnedOnTimer(),
4832 rawRealtime, which);
4833 dumpTimer(pw, uid, category, AUDIO_DATA, u.getAudioTurnedOnTimer(),
4834 rawRealtime, which);
4835
4836 final SparseArray<? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
4837 final int NSE = sensors.size();
4838 for (int ise=0; ise<NSE; ise++) {
4839 final Uid.Sensor se = sensors.valueAt(ise);
4840 final int sensorNumber = sensors.keyAt(ise);
4841 final Timer timer = se.getSensorTime();
4842 if (timer != null) {
4843 // Convert from microseconds to milliseconds with rounding
4844 final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500)
4845 / 1000;
4846 if (totalTime != 0) {
4847 final int count = timer.getCountLocked(which);
4848 final Timer bgTimer = se.getSensorBackgroundTime();
4849 final int bgCount = bgTimer != null ? bgTimer.getCountLocked(which) : 0;
4850 // 'actualTime' are unpooled and always since reset (regardless of 'which')
4851 final long actualTime = timer.getTotalDurationMsLocked(rawRealtimeMs);
4852 final long bgActualTime = bgTimer != null ?
4853 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
4854 dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime,
4855 count, bgCount, actualTime, bgActualTime);
4856 }
4857 }
4858 }
4859
4860 dumpTimer(pw, uid, category, VIBRATOR_DATA, u.getVibratorOnTimer(),
4861 rawRealtime, which);
4862
4863 dumpTimer(pw, uid, category, FOREGROUND_ACTIVITY_DATA, u.getForegroundActivityTimer(),
4864 rawRealtime, which);
4865
4866 dumpTimer(pw, uid, category, FOREGROUND_SERVICE_DATA, u.getForegroundServiceTimer(),
4867 rawRealtime, which);
4868
4869 final Object[] stateTimes = new Object[Uid.NUM_PROCESS_STATE];
4870 long totalStateTime = 0;
4871 for (int ips=0; ips<Uid.NUM_PROCESS_STATE; ips++) {
4872 final long time = u.getProcessStateTime(ips, rawRealtime, which);
4873 totalStateTime += time;
4874 stateTimes[ips] = (time + 500) / 1000;
4875 }
4876 if (totalStateTime > 0) {
4877 dumpLine(pw, uid, category, STATE_TIME_DATA, stateTimes);
4878 }
4879
4880 final long userCpuTimeUs = u.getUserCpuTimeUs(which);
4881 final long systemCpuTimeUs = u.getSystemCpuTimeUs(which);
4882 if (userCpuTimeUs > 0 || systemCpuTimeUs > 0) {
4883 dumpLine(pw, uid, category, CPU_DATA, userCpuTimeUs / 1000, systemCpuTimeUs / 1000,
4884 0 /* old cpu power, keep for compatibility */);
4885 }
4886
4887 // If the cpuFreqs is null, then don't bother checking for cpu freq times.
4888 if (cpuFreqs != null) {
4889 final long[] cpuFreqTimeMs = u.getCpuFreqTimes(which);
4890 // If total cpuFreqTimes is null, then we don't need to check for
4891 // screenOffCpuFreqTimes.
4892 if (cpuFreqTimeMs != null && cpuFreqTimeMs.length == cpuFreqs.length) {
4893 sb.setLength(0);
4894 for (int i = 0; i < cpuFreqTimeMs.length; ++i) {
4895 if (i != 0) sb.append(',');
4896 sb.append(cpuFreqTimeMs[i]);
4897 }
4898 final long[] screenOffCpuFreqTimeMs = u.getScreenOffCpuFreqTimes(which);
4899 if (screenOffCpuFreqTimeMs != null) {
4900 for (int i = 0; i < screenOffCpuFreqTimeMs.length; ++i) {
4901 sb.append(',').append(screenOffCpuFreqTimeMs[i]);
4902 }
4903 } else {
4904 for (int i = 0; i < cpuFreqTimeMs.length; ++i) {
4905 sb.append(",0");
4906 }
4907 }
4908 dumpLine(pw, uid, category, CPU_TIMES_AT_FREQ_DATA, UID_TIMES_TYPE_ALL,
4909 cpuFreqTimeMs.length, sb.toString());
4910 }
4911
4912 final long[] timesInFreqMs = new long[getCpuFreqCount()];
4913 for (int procState = 0; procState < Uid.NUM_PROCESS_STATE; ++procState) {
4914 if (u.getCpuFreqTimes(timesInFreqMs, procState)) {
4915 sb.setLength(0);
4916 for (int i = 0; i < timesInFreqMs.length; ++i) {
4917 if (i != 0) sb.append(',');
4918 sb.append(timesInFreqMs[i]);
4919 }
4920 if (u.getScreenOffCpuFreqTimes(timesInFreqMs, procState)) {
4921 for (int i = 0; i < timesInFreqMs.length; ++i) {
4922 sb.append(',').append(timesInFreqMs[i]);
4923 }
4924 } else {
4925 for (int i = 0; i < timesInFreqMs.length; ++i) {
4926 sb.append(",0");
4927 }
4928 }
4929 dumpLine(pw, uid, category, CPU_TIMES_AT_FREQ_DATA,
4930 Uid.UID_PROCESS_TYPES[procState], timesInFreqMs.length,
4931 sb.toString());
4932 }
4933 }
4934 }
4935
4936 final ArrayMap<String, ? extends BatteryStats.Uid.Proc> processStats
4937 = u.getProcessStats();
4938 for (int ipr=processStats.size()-1; ipr>=0; ipr--) {
4939 final Uid.Proc ps = processStats.valueAt(ipr);
4940
4941 final long userMillis = ps.getUserTime(which);
4942 final long systemMillis = ps.getSystemTime(which);
4943 final long foregroundMillis = ps.getForegroundTime(which);
4944 final int starts = ps.getStarts(which);
4945 final int numCrashes = ps.getNumCrashes(which);
4946 final int numAnrs = ps.getNumAnrs(which);
4947
4948 if (userMillis != 0 || systemMillis != 0 || foregroundMillis != 0
4949 || starts != 0 || numAnrs != 0 || numCrashes != 0) {
4950 dumpLine(pw, uid, category, PROCESS_DATA, "\"" + processStats.keyAt(ipr) + "\"",
4951 userMillis, systemMillis, foregroundMillis, starts, numAnrs, numCrashes);
4952 }
4953 }
4954
4955 final ArrayMap<String, ? extends BatteryStats.Uid.Pkg> packageStats
4956 = u.getPackageStats();
4957 for (int ipkg=packageStats.size()-1; ipkg>=0; ipkg--) {
4958 final Uid.Pkg ps = packageStats.valueAt(ipkg);
4959 int wakeups = 0;
4960 final ArrayMap<String, ? extends Counter> alarms = ps.getWakeupAlarmStats();
4961 for (int iwa=alarms.size()-1; iwa>=0; iwa--) {
4962 int count = alarms.valueAt(iwa).getCountLocked(which);
4963 wakeups += count;
4964 String name = alarms.keyAt(iwa).replace(',', '_');
4965 dumpLine(pw, uid, category, WAKEUP_ALARM_DATA, name, count);
4966 }
4967 final ArrayMap<String, ? extends Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
4968 for (int isvc=serviceStats.size()-1; isvc>=0; isvc--) {
4969 final BatteryStats.Uid.Pkg.Serv ss = serviceStats.valueAt(isvc);
4970 final long startTime = ss.getStartTime(batteryUptime, which);
4971 final int starts = ss.getStarts(which);
4972 final int launches = ss.getLaunches(which);
4973 if (startTime != 0 || starts != 0 || launches != 0) {
4974 dumpLine(pw, uid, category, APK_DATA,
4975 wakeups, // wakeup alarms
4976 packageStats.keyAt(ipkg), // Apk
4977 serviceStats.keyAt(isvc), // service
4978 startTime / 1000, // time spent started, in ms
4979 starts,
4980 launches);
4981 }
4982 }
4983 }
4984 }
4985 }
4986
4987 static final class TimerEntry {
4988 final String mName;
4989 final int mId;
4990 final BatteryStats.Timer mTimer;
4991 final long mTime;
4992 TimerEntry(String name, int id, BatteryStats.Timer timer, long time) {
4993 mName = name;
4994 mId = id;
4995 mTimer = timer;
4996 mTime = time;
4997 }
4998 }
4999
5000 private void printmAh(PrintWriter printer, double power) {
5001 printer.print(formatCharge(power));
5002 }
5003
5004 private void printmAh(StringBuilder sb, double power) {
5005 sb.append(formatCharge(power));
5006 }
5007
5008 /**
5009 * Temporary for settings.
5010 */
5011 public final void dumpLocked(Context context, PrintWriter pw, String prefix, int which,
5012 int reqUid) {
5013 dumpLocked(context, pw, prefix, which, reqUid, checkWifiOnly(context));
5014 }
5015
5016 @SuppressWarnings("unused")
5017 public final void dumpLocked(Context context, PrintWriter pw, String prefix, final int which,
5018 int reqUid, boolean wifiOnly) {
5019
5020 if (which != BatteryStats.STATS_SINCE_CHARGED) {
5021 pw.println("ERROR: BatteryStats.dump called for which type " + which
5022 + " but only STATS_SINCE_CHARGED is supported");
5023 return;
5024 }
5025
5026 final long rawUptime = SystemClock.uptimeMillis() * 1000;
5027 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
5028 final long rawRealtimeMs = (rawRealtime + 500) / 1000;
5029 final long batteryUptime = getBatteryUptime(rawUptime);
5030
5031 final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
5032 final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
5033 final long totalRealtime = computeRealtime(rawRealtime, which);
5034 final long totalUptime = computeUptime(rawUptime, which);
5035 final long whichBatteryScreenOffUptime = computeBatteryScreenOffUptime(rawUptime, which);
5036 final long whichBatteryScreenOffRealtime = computeBatteryScreenOffRealtime(rawRealtime,
5037 which);
5038 final long batteryTimeRemaining = computeBatteryTimeRemaining(rawRealtime);
5039 final long chargeTimeRemaining = computeChargeTimeRemaining(rawRealtime);
5040 final long screenDozeTime = getScreenDozeTime(rawRealtime, which);
5041
5042 final StringBuilder sb = new StringBuilder(128);
5043
5044 final SparseArray<? extends Uid> uidStats = getUidStats();
5045 final int NU = uidStats.size();
5046
5047 final int estimatedBatteryCapacity = getEstimatedBatteryCapacity();
5048 if (estimatedBatteryCapacity > 0) {
5049 sb.setLength(0);
5050 sb.append(prefix);
5051 sb.append(" Estimated battery capacity: ");
5052 sb.append(formatCharge(estimatedBatteryCapacity));
5053 sb.append(" mAh");
5054 pw.println(sb.toString());
5055 }
5056
5057 final int lastLearnedBatteryCapacity = getLearnedBatteryCapacity();
5058 if (lastLearnedBatteryCapacity > 0) {
5059 sb.setLength(0);
5060 sb.append(prefix);
5061 sb.append(" Last learned battery capacity: ");
5062 sb.append(formatCharge(lastLearnedBatteryCapacity / 1000));
5063 sb.append(" mAh");
5064 pw.println(sb.toString());
5065 }
5066 final int minLearnedBatteryCapacity = getMinLearnedBatteryCapacity();
5067 if (minLearnedBatteryCapacity > 0) {
5068 sb.setLength(0);
5069 sb.append(prefix);
5070 sb.append(" Min learned battery capacity: ");
5071 sb.append(formatCharge(minLearnedBatteryCapacity / 1000));
5072 sb.append(" mAh");
5073 pw.println(sb.toString());
5074 }
5075 final int maxLearnedBatteryCapacity = getMaxLearnedBatteryCapacity();
5076 if (maxLearnedBatteryCapacity > 0) {
5077 sb.setLength(0);
5078 sb.append(prefix);
5079 sb.append(" Max learned battery capacity: ");
5080 sb.append(formatCharge(maxLearnedBatteryCapacity / 1000));
5081 sb.append(" mAh");
5082 pw.println(sb.toString());
5083 }
5084
5085 sb.setLength(0);
5086 sb.append(prefix);
5087 sb.append(" Time on battery: ");
5088 formatTimeMs(sb, whichBatteryRealtime / 1000); sb.append("(");
5089 sb.append(formatRatioLocked(whichBatteryRealtime, totalRealtime));
5090 sb.append(") realtime, ");
5091 formatTimeMs(sb, whichBatteryUptime / 1000);
5092 sb.append("("); sb.append(formatRatioLocked(whichBatteryUptime, whichBatteryRealtime));
5093 sb.append(") uptime");
5094 pw.println(sb.toString());
5095
5096 sb.setLength(0);
5097 sb.append(prefix);
5098 sb.append(" Time on battery screen off: ");
5099 formatTimeMs(sb, whichBatteryScreenOffRealtime / 1000); sb.append("(");
5100 sb.append(formatRatioLocked(whichBatteryScreenOffRealtime, whichBatteryRealtime));
5101 sb.append(") realtime, ");
5102 formatTimeMs(sb, whichBatteryScreenOffUptime / 1000);
5103 sb.append("(");
5104 sb.append(formatRatioLocked(whichBatteryScreenOffUptime, whichBatteryRealtime));
5105 sb.append(") uptime");
5106 pw.println(sb.toString());
5107
5108 sb.setLength(0);
5109 sb.append(prefix);
5110 sb.append(" Time on battery screen doze: ");
5111 formatTimeMs(sb, screenDozeTime / 1000); sb.append("(");
5112 sb.append(formatRatioLocked(screenDozeTime, whichBatteryRealtime));
5113 sb.append(")");
5114 pw.println(sb.toString());
5115
5116 sb.setLength(0);
5117 sb.append(prefix);
5118 sb.append(" Total run time: ");
5119 formatTimeMs(sb, totalRealtime / 1000);
5120 sb.append("realtime, ");
5121 formatTimeMs(sb, totalUptime / 1000);
5122 sb.append("uptime");
5123 pw.println(sb.toString());
5124 if (batteryTimeRemaining >= 0) {
5125 sb.setLength(0);
5126 sb.append(prefix);
5127 sb.append(" Battery time remaining: ");
5128 formatTimeMs(sb, batteryTimeRemaining / 1000);
5129 pw.println(sb.toString());
5130 }
5131 if (chargeTimeRemaining >= 0) {
5132 sb.setLength(0);
5133 sb.append(prefix);
5134 sb.append(" Charge time remaining: ");
5135 formatTimeMs(sb, chargeTimeRemaining / 1000);
5136 pw.println(sb.toString());
5137 }
5138
5139 final long dischargeCount = getUahDischarge(which);
5140 if (dischargeCount >= 0) {
5141 sb.setLength(0);
5142 sb.append(prefix);
5143 sb.append(" Discharge: ");
5144 sb.append(formatCharge(dischargeCount / 1000.0));
5145 sb.append(" mAh");
5146 pw.println(sb.toString());
5147 }
5148
5149 final long dischargeScreenOffCount = getUahDischargeScreenOff(which);
5150 if (dischargeScreenOffCount >= 0) {
5151 sb.setLength(0);
5152 sb.append(prefix);
5153 sb.append(" Screen off discharge: ");
5154 sb.append(formatCharge(dischargeScreenOffCount / 1000.0));
5155 sb.append(" mAh");
5156 pw.println(sb.toString());
5157 }
5158
5159 final long dischargeScreenDozeCount = getUahDischargeScreenDoze(which);
5160 if (dischargeScreenDozeCount >= 0) {
5161 sb.setLength(0);
5162 sb.append(prefix);
5163 sb.append(" Screen doze discharge: ");
5164 sb.append(formatCharge(dischargeScreenDozeCount / 1000.0));
5165 sb.append(" mAh");
5166 pw.println(sb.toString());
5167 }
5168
5169 final long dischargeScreenOnCount = dischargeCount - dischargeScreenOffCount;
5170 if (dischargeScreenOnCount >= 0) {
5171 sb.setLength(0);
5172 sb.append(prefix);
5173 sb.append(" Screen on discharge: ");
5174 sb.append(formatCharge(dischargeScreenOnCount / 1000.0));
5175 sb.append(" mAh");
5176 pw.println(sb.toString());
5177 }
5178
5179 final long dischargeLightDozeCount = getUahDischargeLightDoze(which);
5180 if (dischargeLightDozeCount >= 0) {
5181 sb.setLength(0);
5182 sb.append(prefix);
5183 sb.append(" Device light doze discharge: ");
5184 sb.append(formatCharge(dischargeLightDozeCount / 1000.0));
5185 sb.append(" mAh");
5186 pw.println(sb.toString());
5187 }
5188
5189 final long dischargeDeepDozeCount = getUahDischargeDeepDoze(which);
5190 if (dischargeDeepDozeCount >= 0) {
5191 sb.setLength(0);
5192 sb.append(prefix);
5193 sb.append(" Device deep doze discharge: ");
5194 sb.append(formatCharge(dischargeDeepDozeCount / 1000.0));
5195 sb.append(" mAh");
5196 pw.println(sb.toString());
5197 }
5198
5199 pw.print(" Start clock time: ");
5200 pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss", getStartClockTime()).toString());
5201
5202 final long screenOnTime = getScreenOnTime(rawRealtime, which);
5203 final long interactiveTime = getInteractiveTime(rawRealtime, which);
5204 final long powerSaveModeEnabledTime = getPowerSaveModeEnabledTime(rawRealtime, which);
5205 final long deviceIdleModeLightTime = getDeviceIdleModeTime(DEVICE_IDLE_MODE_LIGHT,
5206 rawRealtime, which);
5207 final long deviceIdleModeFullTime = getDeviceIdleModeTime(DEVICE_IDLE_MODE_DEEP,
5208 rawRealtime, which);
5209 final long deviceLightIdlingTime = getDeviceIdlingTime(DEVICE_IDLE_MODE_LIGHT,
5210 rawRealtime, which);
5211 final long deviceIdlingTime = getDeviceIdlingTime(DEVICE_IDLE_MODE_DEEP,
5212 rawRealtime, which);
5213 final long phoneOnTime = getPhoneOnTime(rawRealtime, which);
5214 final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which);
5215 final long wifiOnTime = getWifiOnTime(rawRealtime, which);
5216 sb.setLength(0);
5217 sb.append(prefix);
5218 sb.append(" Screen on: "); formatTimeMs(sb, screenOnTime / 1000);
5219 sb.append("("); sb.append(formatRatioLocked(screenOnTime, whichBatteryRealtime));
5220 sb.append(") "); sb.append(getScreenOnCount(which));
5221 sb.append("x, Interactive: "); formatTimeMs(sb, interactiveTime / 1000);
5222 sb.append("("); sb.append(formatRatioLocked(interactiveTime, whichBatteryRealtime));
5223 sb.append(")");
5224 pw.println(sb.toString());
5225 sb.setLength(0);
5226 sb.append(prefix);
5227 sb.append(" Screen brightnesses:");
5228 boolean didOne = false;
5229 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
5230 final long time = getScreenBrightnessTime(i, rawRealtime, which);
5231 if (time == 0) {
5232 continue;
5233 }
5234 sb.append("\n ");
5235 sb.append(prefix);
5236 didOne = true;
5237 sb.append(SCREEN_BRIGHTNESS_NAMES[i]);
5238 sb.append(" ");
5239 formatTimeMs(sb, time/1000);
5240 sb.append("(");
5241 sb.append(formatRatioLocked(time, screenOnTime));
5242 sb.append(")");
5243 }
5244 if (!didOne) sb.append(" (no activity)");
5245 pw.println(sb.toString());
5246 if (powerSaveModeEnabledTime != 0) {
5247 sb.setLength(0);
5248 sb.append(prefix);
5249 sb.append(" Power save mode enabled: ");
5250 formatTimeMs(sb, powerSaveModeEnabledTime / 1000);
5251 sb.append("(");
5252 sb.append(formatRatioLocked(powerSaveModeEnabledTime, whichBatteryRealtime));
5253 sb.append(")");
5254 pw.println(sb.toString());
5255 }
5256 if (deviceLightIdlingTime != 0) {
5257 sb.setLength(0);
5258 sb.append(prefix);
5259 sb.append(" Device light idling: ");
5260 formatTimeMs(sb, deviceLightIdlingTime / 1000);
5261 sb.append("(");
5262 sb.append(formatRatioLocked(deviceLightIdlingTime, whichBatteryRealtime));
5263 sb.append(") "); sb.append(getDeviceIdlingCount(DEVICE_IDLE_MODE_LIGHT, which));
5264 sb.append("x");
5265 pw.println(sb.toString());
5266 }
5267 if (deviceIdleModeLightTime != 0) {
5268 sb.setLength(0);
5269 sb.append(prefix);
5270 sb.append(" Idle mode light time: ");
5271 formatTimeMs(sb, deviceIdleModeLightTime / 1000);
5272 sb.append("(");
5273 sb.append(formatRatioLocked(deviceIdleModeLightTime, whichBatteryRealtime));
5274 sb.append(") ");
5275 sb.append(getDeviceIdleModeCount(DEVICE_IDLE_MODE_LIGHT, which));
5276 sb.append("x");
5277 sb.append(" -- longest ");
5278 formatTimeMs(sb, getLongestDeviceIdleModeTime(DEVICE_IDLE_MODE_LIGHT));
5279 pw.println(sb.toString());
5280 }
5281 if (deviceIdlingTime != 0) {
5282 sb.setLength(0);
5283 sb.append(prefix);
5284 sb.append(" Device full idling: ");
5285 formatTimeMs(sb, deviceIdlingTime / 1000);
5286 sb.append("(");
5287 sb.append(formatRatioLocked(deviceIdlingTime, whichBatteryRealtime));
5288 sb.append(") "); sb.append(getDeviceIdlingCount(DEVICE_IDLE_MODE_DEEP, which));
5289 sb.append("x");
5290 pw.println(sb.toString());
5291 }
5292 if (deviceIdleModeFullTime != 0) {
5293 sb.setLength(0);
5294 sb.append(prefix);
5295 sb.append(" Idle mode full time: ");
5296 formatTimeMs(sb, deviceIdleModeFullTime / 1000);
5297 sb.append("(");
5298 sb.append(formatRatioLocked(deviceIdleModeFullTime, whichBatteryRealtime));
5299 sb.append(") ");
5300 sb.append(getDeviceIdleModeCount(DEVICE_IDLE_MODE_DEEP, which));
5301 sb.append("x");
5302 sb.append(" -- longest ");
5303 formatTimeMs(sb, getLongestDeviceIdleModeTime(DEVICE_IDLE_MODE_DEEP));
5304 pw.println(sb.toString());
5305 }
5306 if (phoneOnTime != 0) {
5307 sb.setLength(0);
5308 sb.append(prefix);
5309 sb.append(" Active phone call: "); formatTimeMs(sb, phoneOnTime / 1000);
5310 sb.append("("); sb.append(formatRatioLocked(phoneOnTime, whichBatteryRealtime));
5311 sb.append(") "); sb.append(getPhoneOnCount(which)); sb.append("x");
5312 }
5313 final int connChanges = getNumConnectivityChange(which);
5314 if (connChanges != 0) {
5315 pw.print(prefix);
5316 pw.print(" Connectivity changes: "); pw.println(connChanges);
5317 }
5318
5319 // Calculate wakelock times across all uids.
5320 long fullWakeLockTimeTotalMicros = 0;
5321 long partialWakeLockTimeTotalMicros = 0;
5322
5323 final ArrayList<TimerEntry> timers = new ArrayList<>();
5324
5325 for (int iu = 0; iu < NU; iu++) {
5326 final Uid u = uidStats.valueAt(iu);
5327
5328 final ArrayMap<String, ? extends Uid.Wakelock> wakelocks
5329 = u.getWakelockStats();
5330 for (int iw=wakelocks.size()-1; iw>=0; iw--) {
5331 final Uid.Wakelock wl = wakelocks.valueAt(iw);
5332
5333 final Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
5334 if (fullWakeTimer != null) {
5335 fullWakeLockTimeTotalMicros += fullWakeTimer.getTotalTimeLocked(
5336 rawRealtime, which);
5337 }
5338
5339 final Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
5340 if (partialWakeTimer != null) {
5341 final long totalTimeMicros = partialWakeTimer.getTotalTimeLocked(
5342 rawRealtime, which);
5343 if (totalTimeMicros > 0) {
5344 if (reqUid < 0) {
5345 // Only show the ordered list of all wake
5346 // locks if the caller is not asking for data
5347 // about a specific uid.
5348 timers.add(new TimerEntry(wakelocks.keyAt(iw), u.getUid(),
5349 partialWakeTimer, totalTimeMicros));
5350 }
5351 partialWakeLockTimeTotalMicros += totalTimeMicros;
5352 }
5353 }
5354 }
5355 }
5356
5357 final long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
5358 final long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
5359 final long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
5360 final long wifiTxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
5361 final long mobileRxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
5362 final long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
5363 final long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
5364 final long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
5365 final long btRxTotalBytes = getNetworkActivityBytes(NETWORK_BT_RX_DATA, which);
5366 final long btTxTotalBytes = getNetworkActivityBytes(NETWORK_BT_TX_DATA, which);
5367
5368 if (fullWakeLockTimeTotalMicros != 0) {
5369 sb.setLength(0);
5370 sb.append(prefix);
5371 sb.append(" Total full wakelock time: "); formatTimeMsNoSpace(sb,
5372 (fullWakeLockTimeTotalMicros + 500) / 1000);
5373 pw.println(sb.toString());
5374 }
5375
5376 if (partialWakeLockTimeTotalMicros != 0) {
5377 sb.setLength(0);
5378 sb.append(prefix);
5379 sb.append(" Total partial wakelock time: "); formatTimeMsNoSpace(sb,
5380 (partialWakeLockTimeTotalMicros + 500) / 1000);
5381 pw.println(sb.toString());
5382 }
5383
5384 final long multicastWakeLockTimeTotalMicros =
5385 getWifiMulticastWakelockTime(rawRealtime, which);
5386 final int multicastWakeLockCountTotal = getWifiMulticastWakelockCount(which);
5387 if (multicastWakeLockTimeTotalMicros != 0) {
5388 sb.setLength(0);
5389 sb.append(prefix);
5390 sb.append(" Total WiFi Multicast wakelock Count: ");
5391 sb.append(multicastWakeLockCountTotal);
5392 pw.println(sb.toString());
5393
5394 sb.setLength(0);
5395 sb.append(prefix);
5396 sb.append(" Total WiFi Multicast wakelock time: ");
5397 formatTimeMsNoSpace(sb, (multicastWakeLockTimeTotalMicros + 500) / 1000);
5398 pw.println(sb.toString());
5399 }
5400
5401 final int numDisplays = getDisplayCount();
5402 if (numDisplays > 1) {
5403 pw.println("");
5404 pw.print(prefix);
5405 sb.setLength(0);
5406 sb.append(prefix);
5407 sb.append(" MULTI-DISPLAY POWER SUMMARY START");
5408 pw.println(sb.toString());
5409
5410 for (int display = 0; display < numDisplays; display++) {
5411 sb.setLength(0);
5412 sb.append(prefix);
5413 sb.append(" Display ");
5414 sb.append(display);
5415 sb.append(" Statistics:");
5416 pw.println(sb.toString());
5417
5418 final long displayScreenOnTime = getDisplayScreenOnTime(display, rawRealtime);
5419 sb.setLength(0);
5420 sb.append(prefix);
5421 sb.append(" Screen on: ");
5422 formatTimeMs(sb, displayScreenOnTime / 1000);
5423 sb.append("(");
5424 sb.append(formatRatioLocked(displayScreenOnTime, whichBatteryRealtime));
5425 sb.append(") ");
5426 pw.println(sb.toString());
5427
5428 sb.setLength(0);
5429 sb.append(" Screen brightness levels:");
5430 didOne = false;
5431 for (int bin = 0; bin < NUM_SCREEN_BRIGHTNESS_BINS; bin++) {
5432 final long timeUs = getDisplayScreenBrightnessTime(display, bin, rawRealtime);
5433 if (timeUs == 0) {
5434 continue;
5435 }
5436 didOne = true;
5437 sb.append("\n ");
5438 sb.append(prefix);
5439 sb.append(SCREEN_BRIGHTNESS_NAMES[bin]);
5440 sb.append(" ");
5441 formatTimeMs(sb, timeUs / 1000);
5442 sb.append("(");
5443 sb.append(formatRatioLocked(timeUs, displayScreenOnTime));
5444 sb.append(")");
5445 }
5446 if (!didOne) sb.append(" (no activity)");
5447 pw.println(sb.toString());
5448
5449 final long displayScreenDozeTimeUs = getDisplayScreenDozeTime(display, rawRealtime);
5450 sb.setLength(0);
5451 sb.append(prefix);
5452 sb.append(" Screen Doze: ");
5453 formatTimeMs(sb, displayScreenDozeTimeUs / 1000);
5454 sb.append("(");
5455 sb.append(formatRatioLocked(displayScreenDozeTimeUs, whichBatteryRealtime));
5456 sb.append(") ");
5457 pw.println(sb.toString());
5458 }
5459 pw.print(prefix);
5460 sb.setLength(0);
5461 sb.append(prefix);
5462 sb.append(" MULTI-DISPLAY POWER SUMMARY END");
5463 pw.println(sb.toString());
5464 }
5465
5466 pw.println("");
5467 pw.print(prefix);
5468 sb.setLength(0);
5469 sb.append(prefix);
5470 sb.append(" CONNECTIVITY POWER SUMMARY START");
5471 pw.println(sb.toString());
5472
5473 pw.print(prefix);
5474 sb.setLength(0);
5475 sb.append(prefix);
5476 sb.append(" Logging duration for connectivity statistics: ");
5477 formatTimeMs(sb, whichBatteryRealtime / 1000);
5478 pw.println(sb.toString());
5479
5480 sb.setLength(0);
5481 sb.append(prefix);
5482 sb.append(" Cellular Statistics:");
5483 pw.println(sb.toString());
5484
5485 pw.print(prefix);
5486 sb.setLength(0);
5487 sb.append(prefix);
5488 sb.append(" Cellular kernel active time: ");
5489 final long mobileActiveTime = getMobileRadioActiveTime(rawRealtime, which);
5490 formatTimeMs(sb, mobileActiveTime / 1000);
5491 sb.append("("); sb.append(formatRatioLocked(mobileActiveTime, whichBatteryRealtime));
5492 sb.append(")");
5493 pw.println(sb.toString());
5494
5495 printControllerActivity(pw, sb, prefix, CELLULAR_CONTROLLER_NAME,
5496 getModemControllerActivity(), which);
5497
5498 printCellularPerRatBreakdown(pw, sb, prefix + " ", rawRealtimeMs);
5499
5500 pw.print(" Cellular data received: "); pw.println(formatBytesLocked(mobileRxTotalBytes));
5501 pw.print(" Cellular data sent: "); pw.println(formatBytesLocked(mobileTxTotalBytes));
5502 pw.print(" Cellular packets received: "); pw.println(mobileRxTotalPackets);
5503 pw.print(" Cellular packets sent: "); pw.println(mobileTxTotalPackets);
5504
5505 sb.setLength(0);
5506 sb.append(prefix);
5507 sb.append(" Cellular Radio Access Technology:");
5508 didOne = false;
5509 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
5510 final long time = getPhoneDataConnectionTime(i, rawRealtime, which);
5511 if (time == 0) {
5512 continue;
5513 }
5514 sb.append("\n ");
5515 sb.append(prefix);
5516 didOne = true;
5517 sb.append(i < DATA_CONNECTION_NAMES.length ? DATA_CONNECTION_NAMES[i] : "ERROR");
5518 sb.append(" ");
5519 formatTimeMs(sb, time/1000);
5520 sb.append("(");
5521 sb.append(formatRatioLocked(time, whichBatteryRealtime));
5522 sb.append(") ");
5523 }
5524 if (!didOne) sb.append(" (no activity)");
5525 pw.println(sb.toString());
5526
5527 sb.setLength(0);
5528 sb.append(prefix);
5529 sb.append(" Cellular Rx signal strength (RSRP):");
5530 final String[] cellularRxSignalStrengthDescription = new String[]{
5531 "very poor (less than -128dBm): ",
5532 "poor (-128dBm to -118dBm): ",
5533 "moderate (-118dBm to -108dBm): ",
5534 "good (-108dBm to -98dBm): ",
5535 "great (greater than -98dBm): "};
5536 didOne = false;
5537 final int numCellularRxBins = Math.min(CellSignalStrength.getNumSignalStrengthLevels(),
5538 cellularRxSignalStrengthDescription.length);
5539 for (int i=0; i<numCellularRxBins; i++) {
5540 final long time = getPhoneSignalStrengthTime(i, rawRealtime, which);
5541 if (time == 0) {
5542 continue;
5543 }
5544 sb.append("\n ");
5545 sb.append(prefix);
5546 didOne = true;
5547 sb.append(cellularRxSignalStrengthDescription[i]);
5548 sb.append(" ");
5549 formatTimeMs(sb, time/1000);
5550 sb.append("(");
5551 sb.append(formatRatioLocked(time, whichBatteryRealtime));
5552 sb.append(") ");
5553 }
5554 if (!didOne) sb.append(" (no activity)");
5555 pw.println(sb.toString());
5556
5557 pw.print(prefix);
5558 sb.setLength(0);
5559 sb.append(prefix);
5560 sb.append(" Wifi Statistics:");
5561 pw.println(sb.toString());
5562
5563 pw.print(prefix);
5564 sb.setLength(0);
5565 sb.append(prefix);
5566 sb.append(" Wifi kernel active time: ");
5567 final long wifiActiveTime = getWifiActiveTime(rawRealtime, which);
5568 formatTimeMs(sb, wifiActiveTime / 1000);
5569 sb.append("("); sb.append(formatRatioLocked(wifiActiveTime, whichBatteryRealtime));
5570 sb.append(")");
5571 pw.println(sb.toString());
5572
5573 printControllerActivity(pw, sb, prefix, WIFI_CONTROLLER_NAME,
5574 getWifiControllerActivity(), which);
5575
5576 pw.print(" Wifi data received: "); pw.println(formatBytesLocked(wifiRxTotalBytes));
5577 pw.print(" Wifi data sent: "); pw.println(formatBytesLocked(wifiTxTotalBytes));
5578 pw.print(" Wifi packets received: "); pw.println(wifiRxTotalPackets);
5579 pw.print(" Wifi packets sent: "); pw.println(wifiTxTotalPackets);
5580
5581 sb.setLength(0);
5582 sb.append(prefix);
5583 sb.append(" Wifi states:");
5584 didOne = false;
5585 for (int i=0; i<NUM_WIFI_STATES; i++) {
5586 final long time = getWifiStateTime(i, rawRealtime, which);
5587 if (time == 0) {
5588 continue;
5589 }
5590 sb.append("\n ");
5591 didOne = true;
5592 sb.append(WIFI_STATE_NAMES[i]);
5593 sb.append(" ");
5594 formatTimeMs(sb, time/1000);
5595 sb.append("(");
5596 sb.append(formatRatioLocked(time, whichBatteryRealtime));
5597 sb.append(") ");
5598 }
5599 if (!didOne) sb.append(" (no activity)");
5600 pw.println(sb.toString());
5601
5602 sb.setLength(0);
5603 sb.append(prefix);
5604 sb.append(" Wifi supplicant states:");
5605 didOne = false;
5606 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
5607 final long time = getWifiSupplStateTime(i, rawRealtime, which);
5608 if (time == 0) {
5609 continue;
5610 }
5611 sb.append("\n ");
5612 didOne = true;
5613 sb.append(WIFI_SUPPL_STATE_NAMES[i]);
5614 sb.append(" ");
5615 formatTimeMs(sb, time/1000);
5616 sb.append("(");
5617 sb.append(formatRatioLocked(time, whichBatteryRealtime));
5618 sb.append(") ");
5619 }
5620 if (!didOne) sb.append(" (no activity)");
5621 pw.println(sb.toString());
5622
5623 sb.setLength(0);
5624 sb.append(prefix);
5625 sb.append(" Wifi Rx signal strength (RSSI):");
5626 final String[] wifiRxSignalStrengthDescription = new String[]{
5627 "very poor (less than -88.75dBm): ",
5628 "poor (-88.75 to -77.5dBm): ",
5629 "moderate (-77.5dBm to -66.25dBm): ",
5630 "good (-66.25dBm to -55dBm): ",
5631 "great (greater than -55dBm): "};
5632 didOne = false;
5633 final int numWifiRxBins = Math.min(NUM_WIFI_SIGNAL_STRENGTH_BINS,
5634 wifiRxSignalStrengthDescription.length);
5635 for (int i=0; i<numWifiRxBins; i++) {
5636 final long time = getWifiSignalStrengthTime(i, rawRealtime, which);
5637 if (time == 0) {
5638 continue;
5639 }
5640 sb.append("\n ");
5641 sb.append(prefix);
5642 didOne = true;
5643 sb.append(" ");
5644 sb.append(wifiRxSignalStrengthDescription[i]);
5645 formatTimeMs(sb, time/1000);
5646 sb.append("(");
5647 sb.append(formatRatioLocked(time, whichBatteryRealtime));
5648 sb.append(") ");
5649 }
5650 if (!didOne) sb.append(" (no activity)");
5651 pw.println(sb.toString());
5652
5653 pw.print(prefix);
5654 sb.setLength(0);
5655 sb.append(prefix);
5656 sb.append(" GPS Statistics:");
5657 pw.println(sb.toString());
5658
5659 sb.setLength(0);
5660 sb.append(prefix);
5661 sb.append(" GPS signal quality (Top 4 Average CN0):");
5662 final String[] gpsSignalQualityDescription = new String[]{
5663 "poor (less than 20 dBHz): ",
5664 "good (greater than 20 dBHz): "};
5665 final int numGpsSignalQualityBins = Math.min(
5666 GnssSignalQuality.NUM_GNSS_SIGNAL_QUALITY_LEVELS,
5667 gpsSignalQualityDescription.length);
5668 for (int i=0; i<numGpsSignalQualityBins; i++) {
5669 final long time = getGpsSignalQualityTime(i, rawRealtime, which);
5670 sb.append("\n ");
5671 sb.append(prefix);
5672 sb.append(" ");
5673 sb.append(gpsSignalQualityDescription[i]);
5674 formatTimeMs(sb, time/1000);
5675 sb.append("(");
5676 sb.append(formatRatioLocked(time, whichBatteryRealtime));
5677 sb.append(") ");
5678 }
5679 pw.println(sb.toString());
5680
5681 final long gpsBatteryDrainMaMs = getGpsBatteryDrainMaMs();
5682 if (gpsBatteryDrainMaMs > 0) {
5683 pw.print(prefix);
5684 sb.setLength(0);
5685 sb.append(prefix);
5686 sb.append(" GPS Battery Drain: ");
5687 sb.append(new DecimalFormat("#.##").format(
5688 ((double) gpsBatteryDrainMaMs) / (3600 * 1000)));
5689 sb.append("mAh");
5690 pw.println(sb.toString());
5691 }
5692
5693 pw.print(prefix);
5694 sb.setLength(0);
5695 sb.append(prefix);
5696 sb.append(" CONNECTIVITY POWER SUMMARY END");
5697 pw.println(sb.toString());
5698 pw.println("");
5699
5700 pw.print(prefix);
5701 pw.print(" Bluetooth total received: "); pw.print(formatBytesLocked(btRxTotalBytes));
5702 pw.print(", sent: "); pw.println(formatBytesLocked(btTxTotalBytes));
5703
5704 final long bluetoothScanTimeMs = getBluetoothScanTime(rawRealtime, which) / 1000;
5705 sb.setLength(0);
5706 sb.append(prefix);
5707 sb.append(" Bluetooth scan time: "); formatTimeMs(sb, bluetoothScanTimeMs);
5708 pw.println(sb.toString());
5709
5710 printControllerActivity(pw, sb, prefix, "Bluetooth", getBluetoothControllerActivity(),
5711 which);
5712
5713 pw.println();
5714
5715 pw.print(prefix); pw.println(" Device battery use since last full charge");
5716 pw.print(prefix); pw.print(" Amount discharged (lower bound): ");
5717 pw.println(getLowDischargeAmountSinceCharge());
5718 pw.print(prefix); pw.print(" Amount discharged (upper bound): ");
5719 pw.println(getHighDischargeAmountSinceCharge());
5720 pw.print(prefix); pw.print(" Amount discharged while screen on: ");
5721 pw.println(getDischargeAmountScreenOnSinceCharge());
5722 pw.print(prefix); pw.print(" Amount discharged while screen off: ");
5723 pw.println(getDischargeAmountScreenOffSinceCharge());
5724 pw.print(prefix); pw.print(" Amount discharged while screen doze: ");
5725 pw.println(getDischargeAmountScreenDozeSinceCharge());
5726 pw.println();
5727
5728 final BatteryUsageStatsProvider provider = new BatteryUsageStatsProvider(context, this);
5729 final BatteryUsageStats stats = provider.getBatteryUsageStats(
5730 new BatteryUsageStatsQuery.Builder()
5731 .setMaxStatsAgeMs(0)
5732 .includePowerModels()
5733 .includeProcessStateData()
5734 .includeVirtualUids()
5735 .build());
5736 stats.dump(pw, prefix);
5737
5738 List<UidMobileRadioStats> uidMobileRadioStats =
5739 getUidMobileRadioStats(stats.getUidBatteryConsumers());
5740 if (uidMobileRadioStats.size() > 0) {
5741 pw.print(prefix);
5742 pw.println(" Per-app mobile ms per packet:");
5743 long totalTime = 0;
5744 for (int i = 0; i < uidMobileRadioStats.size(); i++) {
5745 final UidMobileRadioStats mrs = uidMobileRadioStats.get(i);
5746 sb.setLength(0);
5747 sb.append(prefix);
5748 sb.append(" Uid ");
5749 UserHandle.formatUid(sb, mrs.uid);
5750 sb.append(": ");
5751 sb.append(formatValue(mrs.millisecondsPerPacket));
5752 sb.append(" (");
5753 sb.append(mrs.rxPackets + mrs.txPackets);
5754 sb.append(" packets over ");
5755 formatTimeMsNoSpace(sb, mrs.radioActiveMs);
5756 sb.append(") ");
5757 sb.append(mrs.radioActiveCount);
5758 sb.append("x");
5759 pw.println(sb);
5760 totalTime += mrs.radioActiveMs;
5761 }
5762 sb.setLength(0);
5763 sb.append(prefix);
5764 sb.append(" TOTAL TIME: ");
5765 formatTimeMs(sb, totalTime);
5766 sb.append("(");
5767 sb.append(formatRatioLocked(totalTime, whichBatteryRealtime));
5768 sb.append(")");
5769 pw.println(sb);
5770 pw.println();
5771 }
5772
5773 final Comparator<TimerEntry> timerComparator = new Comparator<TimerEntry>() {
5774 @Override
5775 public int compare(TimerEntry lhs, TimerEntry rhs) {
5776 long lhsTime = lhs.mTime;
5777 long rhsTime = rhs.mTime;
5778 if (lhsTime < rhsTime) {
5779 return 1;
5780 }
5781 if (lhsTime > rhsTime) {
5782 return -1;
5783 }
5784 return 0;
5785 }
5786 };
5787
5788 if (reqUid < 0) {
5789 final Map<String, ? extends Timer> kernelWakelocks
5790 = getKernelWakelockStats();
5791 if (kernelWakelocks.size() > 0) {
5792 final ArrayList<TimerEntry> ktimers = new ArrayList<>();
5793 for (Map.Entry<String, ? extends Timer> ent
5794 : kernelWakelocks.entrySet()) {
5795 final Timer timer = ent.getValue();
5796 final long totalTimeMillis = computeWakeLock(timer, rawRealtime, which);
5797 if (totalTimeMillis > 0) {
5798 ktimers.add(new TimerEntry(ent.getKey(), 0, timer, totalTimeMillis));
5799 }
5800 }
5801 if (ktimers.size() > 0) {
5802 Collections.sort(ktimers, timerComparator);
5803 pw.print(prefix); pw.println(" All kernel wake locks:");
5804 for (int i=0; i<ktimers.size(); i++) {
5805 final TimerEntry timer = ktimers.get(i);
5806 String linePrefix = ": ";
5807 sb.setLength(0);
5808 sb.append(prefix);
5809 sb.append(" Kernel Wake lock ");
5810 sb.append(timer.mName);
5811 linePrefix = printWakeLock(sb, timer.mTimer, rawRealtime, null,
5812 which, linePrefix);
5813 if (!linePrefix.equals(": ")) {
5814 sb.append(" realtime");
5815 // Only print out wake locks that were held
5816 pw.println(sb.toString());
5817 }
5818 }
5819 pw.println();
5820 }
5821 }
5822
5823 if (timers.size() > 0) {
5824 Collections.sort(timers, timerComparator);
5825 pw.print(prefix); pw.println(" All partial wake locks:");
5826 for (int i=0; i<timers.size(); i++) {
5827 TimerEntry timer = timers.get(i);
5828 sb.setLength(0);
5829 sb.append(" Wake lock ");
5830 UserHandle.formatUid(sb, timer.mId);
5831 sb.append(" ");
5832 sb.append(timer.mName);
5833 printWakeLock(sb, timer.mTimer, rawRealtime, null, which, ": ");
5834 sb.append(" realtime");
5835 pw.println(sb.toString());
5836 }
5837 timers.clear();
5838 pw.println();
5839 }
5840
5841 final Map<String, ? extends Timer> wakeupReasons = getWakeupReasonStats();
5842 if (wakeupReasons.size() > 0) {
5843 pw.print(prefix); pw.println(" All wakeup reasons:");
5844 final ArrayList<TimerEntry> reasons = new ArrayList<>();
5845 for (Map.Entry<String, ? extends Timer> ent : wakeupReasons.entrySet()) {
5846 final Timer timer = ent.getValue();
5847 reasons.add(new TimerEntry(ent.getKey(), 0, timer,
5848 timer.getCountLocked(which)));
5849 }
5850 Collections.sort(reasons, timerComparator);
5851 for (int i=0; i<reasons.size(); i++) {
5852 TimerEntry timer = reasons.get(i);
5853 String linePrefix = ": ";
5854 sb.setLength(0);
5855 sb.append(prefix);
5856 sb.append(" Wakeup reason ");
5857 sb.append(timer.mName);
5858 printWakeLock(sb, timer.mTimer, rawRealtime, null, which, ": ");
5859 sb.append(" realtime");
5860 pw.println(sb.toString());
5861 }
5862 pw.println();
5863 }
5864 }
5865
5866 final LongSparseArray<? extends Timer> mMemoryStats = getKernelMemoryStats();
5867 if (mMemoryStats.size() > 0) {
5868 pw.println(" Memory Stats");
5869 for (int i = 0; i < mMemoryStats.size(); i++) {
5870 sb.setLength(0);
5871 sb.append(" Bandwidth ");
5872 sb.append(mMemoryStats.keyAt(i));
5873 sb.append(" Time ");
5874 sb.append(mMemoryStats.valueAt(i).getTotalTimeLocked(rawRealtime, which));
5875 pw.println(sb.toString());
5876 }
5877 pw.println();
5878 }
5879
5880 final Map<String, ? extends Timer> rpmStats = getRpmStats();
5881 if (rpmStats.size() > 0) {
5882 pw.print(prefix); pw.println(" Resource Power Manager Stats");
5883 if (rpmStats.size() > 0) {
5884 for (Map.Entry<String, ? extends Timer> ent : rpmStats.entrySet()) {
5885 final String timerName = ent.getKey();
5886 final Timer timer = ent.getValue();
5887 printTimer(pw, sb, timer, rawRealtime, which, prefix, timerName);
5888 }
5889 }
5890 pw.println();
5891 }
5892 if (SCREEN_OFF_RPM_STATS_ENABLED) {
5893 final Map<String, ? extends Timer> screenOffRpmStats = getScreenOffRpmStats();
5894 if (screenOffRpmStats.size() > 0) {
5895 pw.print(prefix);
5896 pw.println(" Resource Power Manager Stats for when screen was off");
5897 if (screenOffRpmStats.size() > 0) {
5898 for (Map.Entry<String, ? extends Timer> ent : screenOffRpmStats.entrySet()) {
5899 final String timerName = ent.getKey();
5900 final Timer timer = ent.getValue();
5901 printTimer(pw, sb, timer, rawRealtime, which, prefix, timerName);
5902 }
5903 }
5904 pw.println();
5905 }
5906 }
5907
5908 final long[] cpuFreqs = getCpuFreqs();
5909 if (cpuFreqs != null) {
5910 sb.setLength(0);
5911 sb.append(" CPU freqs:");
5912 for (int i = 0; i < cpuFreqs.length; ++i) {
5913 sb.append(' ').append(cpuFreqs[i]);
5914 }
5915 pw.println(sb.toString());
5916 pw.println();
5917 }
5918
5919 for (int iu=0; iu<NU; iu++) {
5920 final int uid = uidStats.keyAt(iu);
5921 if (reqUid >= 0 && uid != reqUid && uid != Process.SYSTEM_UID) {
5922 continue;
5923 }
5924
5925 final Uid u = uidStats.valueAt(iu);
5926
5927 pw.print(prefix);
5928 pw.print(" ");
5929 UserHandle.formatUid(pw, uid);
5930 pw.println(":");
5931 boolean uidActivity = false;
5932
5933 final long mobileRxBytes = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
5934 final long mobileTxBytes = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
5935 final long wifiRxBytes = u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
5936 final long wifiTxBytes = u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
5937 final long btRxBytes = u.getNetworkActivityBytes(NETWORK_BT_RX_DATA, which);
5938 final long btTxBytes = u.getNetworkActivityBytes(NETWORK_BT_TX_DATA, which);
5939
5940 final long mobileRxPackets = u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
5941 final long mobileTxPackets = u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
5942 final long wifiRxPackets = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
5943 final long wifiTxPackets = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
5944
5945 final long uidMobileActiveTime = u.getMobileRadioActiveTime(which);
5946 final int uidMobileActiveCount = u.getMobileRadioActiveCount(which);
5947
5948 final long fullWifiLockOnTime = u.getFullWifiLockTime(rawRealtime, which);
5949 final long wifiScanTime = u.getWifiScanTime(rawRealtime, which);
5950 final int wifiScanCount = u.getWifiScanCount(which);
5951 final int wifiScanCountBg = u.getWifiScanBackgroundCount(which);
5952 // 'actualTime' are unpooled and always since reset (regardless of 'which')
5953 final long wifiScanActualTime = u.getWifiScanActualTime(rawRealtime);
5954 final long wifiScanActualTimeBg = u.getWifiScanBackgroundTime(rawRealtime);
5955 final long uidWifiRunningTime = u.getWifiRunningTime(rawRealtime, which);
5956
5957 final long mobileWakeup = u.getMobileRadioApWakeupCount(which);
5958 final long wifiWakeup = u.getWifiRadioApWakeupCount(which);
5959
5960 if (mobileRxBytes > 0 || mobileTxBytes > 0
5961 || mobileRxPackets > 0 || mobileTxPackets > 0) {
5962 pw.print(prefix); pw.print(" Mobile network: ");
5963 pw.print(formatBytesLocked(mobileRxBytes)); pw.print(" received, ");
5964 pw.print(formatBytesLocked(mobileTxBytes));
5965 pw.print(" sent (packets "); pw.print(mobileRxPackets);
5966 pw.print(" received, "); pw.print(mobileTxPackets); pw.println(" sent)");
5967 }
5968 if (uidMobileActiveTime > 0 || uidMobileActiveCount > 0) {
5969 sb.setLength(0);
5970 sb.append(prefix); sb.append(" Mobile radio active: ");
5971 formatTimeMs(sb, uidMobileActiveTime / 1000);
5972 sb.append("(");
5973 sb.append(formatRatioLocked(uidMobileActiveTime, mobileActiveTime));
5974 sb.append(") "); sb.append(uidMobileActiveCount); sb.append("x");
5975 long packets = mobileRxPackets + mobileTxPackets;
5976 if (packets == 0) {
5977 packets = 1;
5978 }
5979 sb.append(" @ ");
5980 sb.append(formatCharge(uidMobileActiveTime / 1000 / (double) packets));
5981 sb.append(" mspp");
5982 pw.println(sb.toString());
5983 }
5984
5985 if (mobileWakeup > 0) {
5986 sb.setLength(0);
5987 sb.append(prefix);
5988 sb.append(" Mobile radio AP wakeups: ");
5989 sb.append(mobileWakeup);
5990 pw.println(sb.toString());
5991 }
5992
5993 printControllerActivityIfInteresting(pw, sb, prefix + " ",
5994 CELLULAR_CONTROLLER_NAME, u.getModemControllerActivity(), which);
5995
5996 if (wifiRxBytes > 0 || wifiTxBytes > 0 || wifiRxPackets > 0 || wifiTxPackets > 0) {
5997 pw.print(prefix); pw.print(" Wi-Fi network: ");
5998 pw.print(formatBytesLocked(wifiRxBytes)); pw.print(" received, ");
5999 pw.print(formatBytesLocked(wifiTxBytes));
6000 pw.print(" sent (packets "); pw.print(wifiRxPackets);
6001 pw.print(" received, "); pw.print(wifiTxPackets); pw.println(" sent)");
6002 }
6003
6004 if (fullWifiLockOnTime != 0 || wifiScanTime != 0 || wifiScanCount != 0
6005 || wifiScanCountBg != 0 || wifiScanActualTime != 0 || wifiScanActualTimeBg != 0
6006 || uidWifiRunningTime != 0) {
6007 sb.setLength(0);
6008 sb.append(prefix); sb.append(" Wifi Running: ");
6009 formatTimeMs(sb, uidWifiRunningTime / 1000);
6010 sb.append("("); sb.append(formatRatioLocked(uidWifiRunningTime,
6011 whichBatteryRealtime)); sb.append(")\n");
6012 sb.append(prefix); sb.append(" Full Wifi Lock: ");
6013 formatTimeMs(sb, fullWifiLockOnTime / 1000);
6014 sb.append("("); sb.append(formatRatioLocked(fullWifiLockOnTime,
6015 whichBatteryRealtime)); sb.append(")\n");
6016 sb.append(prefix); sb.append(" Wifi Scan (blamed): ");
6017 formatTimeMs(sb, wifiScanTime / 1000);
6018 sb.append("("); sb.append(formatRatioLocked(wifiScanTime,
6019 whichBatteryRealtime)); sb.append(") ");
6020 sb.append(wifiScanCount);
6021 sb.append("x\n");
6022 // actual and background times are unpooled and since reset (regardless of 'which')
6023 sb.append(prefix); sb.append(" Wifi Scan (actual): ");
6024 formatTimeMs(sb, wifiScanActualTime / 1000);
6025 sb.append("("); sb.append(formatRatioLocked(wifiScanActualTime,
6026 computeBatteryRealtime(rawRealtime, STATS_SINCE_CHARGED)));
6027 sb.append(") ");
6028 sb.append(wifiScanCount);
6029 sb.append("x\n");
6030 sb.append(prefix); sb.append(" Background Wifi Scan: ");
6031 formatTimeMs(sb, wifiScanActualTimeBg / 1000);
6032 sb.append("("); sb.append(formatRatioLocked(wifiScanActualTimeBg,
6033 computeBatteryRealtime(rawRealtime, STATS_SINCE_CHARGED)));
6034 sb.append(") ");
6035 sb.append(wifiScanCountBg);
6036 sb.append("x");
6037 pw.println(sb.toString());
6038 }
6039
6040 if (wifiWakeup > 0) {
6041 sb.setLength(0);
6042 sb.append(prefix);
6043 sb.append(" WiFi AP wakeups: ");
6044 sb.append(wifiWakeup);
6045 pw.println(sb.toString());
6046 }
6047
6048 printControllerActivityIfInteresting(pw, sb, prefix + " ", WIFI_CONTROLLER_NAME,
6049 u.getWifiControllerActivity(), which);
6050
6051 if (btRxBytes > 0 || btTxBytes > 0) {
6052 pw.print(prefix); pw.print(" Bluetooth network: ");
6053 pw.print(formatBytesLocked(btRxBytes)); pw.print(" received, ");
6054 pw.print(formatBytesLocked(btTxBytes));
6055 pw.println(" sent");
6056 }
6057
6058 final Timer bleTimer = u.getBluetoothScanTimer();
6059 if (bleTimer != null) {
6060 // Convert from microseconds to milliseconds with rounding
6061 final long totalTimeMs = (bleTimer.getTotalTimeLocked(rawRealtime, which) + 500)
6062 / 1000;
6063 if (totalTimeMs != 0) {
6064 final int count = bleTimer.getCountLocked(which);
6065 final Timer bleTimerBg = u.getBluetoothScanBackgroundTimer();
6066 final int countBg = bleTimerBg != null ? bleTimerBg.getCountLocked(which) : 0;
6067 // 'actualTime' are unpooled and always since reset (regardless of 'which')
6068 final long actualTimeMs = bleTimer.getTotalDurationMsLocked(rawRealtimeMs);
6069 final long actualTimeMsBg = bleTimerBg != null ?
6070 bleTimerBg.getTotalDurationMsLocked(rawRealtimeMs) : 0;
6071 // Result counters
6072 final int resultCount = u.getBluetoothScanResultCounter() != null ?
6073 u.getBluetoothScanResultCounter().getCountLocked(which) : 0;
6074 final int resultCountBg = u.getBluetoothScanResultBgCounter() != null ?
6075 u.getBluetoothScanResultBgCounter().getCountLocked(which) : 0;
6076 // Unoptimized scan timer. Unpooled and since reset (regardless of 'which').
6077 final Timer unoptimizedScanTimer = u.getBluetoothUnoptimizedScanTimer();
6078 final long unoptimizedScanTotalTime = unoptimizedScanTimer != null ?
6079 unoptimizedScanTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
6080 final long unoptimizedScanMaxTime = unoptimizedScanTimer != null ?
6081 unoptimizedScanTimer.getMaxDurationMsLocked(rawRealtimeMs) : 0;
6082 // Unoptimized bg scan timer. Unpooled and since reset (regardless of 'which').
6083 final Timer unoptimizedScanTimerBg =
6084 u.getBluetoothUnoptimizedScanBackgroundTimer();
6085 final long unoptimizedScanTotalTimeBg = unoptimizedScanTimerBg != null ?
6086 unoptimizedScanTimerBg.getTotalDurationMsLocked(rawRealtimeMs) : 0;
6087 final long unoptimizedScanMaxTimeBg = unoptimizedScanTimerBg != null ?
6088 unoptimizedScanTimerBg.getMaxDurationMsLocked(rawRealtimeMs) : 0;
6089
6090 sb.setLength(0);
6091 if (actualTimeMs != totalTimeMs) {
6092 sb.append(prefix);
6093 sb.append(" Bluetooth Scan (total blamed realtime): ");
6094 formatTimeMs(sb, totalTimeMs);
6095 sb.append(" (");
6096 sb.append(count);
6097 sb.append(" times)");
6098 if (bleTimer.isRunningLocked()) {
6099 sb.append(" (currently running)");
6100 }
6101 sb.append("\n");
6102 }
6103
6104 sb.append(prefix);
6105 sb.append(" Bluetooth Scan (total actual realtime): ");
6106 formatTimeMs(sb, actualTimeMs); // since reset, ignores 'which'
6107 sb.append(" (");
6108 sb.append(count);
6109 sb.append(" times)");
6110 if (bleTimer.isRunningLocked()) {
6111 sb.append(" (currently running)");
6112 }
6113 sb.append("\n");
6114 if (actualTimeMsBg > 0 || countBg > 0) {
6115 sb.append(prefix);
6116 sb.append(" Bluetooth Scan (background realtime): ");
6117 formatTimeMs(sb, actualTimeMsBg); // since reset, ignores 'which'
6118 sb.append(" (");
6119 sb.append(countBg);
6120 sb.append(" times)");
6121 if (bleTimerBg != null && bleTimerBg.isRunningLocked()) {
6122 sb.append(" (currently running in background)");
6123 }
6124 sb.append("\n");
6125 }
6126
6127 sb.append(prefix);
6128 sb.append(" Bluetooth Scan Results: ");
6129 sb.append(resultCount);
6130 sb.append(" (");
6131 sb.append(resultCountBg);
6132 sb.append(" in background)");
6133
6134 if (unoptimizedScanTotalTime > 0 || unoptimizedScanTotalTimeBg > 0) {
6135 sb.append("\n");
6136 sb.append(prefix);
6137 sb.append(" Unoptimized Bluetooth Scan (realtime): ");
6138 formatTimeMs(sb, unoptimizedScanTotalTime); // since reset, ignores 'which'
6139 sb.append(" (max ");
6140 formatTimeMs(sb, unoptimizedScanMaxTime); // since reset, ignores 'which'
6141 sb.append(")");
6142 if (unoptimizedScanTimer != null
6143 && unoptimizedScanTimer.isRunningLocked()) {
6144 sb.append(" (currently running unoptimized)");
6145 }
6146 if (unoptimizedScanTimerBg != null && unoptimizedScanTotalTimeBg > 0) {
6147 sb.append("\n");
6148 sb.append(prefix);
6149 sb.append(" Unoptimized Bluetooth Scan (background realtime): ");
6150 formatTimeMs(sb, unoptimizedScanTotalTimeBg); // since reset
6151 sb.append(" (max ");
6152 formatTimeMs(sb, unoptimizedScanMaxTimeBg); // since reset
6153 sb.append(")");
6154 if (unoptimizedScanTimerBg.isRunningLocked()) {
6155 sb.append(" (currently running unoptimized in background)");
6156 }
6157 }
6158 }
6159 pw.println(sb.toString());
6160 uidActivity = true;
6161 }
6162 }
6163
6164
6165
6166 if (u.hasUserActivity()) {
6167 boolean hasData = false;
6168 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
6169 final int val = u.getUserActivityCount(i, which);
6170 if (val != 0) {
6171 if (!hasData) {
6172 sb.setLength(0);
6173 sb.append(" User activity: ");
6174 hasData = true;
6175 } else {
6176 sb.append(", ");
6177 }
6178 sb.append(val);
6179 sb.append(" ");
6180 sb.append(Uid.USER_ACTIVITY_TYPES[i]);
6181 }
6182 }
6183 if (hasData) {
6184 pw.println(sb.toString());
6185 }
6186 }
6187
6188 final ArrayMap<String, ? extends Uid.Wakelock> wakelocks
6189 = u.getWakelockStats();
6190 long totalFullWakelock = 0, totalPartialWakelock = 0, totalWindowWakelock = 0;
6191 long totalDrawWakelock = 0;
6192 int countWakelock = 0;
6193 for (int iw=wakelocks.size()-1; iw>=0; iw--) {
6194 final Uid.Wakelock wl = wakelocks.valueAt(iw);
6195 String linePrefix = ": ";
6196 sb.setLength(0);
6197 sb.append(prefix);
6198 sb.append(" Wake lock ");
6199 sb.append(wakelocks.keyAt(iw));
6200 linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), rawRealtime,
6201 "full", which, linePrefix);
6202 final Timer pTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
6203 linePrefix = printWakeLock(sb, pTimer, rawRealtime,
6204 "partial", which, linePrefix);
6205 linePrefix = printWakeLock(sb, pTimer != null ? pTimer.getSubTimer() : null,
6206 rawRealtime, "background partial", which, linePrefix);
6207 linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), rawRealtime,
6208 "window", which, linePrefix);
6209 linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_DRAW), rawRealtime,
6210 "draw", which, linePrefix);
6211 sb.append(" realtime");
6212 pw.println(sb.toString());
6213 uidActivity = true;
6214 countWakelock++;
6215
6216 totalFullWakelock += computeWakeLock(wl.getWakeTime(WAKE_TYPE_FULL),
6217 rawRealtime, which);
6218 totalPartialWakelock += computeWakeLock(wl.getWakeTime(WAKE_TYPE_PARTIAL),
6219 rawRealtime, which);
6220 totalWindowWakelock += computeWakeLock(wl.getWakeTime(WAKE_TYPE_WINDOW),
6221 rawRealtime, which);
6222 totalDrawWakelock += computeWakeLock(wl.getWakeTime(WAKE_TYPE_DRAW),
6223 rawRealtime, which);
6224 }
6225 if (countWakelock > 1) {
6226 // get unpooled partial wakelock quantities (unlike totalPartialWakelock, which is
6227 // pooled and therefore just a lower bound)
6228 long actualTotalPartialWakelock = 0;
6229 long actualBgPartialWakelock = 0;
6230 if (u.getAggregatedPartialWakelockTimer() != null) {
6231 final Timer aggTimer = u.getAggregatedPartialWakelockTimer();
6232 // Convert from microseconds to milliseconds with rounding
6233 actualTotalPartialWakelock =
6234 aggTimer.getTotalDurationMsLocked(rawRealtimeMs);
6235 final Timer bgAggTimer = aggTimer.getSubTimer();
6236 actualBgPartialWakelock = bgAggTimer != null ?
6237 bgAggTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
6238 }
6239
6240 if (actualTotalPartialWakelock != 0 || actualBgPartialWakelock != 0 ||
6241 totalFullWakelock != 0 || totalPartialWakelock != 0 ||
6242 totalWindowWakelock != 0) {
6243 sb.setLength(0);
6244 sb.append(prefix);
6245 sb.append(" TOTAL wake: ");
6246 boolean needComma = false;
6247 if (totalFullWakelock != 0) {
6248 needComma = true;
6249 formatTimeMs(sb, totalFullWakelock);
6250 sb.append("full");
6251 }
6252 if (totalPartialWakelock != 0) {
6253 if (needComma) {
6254 sb.append(", ");
6255 }
6256 needComma = true;
6257 formatTimeMs(sb, totalPartialWakelock);
6258 sb.append("blamed partial");
6259 }
6260 if (actualTotalPartialWakelock != 0) {
6261 if (needComma) {
6262 sb.append(", ");
6263 }
6264 needComma = true;
6265 formatTimeMs(sb, actualTotalPartialWakelock);
6266 sb.append("actual partial");
6267 }
6268 if (actualBgPartialWakelock != 0) {
6269 if (needComma) {
6270 sb.append(", ");
6271 }
6272 needComma = true;
6273 formatTimeMs(sb, actualBgPartialWakelock);
6274 sb.append("actual background partial");
6275 }
6276 if (totalWindowWakelock != 0) {
6277 if (needComma) {
6278 sb.append(", ");
6279 }
6280 needComma = true;
6281 formatTimeMs(sb, totalWindowWakelock);
6282 sb.append("window");
6283 }
6284 if (totalDrawWakelock != 0) {
6285 if (needComma) {
6286 sb.append(",");
6287 }
6288 needComma = true;
6289 formatTimeMs(sb, totalDrawWakelock);
6290 sb.append("draw");
6291 }
6292 sb.append(" realtime");
6293 pw.println(sb.toString());
6294 }
6295 }
6296
6297 // Calculate multicast wakelock stats
6298 final Timer mcTimer = u.getMulticastWakelockStats();
6299 if (mcTimer != null) {
6300 final long multicastWakeLockTimeMicros = mcTimer.getTotalTimeLocked(rawRealtime, which);
6301 final int multicastWakeLockCount = mcTimer.getCountLocked(which);
6302
6303 if (multicastWakeLockTimeMicros > 0) {
6304 sb.setLength(0);
6305 sb.append(prefix);
6306 sb.append(" WiFi Multicast Wakelock");
6307 sb.append(" count = ");
6308 sb.append(multicastWakeLockCount);
6309 sb.append(" time = ");
6310 formatTimeMsNoSpace(sb, (multicastWakeLockTimeMicros + 500) / 1000);
6311 pw.println(sb.toString());
6312 }
6313 }
6314
6315 final ArrayMap<String, ? extends Timer> syncs = u.getSyncStats();
6316 for (int isy=syncs.size()-1; isy>=0; isy--) {
6317 final Timer timer = syncs.valueAt(isy);
6318 // Convert from microseconds to milliseconds with rounding
6319 final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000;
6320 final int count = timer.getCountLocked(which);
6321 final Timer bgTimer = timer.getSubTimer();
6322 final long bgTime = bgTimer != null ?
6323 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : -1;
6324 final int bgCount = bgTimer != null ? bgTimer.getCountLocked(which) : -1;
6325 sb.setLength(0);
6326 sb.append(prefix);
6327 sb.append(" Sync ");
6328 sb.append(syncs.keyAt(isy));
6329 sb.append(": ");
6330 if (totalTime != 0) {
6331 formatTimeMs(sb, totalTime);
6332 sb.append("realtime (");
6333 sb.append(count);
6334 sb.append(" times)");
6335 if (bgTime > 0) {
6336 sb.append(", ");
6337 formatTimeMs(sb, bgTime);
6338 sb.append("background (");
6339 sb.append(bgCount);
6340 sb.append(" times)");
6341 }
6342 } else {
6343 sb.append("(not used)");
6344 }
6345 pw.println(sb.toString());
6346 uidActivity = true;
6347 }
6348
6349 final ArrayMap<String, ? extends Timer> jobs = u.getJobStats();
6350 for (int ij=jobs.size()-1; ij>=0; ij--) {
6351 final Timer timer = jobs.valueAt(ij);
6352 // Convert from microseconds to milliseconds with rounding
6353 final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500) / 1000;
6354 final int count = timer.getCountLocked(which);
6355 final Timer bgTimer = timer.getSubTimer();
6356 final long bgTime = bgTimer != null ?
6357 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : -1;
6358 final int bgCount = bgTimer != null ? bgTimer.getCountLocked(which) : -1;
6359 sb.setLength(0);
6360 sb.append(prefix);
6361 sb.append(" Job ");
6362 sb.append(jobs.keyAt(ij));
6363 sb.append(": ");
6364 if (totalTime != 0) {
6365 formatTimeMs(sb, totalTime);
6366 sb.append("realtime (");
6367 sb.append(count);
6368 sb.append(" times)");
6369 if (bgTime > 0) {
6370 sb.append(", ");
6371 formatTimeMs(sb, bgTime);
6372 sb.append("background (");
6373 sb.append(bgCount);
6374 sb.append(" times)");
6375 }
6376 } else {
6377 sb.append("(not used)");
6378 }
6379 pw.println(sb.toString());
6380 uidActivity = true;
6381 }
6382
6383 final ArrayMap<String, SparseIntArray> completions = u.getJobCompletionStats();
6384 for (int ic=completions.size()-1; ic>=0; ic--) {
6385 SparseIntArray types = completions.valueAt(ic);
6386 if (types != null) {
6387 pw.print(prefix);
6388 pw.print(" Job Completions ");
6389 pw.print(completions.keyAt(ic));
6390 pw.print(":");
6391 for (int it=0; it<types.size(); it++) {
6392 pw.print(" ");
6393 pw.print(JobParameters.getInternalReasonCodeDescription(types.keyAt(it)));
6394 pw.print("(");
6395 pw.print(types.valueAt(it));
6396 pw.print("x)");
6397 }
6398 pw.println();
6399 }
6400 }
6401
6402 u.getDeferredJobsLineLocked(sb, which);
6403 if (sb.length() > 0) {
6404 pw.print(" Jobs deferred on launch "); pw.println(sb.toString());
6405 }
6406
6407 uidActivity |= printTimer(pw, sb, u.getFlashlightTurnedOnTimer(), rawRealtime, which,
6408 prefix, "Flashlight");
6409 uidActivity |= printTimer(pw, sb, u.getCameraTurnedOnTimer(), rawRealtime, which,
6410 prefix, "Camera");
6411 uidActivity |= printTimer(pw, sb, u.getVideoTurnedOnTimer(), rawRealtime, which,
6412 prefix, "Video");
6413 uidActivity |= printTimer(pw, sb, u.getAudioTurnedOnTimer(), rawRealtime, which,
6414 prefix, "Audio");
6415
6416 final SparseArray<? extends Uid.Sensor> sensors = u.getSensorStats();
6417 final int NSE = sensors.size();
6418 for (int ise=0; ise<NSE; ise++) {
6419 final Uid.Sensor se = sensors.valueAt(ise);
6420 final int sensorNumber = sensors.keyAt(ise);
6421 sb.setLength(0);
6422 sb.append(prefix);
6423 sb.append(" Sensor ");
6424 int handle = se.getHandle();
6425 if (handle == Uid.Sensor.GPS) {
6426 sb.append("GPS");
6427 } else {
6428 sb.append(handle);
6429 }
6430 sb.append(": ");
6431
6432 final Timer timer = se.getSensorTime();
6433 if (timer != null) {
6434 // Convert from microseconds to milliseconds with rounding
6435 final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500)
6436 / 1000;
6437 final int count = timer.getCountLocked(which);
6438 final Timer bgTimer = se.getSensorBackgroundTime();
6439 final int bgCount = bgTimer != null ? bgTimer.getCountLocked(which) : 0;
6440 // 'actualTime' are unpooled and always since reset (regardless of 'which')
6441 final long actualTime = timer.getTotalDurationMsLocked(rawRealtimeMs);
6442 final long bgActualTime = bgTimer != null ?
6443 bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
6444
6445 //timer.logState();
6446 if (totalTime != 0) {
6447 if (actualTime != totalTime) {
6448 formatTimeMs(sb, totalTime);
6449 sb.append("blamed realtime, ");
6450 }
6451
6452 formatTimeMs(sb, actualTime); // since reset, regardless of 'which'
6453 sb.append("realtime (");
6454 sb.append(count);
6455 sb.append(" times)");
6456
6457 if (bgActualTime != 0 || bgCount > 0) {
6458 sb.append(", ");
6459 formatTimeMs(sb, bgActualTime); // since reset, regardless of 'which'
6460 sb.append("background (");
6461 sb.append(bgCount);
6462 sb.append(" times)");
6463 }
6464 } else {
6465 sb.append("(not used)");
6466 }
6467 } else {
6468 sb.append("(not used)");
6469 }
6470
6471 pw.println(sb.toString());
6472 uidActivity = true;
6473 }
6474
6475 uidActivity |= printTimer(pw, sb, u.getVibratorOnTimer(), rawRealtime, which, prefix,
6476 "Vibrator");
6477 uidActivity |= printTimer(pw, sb, u.getForegroundActivityTimer(), rawRealtime, which,
6478 prefix, "Foreground activities");
6479 uidActivity |= printTimer(pw, sb, u.getForegroundServiceTimer(), rawRealtime, which,
6480 prefix, "Foreground services");
6481
6482 long totalStateTime = 0;
6483 for (int ips=0; ips<Uid.NUM_PROCESS_STATE; ips++) {
6484 long time = u.getProcessStateTime(ips, rawRealtime, which);
6485 if (time > 0) {
6486 totalStateTime += time;
6487 sb.setLength(0);
6488 sb.append(prefix);
6489 sb.append(" ");
6490 sb.append(Uid.PROCESS_STATE_NAMES[ips]);
6491 sb.append(" for: ");
6492 formatTimeMs(sb, (time + 500) / 1000);
6493 pw.println(sb.toString());
6494 uidActivity = true;
6495 }
6496 }
6497 if (totalStateTime > 0) {
6498 sb.setLength(0);
6499 sb.append(prefix);
6500 sb.append(" Total running: ");
6501 formatTimeMs(sb, (totalStateTime + 500) / 1000);
6502 pw.println(sb.toString());
6503 }
6504
6505 final long userCpuTimeUs = u.getUserCpuTimeUs(which);
6506 final long systemCpuTimeUs = u.getSystemCpuTimeUs(which);
6507 if (userCpuTimeUs > 0 || systemCpuTimeUs > 0) {
6508 sb.setLength(0);
6509 sb.append(prefix);
6510 sb.append(" Total cpu time: u=");
6511 formatTimeMs(sb, userCpuTimeUs / 1000);
6512 sb.append("s=");
6513 formatTimeMs(sb, systemCpuTimeUs / 1000);
6514 pw.println(sb.toString());
6515 }
6516
6517 final long[] cpuFreqTimes = u.getCpuFreqTimes(which);
6518 if (cpuFreqTimes != null) {
6519 sb.setLength(0);
6520 sb.append(" Total cpu time per freq:");
6521 for (int i = 0; i < cpuFreqTimes.length; ++i) {
6522 sb.append(' ').append(cpuFreqTimes[i]);
6523 }
6524 pw.println(sb.toString());
6525 }
6526 final long[] screenOffCpuFreqTimes = u.getScreenOffCpuFreqTimes(which);
6527 if (screenOffCpuFreqTimes != null) {
6528 sb.setLength(0);
6529 sb.append(" Total screen-off cpu time per freq:");
6530 for (int i = 0; i < screenOffCpuFreqTimes.length; ++i) {
6531 sb.append(' ').append(screenOffCpuFreqTimes[i]);
6532 }
6533 pw.println(sb.toString());
6534 }
6535
6536 final long[] timesInFreqMs = new long[getCpuFreqCount()];
6537 for (int procState = 0; procState < Uid.NUM_PROCESS_STATE; ++procState) {
6538 if (u.getCpuFreqTimes(timesInFreqMs, procState)) {
6539 sb.setLength(0);
6540 sb.append(" Cpu times per freq at state ")
6541 .append(Uid.PROCESS_STATE_NAMES[procState]).append(':');
6542 for (int i = 0; i < timesInFreqMs.length; ++i) {
6543 sb.append(" ").append(timesInFreqMs[i]);
6544 }
6545 pw.println(sb.toString());
6546 }
6547
6548 if (u.getScreenOffCpuFreqTimes(timesInFreqMs, procState)) {
6549 sb.setLength(0);
6550 sb.append(" Screen-off cpu times per freq at state ")
6551 .append(Uid.PROCESS_STATE_NAMES[procState]).append(':');
6552 for (int i = 0; i < timesInFreqMs.length; ++i) {
6553 sb.append(" ").append(timesInFreqMs[i]);
6554 }
6555 pw.println(sb.toString());
6556 }
6557 }
6558
6559 final ArrayMap<String, ? extends Uid.Proc> processStats
6560 = u.getProcessStats();
6561 for (int ipr=processStats.size()-1; ipr>=0; ipr--) {
6562 final Uid.Proc ps = processStats.valueAt(ipr);
6563 long userTime;
6564 long systemTime;
6565 long foregroundTime;
6566 int starts;
6567 int numExcessive;
6568
6569 userTime = ps.getUserTime(which);
6570 systemTime = ps.getSystemTime(which);
6571 foregroundTime = ps.getForegroundTime(which);
6572 starts = ps.getStarts(which);
6573 final int numCrashes = ps.getNumCrashes(which);
6574 final int numAnrs = ps.getNumAnrs(which);
6575 numExcessive = which == STATS_SINCE_CHARGED
6576 ? ps.countExcessivePowers() : 0;
6577
6578 if (userTime != 0 || systemTime != 0 || foregroundTime != 0 || starts != 0
6579 || numExcessive != 0 || numCrashes != 0 || numAnrs != 0) {
6580 sb.setLength(0);
6581 sb.append(prefix); sb.append(" Proc ");
6582 sb.append(processStats.keyAt(ipr)); sb.append(":\n");
6583 sb.append(prefix); sb.append(" CPU: ");
6584 formatTimeMs(sb, userTime); sb.append("usr + ");
6585 formatTimeMs(sb, systemTime); sb.append("krn ; ");
6586 formatTimeMs(sb, foregroundTime); sb.append("fg");
6587 if (starts != 0 || numCrashes != 0 || numAnrs != 0) {
6588 sb.append("\n"); sb.append(prefix); sb.append(" ");
6589 boolean hasOne = false;
6590 if (starts != 0) {
6591 hasOne = true;
6592 sb.append(starts); sb.append(" starts");
6593 }
6594 if (numCrashes != 0) {
6595 if (hasOne) {
6596 sb.append(", ");
6597 }
6598 hasOne = true;
6599 sb.append(numCrashes); sb.append(" crashes");
6600 }
6601 if (numAnrs != 0) {
6602 if (hasOne) {
6603 sb.append(", ");
6604 }
6605 sb.append(numAnrs); sb.append(" anrs");
6606 }
6607 }
6608 pw.println(sb.toString());
6609 for (int e=0; e<numExcessive; e++) {
6610 Uid.Proc.ExcessivePower ew = ps.getExcessivePower(e);
6611 if (ew != null) {
6612 pw.print(prefix); pw.print(" * Killed for ");
6613 if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) {
6614 pw.print("cpu");
6615 } else {
6616 pw.print("unknown");
6617 }
6618 pw.print(" use: ");
6619 TimeUtils.formatDuration(ew.usedTime, pw);
6620 pw.print(" over ");
6621 TimeUtils.formatDuration(ew.overTime, pw);
6622 if (ew.overTime != 0) {
6623 pw.print(" (");
6624 pw.print((ew.usedTime*100)/ew.overTime);
6625 pw.println("%)");
6626 }
6627 }
6628 }
6629 uidActivity = true;
6630 }
6631 }
6632
6633 final ArrayMap<String, ? extends Uid.Pkg> packageStats
6634 = u.getPackageStats();
6635 for (int ipkg=packageStats.size()-1; ipkg>=0; ipkg--) {
6636 pw.print(prefix); pw.print(" Apk "); pw.print(packageStats.keyAt(ipkg));
6637 pw.println(":");
6638 boolean apkActivity = false;
6639 final Uid.Pkg ps = packageStats.valueAt(ipkg);
6640 final ArrayMap<String, ? extends Counter> alarms = ps.getWakeupAlarmStats();
6641 for (int iwa=alarms.size()-1; iwa>=0; iwa--) {
6642 pw.print(prefix); pw.print(" Wakeup alarm ");
6643 pw.print(alarms.keyAt(iwa)); pw.print(": ");
6644 pw.print(alarms.valueAt(iwa).getCountLocked(which));
6645 pw.println(" times");
6646 apkActivity = true;
6647 }
6648 final ArrayMap<String, ? extends Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
6649 for (int isvc=serviceStats.size()-1; isvc>=0; isvc--) {
6650 final Uid.Pkg.Serv ss = serviceStats.valueAt(isvc);
6651 final long startTime = ss.getStartTime(batteryUptime, which);
6652 final int starts = ss.getStarts(which);
6653 final int launches = ss.getLaunches(which);
6654 if (startTime != 0 || starts != 0 || launches != 0) {
6655 sb.setLength(0);
6656 sb.append(prefix); sb.append(" Service ");
6657 sb.append(serviceStats.keyAt(isvc)); sb.append(":\n");
6658 sb.append(prefix); sb.append(" Created for: ");
6659 formatTimeMs(sb, startTime / 1000);
6660 sb.append("uptime\n");
6661 sb.append(prefix); sb.append(" Starts: ");
6662 sb.append(starts);
6663 sb.append(", launches: "); sb.append(launches);
6664 pw.println(sb.toString());
6665 apkActivity = true;
6666 }
6667 }
6668 if (!apkActivity) {
6669 pw.print(prefix); pw.println(" (nothing executed)");
6670 }
6671 uidActivity = true;
6672 }
6673 if (!uidActivity) {
6674 pw.print(prefix); pw.println(" (nothing executed)");
6675 }
6676 }
6677 }
6678
6679 static void printBitDescriptions(StringBuilder sb, int oldval, int newval,
6680 HistoryTag wakelockTag, BitDescription[] descriptions, boolean longNames) {
6681 int diff = oldval ^ newval;
6682 if (diff == 0) return;
6683 boolean didWake = false;
6684 for (int i=0; i<descriptions.length; i++) {
6685 BitDescription bd = descriptions[i];
6686 if ((diff&bd.mask) != 0) {
6687 sb.append(longNames ? " " : ",");
6688 if (bd.shift < 0) {
6689 sb.append((newval & bd.mask) != 0 ? "+" : "-");
6690 sb.append(longNames ? bd.name : bd.shortName);
6691 if (bd.mask == HistoryItem.STATE_WAKE_LOCK_FLAG && wakelockTag != null) {
6692 didWake = true;
6693 sb.append("=");
6694 if (longNames) {
6695 UserHandle.formatUid(sb, wakelockTag.uid);
6696 sb.append(":\"");
6697 sb.append(wakelockTag.string);
6698 sb.append("\"");
6699 } else {
6700 sb.append(wakelockTag.poolIdx);
6701 }
6702 }
6703 } else {
6704 sb.append(longNames ? bd.name : bd.shortName);
6705 sb.append("=");
6706 int val = (newval&bd.mask)>>bd.shift;
6707 if (bd.values != null && val >= 0 && val < bd.values.length) {
6708 sb.append(longNames ? bd.values[val] : bd.shortValues[val]);
6709 } else {
6710 sb.append(val);
6711 }
6712 }
6713 }
6714 }
6715 if (!didWake && wakelockTag != null) {
6716 sb.append(longNames ? " wake_lock=" : ",w=");
6717 if (longNames) {
6718 UserHandle.formatUid(sb, wakelockTag.uid);
6719 sb.append(":\"");
6720 sb.append(wakelockTag.string);
6721 sb.append("\"");
6722 } else {
6723 sb.append(wakelockTag.poolIdx);
6724 }
6725 }
6726 }
6727
6728 public void prepareForDumpLocked() {
6729 // We don't need to require subclasses implement this.
6730 }
6731
6732 public static class HistoryPrinter {
6733 int oldState = 0;
6734 int oldState2 = 0;
6735 int oldLevel = -1;
6736 int oldStatus = -1;
6737 int oldHealth = -1;
6738 int oldPlug = -1;
6739 int oldTemp = -1;
6740 int oldVolt = -1;
6741 int oldChargeMAh = -1;
6742 double oldModemRailChargeMah = -1;
6743 double oldWifiRailChargeMah = -1;
6744 long lastTime = -1;
6745
6746 void reset() {
6747 oldState = oldState2 = 0;
6748 oldLevel = -1;
6749 oldStatus = -1;
6750 oldHealth = -1;
6751 oldPlug = -1;
6752 oldTemp = -1;
6753 oldVolt = -1;
6754 oldChargeMAh = -1;
6755 oldModemRailChargeMah = -1;
6756 oldWifiRailChargeMah = -1;
6757 }
6758
6759 public void printNextItem(PrintWriter pw, HistoryItem rec, long baseTime, boolean checkin,
6760 boolean verbose) {
6761 pw.print(printNextItem(rec, baseTime, checkin, verbose));
6762 }
6763
6764 /** Print the next history item to proto. */
6765 public void printNextItem(ProtoOutputStream proto, HistoryItem rec, long baseTime,
6766 boolean verbose) {
6767 String item = printNextItem(rec, baseTime, true, verbose);
6768 for (String line : item.split("\n")) {
6769 proto.write(BatteryStatsServiceDumpHistoryProto.CSV_LINES, line);
6770 }
6771 }
6772
6773 private String printNextItem(HistoryItem rec, long baseTime, boolean checkin,
6774 boolean verbose) {
6775 StringBuilder item = new StringBuilder();
6776 if (!checkin) {
6777 item.append(" ");
6778 TimeUtils.formatDuration(
6779 rec.time - baseTime, item, TimeUtils.HUNDRED_DAY_FIELD_LEN);
6780 item.append(" (");
6781 item.append(rec.numReadInts);
6782 item.append(") ");
6783 } else {
6784 item.append(BATTERY_STATS_CHECKIN_VERSION); item.append(',');
6785 item.append(HISTORY_DATA); item.append(',');
6786 if (lastTime < 0) {
6787 item.append(rec.time - baseTime);
6788 } else {
6789 item.append(rec.time - lastTime);
6790 }
6791 lastTime = rec.time;
6792 }
6793 if (rec.cmd == HistoryItem.CMD_START) {
6794 if (checkin) {
6795 item.append(":");
6796 }
6797 item.append("START\n");
6798 reset();
6799 } else if (rec.cmd == HistoryItem.CMD_CURRENT_TIME
6800 || rec.cmd == HistoryItem.CMD_RESET) {
6801 if (checkin) {
6802 item.append(":");
6803 }
6804 if (rec.cmd == HistoryItem.CMD_RESET) {
6805 item.append("RESET:");
6806 reset();
6807 }
6808 item.append("TIME:");
6809 if (checkin) {
6810 item.append(rec.currentTime);
6811 item.append("\n");
6812 } else {
6813 item.append(" ");
6814 item.append(DateFormat.format("yyyy-MM-dd-HH-mm-ss",
6815 rec.currentTime).toString());
6816 item.append("\n");
6817 }
6818 } else if (rec.cmd == HistoryItem.CMD_SHUTDOWN) {
6819 if (checkin) {
6820 item.append(":");
6821 }
6822 item.append("SHUTDOWN\n");
6823 } else if (rec.cmd == HistoryItem.CMD_OVERFLOW) {
6824 if (checkin) {
6825 item.append(":");
6826 }
6827 item.append("*OVERFLOW*\n");
6828 } else {
6829 if (!checkin) {
6830 if (rec.batteryLevel < 10) item.append("00");
6831 else if (rec.batteryLevel < 100) item.append("0");
6832 item.append(rec.batteryLevel);
6833 if (verbose) {
6834 item.append(" ");
6835 if (rec.states < 0) ;
6836 else if (rec.states < 0x10) item.append("0000000");
6837 else if (rec.states < 0x100) item.append("000000");
6838 else if (rec.states < 0x1000) item.append("00000");
6839 else if (rec.states < 0x10000) item.append("0000");
6840 else if (rec.states < 0x100000) item.append("000");
6841 else if (rec.states < 0x1000000) item.append("00");
6842 else if (rec.states < 0x10000000) item.append("0");
6843 item.append(Integer.toHexString(rec.states));
6844 }
6845 } else {
6846 if (oldLevel != rec.batteryLevel) {
6847 oldLevel = rec.batteryLevel;
6848 item.append(",Bl="); item.append(rec.batteryLevel);
6849 }
6850 }
6851 if (oldStatus != rec.batteryStatus) {
6852 oldStatus = rec.batteryStatus;
6853 item.append(checkin ? ",Bs=" : " status=");
6854 switch (oldStatus) {
6855 case BatteryManager.BATTERY_STATUS_UNKNOWN:
6856 item.append(checkin ? "?" : "unknown");
6857 break;
6858 case BatteryManager.BATTERY_STATUS_CHARGING:
6859 item.append(checkin ? "c" : "charging");
6860 break;
6861 case BatteryManager.BATTERY_STATUS_DISCHARGING:
6862 item.append(checkin ? "d" : "discharging");
6863 break;
6864 case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
6865 item.append(checkin ? "n" : "not-charging");
6866 break;
6867 case BatteryManager.BATTERY_STATUS_FULL:
6868 item.append(checkin ? "f" : "full");
6869 break;
6870 default:
6871 item.append(oldStatus);
6872 break;
6873 }
6874 }
6875 if (oldHealth != rec.batteryHealth) {
6876 oldHealth = rec.batteryHealth;
6877 item.append(checkin ? ",Bh=" : " health=");
6878 switch (oldHealth) {
6879 case BatteryManager.BATTERY_HEALTH_UNKNOWN:
6880 item.append(checkin ? "?" : "unknown");
6881 break;
6882 case BatteryManager.BATTERY_HEALTH_GOOD:
6883 item.append(checkin ? "g" : "good");
6884 break;
6885 case BatteryManager.BATTERY_HEALTH_OVERHEAT:
6886 item.append(checkin ? "h" : "overheat");
6887 break;
6888 case BatteryManager.BATTERY_HEALTH_DEAD:
6889 item.append(checkin ? "d" : "dead");
6890 break;
6891 case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
6892 item.append(checkin ? "v" : "over-voltage");
6893 break;
6894 case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
6895 item.append(checkin ? "f" : "failure");
6896 break;
6897 case BatteryManager.BATTERY_HEALTH_COLD:
6898 item.append(checkin ? "c" : "cold");
6899 break;
6900 default:
6901 item.append(oldHealth);
6902 break;
6903 }
6904 }
6905 if (oldPlug != rec.batteryPlugType) {
6906 oldPlug = rec.batteryPlugType;
6907 item.append(checkin ? ",Bp=" : " plug=");
6908 switch (oldPlug) {
6909 case 0:
6910 item.append(checkin ? "n" : "none");
6911 break;
6912 case BatteryManager.BATTERY_PLUGGED_AC:
6913 item.append(checkin ? "a" : "ac");
6914 break;
6915 case BatteryManager.BATTERY_PLUGGED_USB:
6916 item.append(checkin ? "u" : "usb");
6917 break;
6918 case BatteryManager.BATTERY_PLUGGED_WIRELESS:
6919 item.append(checkin ? "w" : "wireless");
6920 break;
6921 default:
6922 item.append(oldPlug);
6923 break;
6924 }
6925 }
6926 if (oldTemp != rec.batteryTemperature) {
6927 oldTemp = rec.batteryTemperature;
6928 item.append(checkin ? ",Bt=" : " temp=");
6929 item.append(oldTemp);
6930 }
6931 if (oldVolt != rec.batteryVoltage) {
6932 oldVolt = rec.batteryVoltage;
6933 item.append(checkin ? ",Bv=" : " volt=");
6934 item.append(oldVolt);
6935 }
6936 final int chargeMAh = rec.batteryChargeUah / 1000;
6937 if (oldChargeMAh != chargeMAh) {
6938 oldChargeMAh = chargeMAh;
6939 item.append(checkin ? ",Bcc=" : " charge=");
6940 item.append(oldChargeMAh);
6941 }
6942 if (oldModemRailChargeMah != rec.modemRailChargeMah) {
6943 oldModemRailChargeMah = rec.modemRailChargeMah;
6944 item.append(checkin ? ",Mrc=" : " modemRailChargemAh=");
6945 item.append(new DecimalFormat("#.##").format(oldModemRailChargeMah));
6946 }
6947 if (oldWifiRailChargeMah != rec.wifiRailChargeMah) {
6948 oldWifiRailChargeMah = rec.wifiRailChargeMah;
6949 item.append(checkin ? ",Wrc=" : " wifiRailChargemAh=");
6950 item.append(new DecimalFormat("#.##").format(oldWifiRailChargeMah));
6951 }
6952 printBitDescriptions(item, oldState, rec.states, rec.wakelockTag,
6953 HISTORY_STATE_DESCRIPTIONS, !checkin);
6954 printBitDescriptions(item, oldState2, rec.states2, null,
6955 HISTORY_STATE2_DESCRIPTIONS, !checkin);
6956 if (rec.wakeReasonTag != null) {
6957 if (checkin) {
6958 item.append(",wr=");
6959 item.append(rec.wakeReasonTag.poolIdx);
6960 } else {
6961 item.append(" wake_reason=");
6962 item.append(rec.wakeReasonTag.uid);
6963 item.append(":\"");
6964 item.append(rec.wakeReasonTag.string);
6965 item.append("\"");
6966 }
6967 }
6968 if (rec.eventCode != HistoryItem.EVENT_NONE) {
6969 item.append(checkin ? "," : " ");
6970 if ((rec.eventCode&HistoryItem.EVENT_FLAG_START) != 0) {
6971 item.append("+");
6972 } else if ((rec.eventCode&HistoryItem.EVENT_FLAG_FINISH) != 0) {
6973 item.append("-");
6974 }
6975 String[] eventNames = checkin ? HISTORY_EVENT_CHECKIN_NAMES
6976 : HISTORY_EVENT_NAMES;
6977 int idx = rec.eventCode & ~(HistoryItem.EVENT_FLAG_START
6978 | HistoryItem.EVENT_FLAG_FINISH);
6979 if (idx >= 0 && idx < eventNames.length) {
6980 item.append(eventNames[idx]);
6981 } else {
6982 item.append(checkin ? "Ev" : "event");
6983 item.append(idx);
6984 }
6985 item.append("=");
6986 if (checkin) {
6987 item.append(rec.eventTag.poolIdx);
6988 } else {
6989 item.append(HISTORY_EVENT_INT_FORMATTERS[idx]
6990 .applyAsString(rec.eventTag.uid));
6991 item.append(":\"");
6992 item.append(rec.eventTag.string);
6993 item.append("\"");
6994 }
6995 }
6996 item.append("\n");
6997 if (rec.stepDetails != null) {
6998 if (!checkin) {
6999 item.append(" Details: cpu=");
7000 item.append(rec.stepDetails.userTime);
7001 item.append("u+");
7002 item.append(rec.stepDetails.systemTime);
7003 item.append("s");
7004 if (rec.stepDetails.appCpuUid1 >= 0) {
7005 item.append(" (");
7006 printStepCpuUidDetails(item, rec.stepDetails.appCpuUid1,
7007 rec.stepDetails.appCpuUTime1, rec.stepDetails.appCpuSTime1);
7008 if (rec.stepDetails.appCpuUid2 >= 0) {
7009 item.append(", ");
7010 printStepCpuUidDetails(item, rec.stepDetails.appCpuUid2,
7011 rec.stepDetails.appCpuUTime2, rec.stepDetails.appCpuSTime2);
7012 }
7013 if (rec.stepDetails.appCpuUid3 >= 0) {
7014 item.append(", ");
7015 printStepCpuUidDetails(item, rec.stepDetails.appCpuUid3,
7016 rec.stepDetails.appCpuUTime3, rec.stepDetails.appCpuSTime3);
7017 }
7018 item.append(')');
7019 }
7020 item.append("\n");
7021 item.append(" /proc/stat=");
7022 item.append(rec.stepDetails.statUserTime);
7023 item.append(" usr, ");
7024 item.append(rec.stepDetails.statSystemTime);
7025 item.append(" sys, ");
7026 item.append(rec.stepDetails.statIOWaitTime);
7027 item.append(" io, ");
7028 item.append(rec.stepDetails.statIrqTime);
7029 item.append(" irq, ");
7030 item.append(rec.stepDetails.statSoftIrqTime);
7031 item.append(" sirq, ");
7032 item.append(rec.stepDetails.statIdlTime);
7033 item.append(" idle");
7034 int totalRun = rec.stepDetails.statUserTime + rec.stepDetails.statSystemTime
7035 + rec.stepDetails.statIOWaitTime + rec.stepDetails.statIrqTime
7036 + rec.stepDetails.statSoftIrqTime;
7037 int total = totalRun + rec.stepDetails.statIdlTime;
7038 if (total > 0) {
7039 item.append(" (");
7040 float perc = ((float)totalRun) / ((float)total) * 100;
7041 item.append(String.format("%.1f%%", perc));
7042 item.append(" of ");
7043 StringBuilder sb = new StringBuilder(64);
7044 formatTimeMsNoSpace(sb, total*10);
7045 item.append(sb);
7046 item.append(")");
7047 }
7048
7049 item.append(", SubsystemPowerState ");
7050 item.append(rec.stepDetails.statSubsystemPowerState);
7051 item.append("\n");
7052 } else {
7053 item.append(BATTERY_STATS_CHECKIN_VERSION); item.append(',');
7054 item.append(HISTORY_DATA); item.append(",0,Dcpu=");
7055 item.append(rec.stepDetails.userTime);
7056 item.append(":");
7057 item.append(rec.stepDetails.systemTime);
7058 if (rec.stepDetails.appCpuUid1 >= 0) {
7059 printStepCpuUidCheckinDetails(item, rec.stepDetails.appCpuUid1,
7060 rec.stepDetails.appCpuUTime1, rec.stepDetails.appCpuSTime1);
7061 if (rec.stepDetails.appCpuUid2 >= 0) {
7062 printStepCpuUidCheckinDetails(item, rec.stepDetails.appCpuUid2,
7063 rec.stepDetails.appCpuUTime2, rec.stepDetails.appCpuSTime2);
7064 }
7065 if (rec.stepDetails.appCpuUid3 >= 0) {
7066 printStepCpuUidCheckinDetails(item, rec.stepDetails.appCpuUid3,
7067 rec.stepDetails.appCpuUTime3, rec.stepDetails.appCpuSTime3);
7068 }
7069 }
7070 item.append("\n");
7071 item.append(BATTERY_STATS_CHECKIN_VERSION); item.append(',');
7072 item.append(HISTORY_DATA); item.append(",0,Dpst=");
7073 item.append(rec.stepDetails.statUserTime);
7074 item.append(',');
7075 item.append(rec.stepDetails.statSystemTime);
7076 item.append(',');
7077 item.append(rec.stepDetails.statIOWaitTime);
7078 item.append(',');
7079 item.append(rec.stepDetails.statIrqTime);
7080 item.append(',');
7081 item.append(rec.stepDetails.statSoftIrqTime);
7082 item.append(',');
7083 item.append(rec.stepDetails.statIdlTime);
7084 item.append(',');
7085
7086 if (rec.stepDetails.statSubsystemPowerState != null) {
7087 item.append(rec.stepDetails.statSubsystemPowerState);
7088 }
7089 item.append("\n");
7090 }
7091 }
7092 oldState = rec.states;
7093 oldState2 = rec.states2;
7094 // Clear High Tx Power Flag for volta positioning
7095 if ((rec.states2 & HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG) != 0) {
7096 rec.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
7097 }
7098 }
7099
7100 return item.toString();
7101 }
7102
7103 private void printStepCpuUidDetails(StringBuilder sb, int uid, int utime, int stime) {
7104 UserHandle.formatUid(sb, uid);
7105 sb.append("=");
7106 sb.append(utime);
7107 sb.append("u+");
7108 sb.append(stime);
7109 sb.append("s");
7110 }
7111
7112 private void printStepCpuUidCheckinDetails(StringBuilder sb, int uid, int utime,
7113 int stime) {
7114 sb.append('/');
7115 sb.append(uid);
7116 sb.append(":");
7117 sb.append(utime);
7118 sb.append(":");
7119 sb.append(stime);
7120 }
7121 }
7122
7123 private void printSizeValue(PrintWriter pw, long size) {
7124 float result = size;
7125 String suffix = "";
7126 if (result >= 10*1024) {
7127 suffix = "KB";
7128 result = result / 1024;
7129 }
7130 if (result >= 10*1024) {
7131 suffix = "MB";
7132 result = result / 1024;
7133 }
7134 if (result >= 10*1024) {
7135 suffix = "GB";
7136 result = result / 1024;
7137 }
7138 if (result >= 10*1024) {
7139 suffix = "TB";
7140 result = result / 1024;
7141 }
7142 if (result >= 10*1024) {
7143 suffix = "PB";
7144 result = result / 1024;
7145 }
7146 pw.print((int)result);
7147 pw.print(suffix);
7148 }
7149
7150 private static boolean dumpTimeEstimate(PrintWriter pw, String label1, String label2,
7151 String label3, long estimatedTime) {
7152 if (estimatedTime < 0) {
7153 return false;
7154 }
7155 pw.print(label1);
7156 pw.print(label2);
7157 pw.print(label3);
7158 StringBuilder sb = new StringBuilder(64);
7159 formatTimeMs(sb, estimatedTime);
7160 pw.print(sb);
7161 pw.println();
7162 return true;
7163 }
7164
7165 private static boolean dumpDurationSteps(PrintWriter pw, String prefix, String header,
7166 LevelStepTracker steps, boolean checkin) {
7167 if (steps == null) {
7168 return false;
7169 }
7170 int count = steps.mNumStepDurations;
7171 if (count <= 0) {
7172 return false;
7173 }
7174 if (!checkin) {
7175 pw.println(header);
7176 }
7177 String[] lineArgs = new String[5];
7178 for (int i=0; i<count; i++) {
7179 long duration = steps.getDurationAt(i);
7180 int level = steps.getLevelAt(i);
7181 long initMode = steps.getInitModeAt(i);
7182 long modMode = steps.getModModeAt(i);
7183 if (checkin) {
7184 lineArgs[0] = Long.toString(duration);
7185 lineArgs[1] = Integer.toString(level);
7186 if ((modMode&STEP_LEVEL_MODE_SCREEN_STATE) == 0) {
7187 switch ((int)(initMode&STEP_LEVEL_MODE_SCREEN_STATE) + 1) {
7188 case Display.STATE_OFF: lineArgs[2] = "s-"; break;
7189 case Display.STATE_ON: lineArgs[2] = "s+"; break;
7190 case Display.STATE_DOZE: lineArgs[2] = "sd"; break;
7191 case Display.STATE_DOZE_SUSPEND: lineArgs[2] = "sds"; break;
7192 default: lineArgs[2] = "?"; break;
7193 }
7194 } else {
7195 lineArgs[2] = "";
7196 }
7197 if ((modMode&STEP_LEVEL_MODE_POWER_SAVE) == 0) {
7198 lineArgs[3] = (initMode&STEP_LEVEL_MODE_POWER_SAVE) != 0 ? "p+" : "p-";
7199 } else {
7200 lineArgs[3] = "";
7201 }
7202 if ((modMode&STEP_LEVEL_MODE_DEVICE_IDLE) == 0) {
7203 lineArgs[4] = (initMode&STEP_LEVEL_MODE_DEVICE_IDLE) != 0 ? "i+" : "i-";
7204 } else {
7205 lineArgs[4] = "";
7206 }
7207 dumpLine(pw, 0 /* uid */, "i" /* category */, header, (Object[])lineArgs);
7208 } else {
7209 pw.print(prefix);
7210 pw.print("#"); pw.print(i); pw.print(": ");
7211 TimeUtils.formatDuration(duration, pw);
7212 pw.print(" to "); pw.print(level);
7213 boolean haveModes = false;
7214 if ((modMode&STEP_LEVEL_MODE_SCREEN_STATE) == 0) {
7215 pw.print(" (");
7216 switch ((int)(initMode&STEP_LEVEL_MODE_SCREEN_STATE) + 1) {
7217 case Display.STATE_OFF: pw.print("screen-off"); break;
7218 case Display.STATE_ON: pw.print("screen-on"); break;
7219 case Display.STATE_DOZE: pw.print("screen-doze"); break;
7220 case Display.STATE_DOZE_SUSPEND: pw.print("screen-doze-suspend"); break;
7221 default: pw.print("screen-?"); break;
7222 }
7223 haveModes = true;
7224 }
7225 if ((modMode&STEP_LEVEL_MODE_POWER_SAVE) == 0) {
7226 pw.print(haveModes ? ", " : " (");
7227 pw.print((initMode&STEP_LEVEL_MODE_POWER_SAVE) != 0
7228 ? "power-save-on" : "power-save-off");
7229 haveModes = true;
7230 }
7231 if ((modMode&STEP_LEVEL_MODE_DEVICE_IDLE) == 0) {
7232 pw.print(haveModes ? ", " : " (");
7233 pw.print((initMode&STEP_LEVEL_MODE_DEVICE_IDLE) != 0
7234 ? "device-idle-on" : "device-idle-off");
7235 haveModes = true;
7236 }
7237 if (haveModes) {
7238 pw.print(")");
7239 }
7240 pw.println();
7241 }
7242 }
7243 return true;
7244 }
7245
7246 private static void dumpDurationSteps(ProtoOutputStream proto, long fieldId,
7247 LevelStepTracker steps) {
7248 if (steps == null) {
7249 return;
7250 }
7251 int count = steps.mNumStepDurations;
7252 for (int i = 0; i < count; ++i) {
7253 long token = proto.start(fieldId);
7254 proto.write(SystemProto.BatteryLevelStep.DURATION_MS, steps.getDurationAt(i));
7255 proto.write(SystemProto.BatteryLevelStep.LEVEL, steps.getLevelAt(i));
7256
7257 final long initMode = steps.getInitModeAt(i);
7258 final long modMode = steps.getModModeAt(i);
7259
7260 int ds = SystemProto.BatteryLevelStep.DS_MIXED;
7261 if ((modMode & STEP_LEVEL_MODE_SCREEN_STATE) == 0) {
7262 switch ((int) (initMode & STEP_LEVEL_MODE_SCREEN_STATE) + 1) {
7263 case Display.STATE_OFF:
7264 ds = SystemProto.BatteryLevelStep.DS_OFF;
7265 break;
7266 case Display.STATE_ON:
7267 ds = SystemProto.BatteryLevelStep.DS_ON;
7268 break;
7269 case Display.STATE_DOZE:
7270 ds = SystemProto.BatteryLevelStep.DS_DOZE;
7271 break;
7272 case Display.STATE_DOZE_SUSPEND:
7273 ds = SystemProto.BatteryLevelStep.DS_DOZE_SUSPEND;
7274 break;
7275 default:
7276 ds = SystemProto.BatteryLevelStep.DS_ERROR;
7277 break;
7278 }
7279 }
7280 proto.write(SystemProto.BatteryLevelStep.DISPLAY_STATE, ds);
7281
7282 int psm = SystemProto.BatteryLevelStep.PSM_MIXED;
7283 if ((modMode & STEP_LEVEL_MODE_POWER_SAVE) == 0) {
7284 psm = (initMode & STEP_LEVEL_MODE_POWER_SAVE) != 0
7285 ? SystemProto.BatteryLevelStep.PSM_ON : SystemProto.BatteryLevelStep.PSM_OFF;
7286 }
7287 proto.write(SystemProto.BatteryLevelStep.POWER_SAVE_MODE, psm);
7288
7289 int im = SystemProto.BatteryLevelStep.IM_MIXED;
7290 if ((modMode & STEP_LEVEL_MODE_DEVICE_IDLE) == 0) {
7291 im = (initMode & STEP_LEVEL_MODE_DEVICE_IDLE) != 0
7292 ? SystemProto.BatteryLevelStep.IM_ON : SystemProto.BatteryLevelStep.IM_OFF;
7293 }
7294 proto.write(SystemProto.BatteryLevelStep.IDLE_MODE, im);
7295
7296 proto.end(token);
7297 }
7298 }
7299
7300 public static final int DUMP_CHARGED_ONLY = 1<<1;
7301 public static final int DUMP_DAILY_ONLY = 1<<2;
7302 public static final int DUMP_HISTORY_ONLY = 1<<3;
7303 public static final int DUMP_INCLUDE_HISTORY = 1<<4;
7304 public static final int DUMP_VERBOSE = 1<<5;
7305 public static final int DUMP_DEVICE_WIFI_ONLY = 1<<6;
7306
7307 private void dumpHistoryLocked(PrintWriter pw, int flags, long histStart, boolean checkin) {
7308 final HistoryPrinter hprinter = new HistoryPrinter();
7309 final HistoryItem rec = new HistoryItem();
7310 long lastTime = -1;
7311 long baseTime = -1;
7312 boolean printed = false;
7313 HistoryEventTracker tracker = null;
7314 while (getNextHistoryLocked(rec)) {
7315 lastTime = rec.time;
7316 if (baseTime < 0) {
7317 baseTime = lastTime;
7318 }
7319 if (rec.time >= histStart) {
7320 if (histStart >= 0 && !printed) {
7321 if (rec.cmd == HistoryItem.CMD_CURRENT_TIME
7322 || rec.cmd == HistoryItem.CMD_RESET
7323 || rec.cmd == HistoryItem.CMD_START
7324 || rec.cmd == HistoryItem.CMD_SHUTDOWN) {
7325 printed = true;
7326 hprinter.printNextItem(pw, rec, baseTime, checkin,
7327 (flags&DUMP_VERBOSE) != 0);
7328 rec.cmd = HistoryItem.CMD_UPDATE;
7329 } else if (rec.currentTime != 0) {
7330 printed = true;
7331 byte cmd = rec.cmd;
7332 rec.cmd = HistoryItem.CMD_CURRENT_TIME;
7333 hprinter.printNextItem(pw, rec, baseTime, checkin,
7334 (flags&DUMP_VERBOSE) != 0);
7335 rec.cmd = cmd;
7336 }
7337 if (tracker != null) {
7338 if (rec.cmd != HistoryItem.CMD_UPDATE) {
7339 hprinter.printNextItem(pw, rec, baseTime, checkin,
7340 (flags&DUMP_VERBOSE) != 0);
7341 rec.cmd = HistoryItem.CMD_UPDATE;
7342 }
7343 int oldEventCode = rec.eventCode;
7344 HistoryTag oldEventTag = rec.eventTag;
7345 rec.eventTag = new HistoryTag();
7346 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
7347 HashMap<String, SparseIntArray> active
7348 = tracker.getStateForEvent(i);
7349 if (active == null) {
7350 continue;
7351 }
7352 for (HashMap.Entry<String, SparseIntArray> ent
7353 : active.entrySet()) {
7354 SparseIntArray uids = ent.getValue();
7355 for (int j=0; j<uids.size(); j++) {
7356 rec.eventCode = i;
7357 rec.eventTag.string = ent.getKey();
7358 rec.eventTag.uid = uids.keyAt(j);
7359 rec.eventTag.poolIdx = uids.valueAt(j);
7360 hprinter.printNextItem(pw, rec, baseTime, checkin,
7361 (flags&DUMP_VERBOSE) != 0);
7362 rec.wakeReasonTag = null;
7363 rec.wakelockTag = null;
7364 }
7365 }
7366 }
7367 rec.eventCode = oldEventCode;
7368 rec.eventTag = oldEventTag;
7369 tracker = null;
7370 }
7371 }
7372 hprinter.printNextItem(pw, rec, baseTime, checkin,
7373 (flags&DUMP_VERBOSE) != 0);
7374 } else if (false && rec.eventCode != HistoryItem.EVENT_NONE) {
7375 // This is an attempt to aggregate the previous state and generate
7376 // fake events to reflect that state at the point where we start
7377 // printing real events. It doesn't really work right, so is turned off.
7378 if (tracker == null) {
7379 tracker = new HistoryEventTracker();
7380 }
7381 tracker.updateState(rec.eventCode, rec.eventTag.string,
7382 rec.eventTag.uid, rec.eventTag.poolIdx);
7383 }
7384 }
7385 if (histStart >= 0) {
7386 commitCurrentHistoryBatchLocked();
7387 pw.print(checkin ? "NEXT: " : " NEXT: "); pw.println(lastTime+1);
7388 }
7389 }
7390
7391 private void dumpDailyLevelStepSummary(PrintWriter pw, String prefix, String label,
7392 LevelStepTracker steps, StringBuilder tmpSb, int[] tmpOutInt) {
7393 if (steps == null) {
7394 return;
7395 }
7396 long timeRemaining = steps.computeTimeEstimate(0, 0, tmpOutInt);
7397 if (timeRemaining >= 0) {
7398 pw.print(prefix); pw.print(label); pw.print(" total time: ");
7399 tmpSb.setLength(0);
7400 formatTimeMs(tmpSb, timeRemaining);
7401 pw.print(tmpSb);
7402 pw.print(" (from "); pw.print(tmpOutInt[0]);
7403 pw.println(" steps)");
7404 }
7405 for (int i=0; i< STEP_LEVEL_MODES_OF_INTEREST.length; i++) {
7406 long estimatedTime = steps.computeTimeEstimate(STEP_LEVEL_MODES_OF_INTEREST[i],
7407 STEP_LEVEL_MODE_VALUES[i], tmpOutInt);
7408 if (estimatedTime > 0) {
7409 pw.print(prefix); pw.print(label); pw.print(" ");
7410 pw.print(STEP_LEVEL_MODE_LABELS[i]);
7411 pw.print(" time: ");
7412 tmpSb.setLength(0);
7413 formatTimeMs(tmpSb, estimatedTime);
7414 pw.print(tmpSb);
7415 pw.print(" (from "); pw.print(tmpOutInt[0]);
7416 pw.println(" steps)");
7417 }
7418 }
7419 }
7420
7421 private void dumpDailyPackageChanges(PrintWriter pw, String prefix,
7422 ArrayList<PackageChange> changes) {
7423 if (changes == null) {
7424 return;
7425 }
7426 pw.print(prefix); pw.println("Package changes:");
7427 for (int i=0; i<changes.size(); i++) {
7428 PackageChange pc = changes.get(i);
7429 if (pc.mUpdate) {
7430 pw.print(prefix); pw.print(" Update "); pw.print(pc.mPackageName);
7431 pw.print(" vers="); pw.println(pc.mVersionCode);
7432 } else {
7433 pw.print(prefix); pw.print(" Uninstall "); pw.println(pc.mPackageName);
7434 }
7435 }
7436 }
7437
7438 /**
7439 * Dumps a human-readable summary of the battery statistics to the given PrintWriter.
7440 *
7441 * @param pw a Printer to receive the dump output.
7442 */
7443 @SuppressWarnings("unused")
7444 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
7445 prepareForDumpLocked();
7446
7447 final boolean filtering = (flags
7448 & (DUMP_HISTORY_ONLY|DUMP_CHARGED_ONLY|DUMP_DAILY_ONLY)) != 0;
7449
7450 if ((flags&DUMP_HISTORY_ONLY) != 0 || !filtering) {
7451 final long historyTotalSize = getHistoryTotalSize();
7452 final long historyUsedSize = getHistoryUsedSize();
7453 if (startIteratingHistoryLocked()) {
7454 try {
7455 pw.print("Battery History (");
7456 pw.print((100*historyUsedSize)/historyTotalSize);
7457 pw.print("% used, ");
7458 printSizeValue(pw, historyUsedSize);
7459 pw.print(" used of ");
7460 printSizeValue(pw, historyTotalSize);
7461 pw.print(", ");
7462 pw.print(getHistoryStringPoolSize());
7463 pw.print(" strings using ");
7464 printSizeValue(pw, getHistoryStringPoolBytes());
7465 pw.println("):");
7466 dumpHistoryLocked(pw, flags, histStart, false);
7467 pw.println();
7468 } finally {
7469 finishIteratingHistoryLocked();
7470 }
7471 }
7472 }
7473
7474 if (filtering && (flags&(DUMP_CHARGED_ONLY|DUMP_DAILY_ONLY)) == 0) {
7475 return;
7476 }
7477
7478 if (!filtering) {
7479 SparseArray<? extends Uid> uidStats = getUidStats();
7480 final int NU = uidStats.size();
7481 boolean didPid = false;
7482 long nowRealtime = SystemClock.elapsedRealtime();
7483 for (int i=0; i<NU; i++) {
7484 Uid uid = uidStats.valueAt(i);
7485 SparseArray<? extends Uid.Pid> pids = uid.getPidStats();
7486 if (pids != null) {
7487 for (int j=0; j<pids.size(); j++) {
7488 Uid.Pid pid = pids.valueAt(j);
7489 if (!didPid) {
7490 pw.println("Per-PID Stats:");
7491 didPid = true;
7492 }
7493 long time = pid.mWakeSumMs + (pid.mWakeNesting > 0
7494 ? (nowRealtime - pid.mWakeStartMs) : 0);
7495 pw.print(" PID "); pw.print(pids.keyAt(j));
7496 pw.print(" wake time: ");
7497 TimeUtils.formatDuration(time, pw);
7498 pw.println("");
7499 }
7500 }
7501 }
7502 if (didPid) {
7503 pw.println();
7504 }
7505 }
7506
7507 if (!filtering || (flags&DUMP_CHARGED_ONLY) != 0) {
7508 if (dumpDurationSteps(pw, " ", "Discharge step durations:",
7509 getDischargeLevelStepTracker(), false)) {
7510 long timeRemaining = computeBatteryTimeRemaining(
7511 SystemClock.elapsedRealtime() * 1000);
7512 if (timeRemaining >= 0) {
7513 pw.print(" Estimated discharge time remaining: ");
7514 TimeUtils.formatDuration(timeRemaining / 1000, pw);
7515 pw.println();
7516 }
7517 final LevelStepTracker steps = getDischargeLevelStepTracker();
7518 for (int i=0; i< STEP_LEVEL_MODES_OF_INTEREST.length; i++) {
7519 dumpTimeEstimate(pw, " Estimated ", STEP_LEVEL_MODE_LABELS[i], " time: ",
7520 steps.computeTimeEstimate(STEP_LEVEL_MODES_OF_INTEREST[i],
7521 STEP_LEVEL_MODE_VALUES[i], null));
7522 }
7523 pw.println();
7524 }
7525 if (dumpDurationSteps(pw, " ", "Charge step durations:",
7526 getChargeLevelStepTracker(), false)) {
7527 long timeRemaining = computeChargeTimeRemaining(
7528 SystemClock.elapsedRealtime() * 1000);
7529 if (timeRemaining >= 0) {
7530 pw.print(" Estimated charge time remaining: ");
7531 TimeUtils.formatDuration(timeRemaining / 1000, pw);
7532 pw.println();
7533 }
7534 pw.println();
7535 }
7536 }
7537 if (!filtering || (flags & DUMP_DAILY_ONLY) != 0) {
7538 pw.println("Daily stats:");
7539 pw.print(" Current start time: ");
7540 pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss",
7541 getCurrentDailyStartTime()).toString());
7542 pw.print(" Next min deadline: ");
7543 pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss",
7544 getNextMinDailyDeadline()).toString());
7545 pw.print(" Next max deadline: ");
7546 pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss",
7547 getNextMaxDailyDeadline()).toString());
7548 StringBuilder sb = new StringBuilder(64);
7549 int[] outInt = new int[1];
7550 LevelStepTracker dsteps = getDailyDischargeLevelStepTracker();
7551 LevelStepTracker csteps = getDailyChargeLevelStepTracker();
7552 ArrayList<PackageChange> pkgc = getDailyPackageChanges();
7553 if (dsteps.mNumStepDurations > 0 || csteps.mNumStepDurations > 0 || pkgc != null) {
7554 if ((flags&DUMP_DAILY_ONLY) != 0 || !filtering) {
7555 if (dumpDurationSteps(pw, " ", " Current daily discharge step durations:",
7556 dsteps, false)) {
7557 dumpDailyLevelStepSummary(pw, " ", "Discharge", dsteps,
7558 sb, outInt);
7559 }
7560 if (dumpDurationSteps(pw, " ", " Current daily charge step durations:",
7561 csteps, false)) {
7562 dumpDailyLevelStepSummary(pw, " ", "Charge", csteps,
7563 sb, outInt);
7564 }
7565 dumpDailyPackageChanges(pw, " ", pkgc);
7566 } else {
7567 pw.println(" Current daily steps:");
7568 dumpDailyLevelStepSummary(pw, " ", "Discharge", dsteps,
7569 sb, outInt);
7570 dumpDailyLevelStepSummary(pw, " ", "Charge", csteps,
7571 sb, outInt);
7572 }
7573 }
7574 DailyItem dit;
7575 int curIndex = 0;
7576 while ((dit=getDailyItemLocked(curIndex)) != null) {
7577 curIndex++;
7578 if ((flags&DUMP_DAILY_ONLY) != 0) {
7579 pw.println();
7580 }
7581 pw.print(" Daily from ");
7582 pw.print(DateFormat.format("yyyy-MM-dd-HH-mm-ss", dit.mStartTime).toString());
7583 pw.print(" to ");
7584 pw.print(DateFormat.format("yyyy-MM-dd-HH-mm-ss", dit.mEndTime).toString());
7585 pw.println(":");
7586 if ((flags&DUMP_DAILY_ONLY) != 0 || !filtering) {
7587 if (dumpDurationSteps(pw, " ",
7588 " Discharge step durations:", dit.mDischargeSteps, false)) {
7589 dumpDailyLevelStepSummary(pw, " ", "Discharge", dit.mDischargeSteps,
7590 sb, outInt);
7591 }
7592 if (dumpDurationSteps(pw, " ",
7593 " Charge step durations:", dit.mChargeSteps, false)) {
7594 dumpDailyLevelStepSummary(pw, " ", "Charge", dit.mChargeSteps,
7595 sb, outInt);
7596 }
7597 dumpDailyPackageChanges(pw, " ", dit.mPackageChanges);
7598 } else {
7599 dumpDailyLevelStepSummary(pw, " ", "Discharge", dit.mDischargeSteps,
7600 sb, outInt);
7601 dumpDailyLevelStepSummary(pw, " ", "Charge", dit.mChargeSteps,
7602 sb, outInt);
7603 }
7604 }
7605 pw.println();
7606 }
7607 if (!filtering || (flags&DUMP_CHARGED_ONLY) != 0) {
7608 pw.println("Statistics since last charge:");
7609 pw.println(" System starts: " + getStartCount()
7610 + ", currently on battery: " + getIsOnBattery());
7611 dumpLocked(context, pw, "", STATS_SINCE_CHARGED, reqUid,
7612 (flags&DUMP_DEVICE_WIFI_ONLY) != 0);
7613 pw.println();
7614 }
7615 }
7616
7617 // This is called from BatteryStatsService.
7618 @SuppressWarnings("unused")
7619 public void dumpCheckinLocked(Context context, PrintWriter pw,
7620 List<ApplicationInfo> apps, int flags, long histStart) {
7621 prepareForDumpLocked();
7622
7623 dumpLine(pw, 0 /* uid */, "i" /* category */, VERSION_DATA,
7624 CHECKIN_VERSION, getParcelVersion(), getStartPlatformVersion(),
7625 getEndPlatformVersion());
7626
7627 long now = getHistoryBaseTime() + SystemClock.elapsedRealtime();
7628
7629 if ((flags & (DUMP_INCLUDE_HISTORY | DUMP_HISTORY_ONLY)) != 0) {
7630 if (startIteratingHistoryLocked()) {
7631 try {
7632 for (int i=0; i<getHistoryStringPoolSize(); i++) {
7633 pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
7634 pw.print(HISTORY_STRING_POOL); pw.print(',');
7635 pw.print(i);
7636 pw.print(",");
7637 pw.print(getHistoryTagPoolUid(i));
7638 pw.print(",\"");
7639 String str = getHistoryTagPoolString(i);
7640 if (str != null) {
7641 str = str.replace("\\", "\\\\");
7642 str = str.replace("\"", "\\\"");
7643 pw.print(str);
7644 }
7645 pw.print("\"");
7646 pw.println();
7647 }
7648 dumpHistoryLocked(pw, flags, histStart, true);
7649 } finally {
7650 finishIteratingHistoryLocked();
7651 }
7652 }
7653 }
7654
7655 if ((flags & DUMP_HISTORY_ONLY) != 0) {
7656 return;
7657 }
7658
7659 if (apps != null) {
7660 SparseArray<Pair<ArrayList<String>, MutableBoolean>> uids = new SparseArray<>();
7661 for (int i=0; i<apps.size(); i++) {
7662 ApplicationInfo ai = apps.get(i);
7663 Pair<ArrayList<String>, MutableBoolean> pkgs = uids.get(
7664 UserHandle.getAppId(ai.uid));
7665 if (pkgs == null) {
7666 pkgs = new Pair<>(new ArrayList<String>(), new MutableBoolean(false));
7667 uids.put(UserHandle.getAppId(ai.uid), pkgs);
7668 }
7669 pkgs.first.add(ai.packageName);
7670 }
7671 SparseArray<? extends Uid> uidStats = getUidStats();
7672 final int NU = uidStats.size();
7673 String[] lineArgs = new String[2];
7674 for (int i=0; i<NU; i++) {
7675 int uid = UserHandle.getAppId(uidStats.keyAt(i));
7676 Pair<ArrayList<String>, MutableBoolean> pkgs = uids.get(uid);
7677 if (pkgs != null && !pkgs.second.value) {
7678 pkgs.second.value = true;
7679 for (int j=0; j<pkgs.first.size(); j++) {
7680 lineArgs[0] = Integer.toString(uid);
7681 lineArgs[1] = pkgs.first.get(j);
7682 dumpLine(pw, 0 /* uid */, "i" /* category */, UID_DATA,
7683 (Object[])lineArgs);
7684 }
7685 }
7686 }
7687 }
7688 if ((flags & DUMP_DAILY_ONLY) == 0) {
7689 dumpDurationSteps(pw, "", DISCHARGE_STEP_DATA, getDischargeLevelStepTracker(), true);
7690 String[] lineArgs = new String[1];
7691 long timeRemaining = computeBatteryTimeRemaining(SystemClock.elapsedRealtime() * 1000);
7692 if (timeRemaining >= 0) {
7693 lineArgs[0] = Long.toString(timeRemaining);
7694 dumpLine(pw, 0 /* uid */, "i" /* category */, DISCHARGE_TIME_REMAIN_DATA,
7695 (Object[])lineArgs);
7696 }
7697 dumpDurationSteps(pw, "", CHARGE_STEP_DATA, getChargeLevelStepTracker(), true);
7698 timeRemaining = computeChargeTimeRemaining(SystemClock.elapsedRealtime() * 1000);
7699 if (timeRemaining >= 0) {
7700 lineArgs[0] = Long.toString(timeRemaining);
7701 dumpLine(pw, 0 /* uid */, "i" /* category */, CHARGE_TIME_REMAIN_DATA,
7702 (Object[])lineArgs);
7703 }
7704 dumpCheckinLocked(context, pw, STATS_SINCE_CHARGED, -1,
7705 (flags&DUMP_DEVICE_WIFI_ONLY) != 0);
7706 }
7707 }
7708
7709 /**
7710 * Dump #STATS_SINCE_CHARGED batterystats data to a proto. If the flags include
7711 * DUMP_INCLUDE_HISTORY or DUMP_HISTORY_ONLY, only the history will be dumped.
7712 * @hide
7713 */
7714 public void dumpProtoLocked(Context context, FileDescriptor fd, List<ApplicationInfo> apps,
7715 int flags, long histStart) {
7716 final ProtoOutputStream proto = new ProtoOutputStream(fd);
7717 prepareForDumpLocked();
7718
7719 if ((flags & (DUMP_INCLUDE_HISTORY | DUMP_HISTORY_ONLY)) != 0) {
7720 dumpProtoHistoryLocked(proto, flags, histStart);
7721 proto.flush();
7722 return;
7723 }
7724
7725 final long bToken = proto.start(BatteryStatsServiceDumpProto.BATTERYSTATS);
7726
7727 proto.write(BatteryStatsProto.REPORT_VERSION, CHECKIN_VERSION);
7728 proto.write(BatteryStatsProto.PARCEL_VERSION, getParcelVersion());
7729 proto.write(BatteryStatsProto.START_PLATFORM_VERSION, getStartPlatformVersion());
7730 proto.write(BatteryStatsProto.END_PLATFORM_VERSION, getEndPlatformVersion());
7731
7732 if ((flags & DUMP_DAILY_ONLY) == 0) {
7733 final BatteryUsageStats stats = getBatteryUsageStats(context);
7734 ProportionalAttributionCalculator proportionalAttributionCalculator =
7735 new ProportionalAttributionCalculator(context, stats);
7736 dumpProtoAppsLocked(proto, stats, apps, proportionalAttributionCalculator);
7737 dumpProtoSystemLocked(proto, stats);
7738 }
7739
7740 proto.end(bToken);
7741 proto.flush();
7742 }
7743
7744 private void dumpProtoAppsLocked(ProtoOutputStream proto, BatteryUsageStats stats,
7745 List<ApplicationInfo> apps,
7746 ProportionalAttributionCalculator proportionalAttributionCalculator) {
7747 final int which = STATS_SINCE_CHARGED;
7748 final long rawUptimeUs = SystemClock.uptimeMillis() * 1000;
7749 final long rawRealtimeMs = SystemClock.elapsedRealtime();
7750 final long rawRealtimeUs = rawRealtimeMs * 1000;
7751 final long batteryUptimeUs = getBatteryUptime(rawUptimeUs);
7752
7753 SparseArray<ArrayList<String>> aidToPackages = new SparseArray<>();
7754 if (apps != null) {
7755 for (int i = 0; i < apps.size(); ++i) {
7756 ApplicationInfo ai = apps.get(i);
7757 int aid = UserHandle.getAppId(ai.uid);
7758 ArrayList<String> pkgs = aidToPackages.get(aid);
7759 if (pkgs == null) {
7760 pkgs = new ArrayList<String>();
7761 aidToPackages.put(aid, pkgs);
7762 }
7763 pkgs.add(ai.packageName);
7764 }
7765 }
7766
7767 SparseArray<UidBatteryConsumer> uidToConsumer = new SparseArray<>();
7768 final List<UidBatteryConsumer> consumers = stats.getUidBatteryConsumers();
7769 for (int i = consumers.size() - 1; i >= 0; --i) {
7770 final UidBatteryConsumer bs = consumers.get(i);
7771 uidToConsumer.put(bs.getUid(), bs);
7772 }
7773
7774 SparseArray<? extends Uid> uidStats = getUidStats();
7775 final int n = uidStats.size();
7776 for (int iu = 0; iu < n; ++iu) {
7777 final long uTkn = proto.start(BatteryStatsProto.UIDS);
7778 final Uid u = uidStats.valueAt(iu);
7779
7780 final int uid = uidStats.keyAt(iu);
7781 proto.write(UidProto.UID, uid);
7782
7783 // Print packages and apk stats (UID_DATA & APK_DATA)
7784 ArrayList<String> pkgs = aidToPackages.get(UserHandle.getAppId(uid));
7785 if (pkgs == null) {
7786 pkgs = new ArrayList<String>();
7787 }
7788 final ArrayMap<String, ? extends BatteryStats.Uid.Pkg> packageStats =
7789 u.getPackageStats();
7790 for (int ipkg = packageStats.size() - 1; ipkg >= 0; --ipkg) {
7791 String pkg = packageStats.keyAt(ipkg);
7792 final ArrayMap<String, ? extends Uid.Pkg.Serv> serviceStats =
7793 packageStats.valueAt(ipkg).getServiceStats();
7794 if (serviceStats.size() == 0) {
7795 // Due to the way ActivityManagerService logs wakeup alarms, some packages (for
7796 // example, "android") may be included in the packageStats that aren't part of
7797 // the UID. If they don't have any services, then they shouldn't be listed here.
7798 // These packages won't be a part in the pkgs List.
7799 continue;
7800 }
7801
7802 final long pToken = proto.start(UidProto.PACKAGES);
7803 proto.write(UidProto.Package.NAME, pkg);
7804 // Remove from the packages list since we're logging it here.
7805 pkgs.remove(pkg);
7806
7807 for (int isvc = serviceStats.size() - 1; isvc >= 0; --isvc) {
7808 final BatteryStats.Uid.Pkg.Serv ss = serviceStats.valueAt(isvc);
7809
7810 final long startTimeMs = roundUsToMs(ss.getStartTime(batteryUptimeUs, which));
7811 final int starts = ss.getStarts(which);
7812 final int launches = ss.getLaunches(which);
7813 if (startTimeMs == 0 && starts == 0 && launches == 0) {
7814 continue;
7815 }
7816
7817 long sToken = proto.start(UidProto.Package.SERVICES);
7818
7819 proto.write(UidProto.Package.Service.NAME, serviceStats.keyAt(isvc));
7820 proto.write(UidProto.Package.Service.START_DURATION_MS, startTimeMs);
7821 proto.write(UidProto.Package.Service.START_COUNT, starts);
7822 proto.write(UidProto.Package.Service.LAUNCH_COUNT, launches);
7823
7824 proto.end(sToken);
7825 }
7826 proto.end(pToken);
7827 }
7828 // Print any remaining packages that weren't in the packageStats map. pkgs is pulled
7829 // from PackageManager data. Packages are only included in packageStats if there was
7830 // specific data tracked for them (services and wakeup alarms, etc.).
7831 for (String p : pkgs) {
7832 final long pToken = proto.start(UidProto.PACKAGES);
7833 proto.write(UidProto.Package.NAME, p);
7834 proto.end(pToken);
7835 }
7836
7837 // Total wakelock data (AGGREGATED_WAKELOCK_DATA)
7838 if (u.getAggregatedPartialWakelockTimer() != null) {
7839 final Timer timer = u.getAggregatedPartialWakelockTimer();
7840 // Times are since reset (regardless of 'which')
7841 final long totTimeMs = timer.getTotalDurationMsLocked(rawRealtimeMs);
7842 final Timer bgTimer = timer.getSubTimer();
7843 final long bgTimeMs = bgTimer != null
7844 ? bgTimer.getTotalDurationMsLocked(rawRealtimeMs) : 0;
7845 final long awToken = proto.start(UidProto.AGGREGATED_WAKELOCK);
7846 proto.write(UidProto.AggregatedWakelock.PARTIAL_DURATION_MS, totTimeMs);
7847 proto.write(UidProto.AggregatedWakelock.BACKGROUND_PARTIAL_DURATION_MS, bgTimeMs);
7848 proto.end(awToken);
7849 }
7850
7851 // Audio (AUDIO_DATA)
7852 dumpTimer(proto, UidProto.AUDIO, u.getAudioTurnedOnTimer(), rawRealtimeUs, which);
7853
7854 // Bluetooth Controller (BLUETOOTH_CONTROLLER_DATA)
7855 dumpControllerActivityProto(proto, UidProto.BLUETOOTH_CONTROLLER,
7856 u.getBluetoothControllerActivity(), which);
7857
7858 // BLE scans (BLUETOOTH_MISC_DATA) (uses totalDurationMsLocked and MaxDurationMsLocked)
7859 final Timer bleTimer = u.getBluetoothScanTimer();
7860 if (bleTimer != null) {
7861 final long bmToken = proto.start(UidProto.BLUETOOTH_MISC);
7862
7863 dumpTimer(proto, UidProto.BluetoothMisc.APPORTIONED_BLE_SCAN, bleTimer,
7864 rawRealtimeUs, which);
7865 dumpTimer(proto, UidProto.BluetoothMisc.BACKGROUND_BLE_SCAN,
7866 u.getBluetoothScanBackgroundTimer(), rawRealtimeUs, which);
7867 // Unoptimized scan timer. Unpooled and since reset (regardless of 'which').
7868 dumpTimer(proto, UidProto.BluetoothMisc.UNOPTIMIZED_BLE_SCAN,
7869 u.getBluetoothUnoptimizedScanTimer(), rawRealtimeUs, which);
7870 // Unoptimized bg scan timer. Unpooled and since reset (regardless of 'which').
7871 dumpTimer(proto, UidProto.BluetoothMisc.BACKGROUND_UNOPTIMIZED_BLE_SCAN,
7872 u.getBluetoothUnoptimizedScanBackgroundTimer(), rawRealtimeUs, which);
7873 // Result counters
7874 proto.write(UidProto.BluetoothMisc.BLE_SCAN_RESULT_COUNT,
7875 u.getBluetoothScanResultCounter() != null
7876 ? u.getBluetoothScanResultCounter().getCountLocked(which) : 0);
7877 proto.write(UidProto.BluetoothMisc.BACKGROUND_BLE_SCAN_RESULT_COUNT,
7878 u.getBluetoothScanResultBgCounter() != null
7879 ? u.getBluetoothScanResultBgCounter().getCountLocked(which) : 0);
7880
7881 proto.end(bmToken);
7882 }
7883
7884 // Camera (CAMERA_DATA)
7885 dumpTimer(proto, UidProto.CAMERA, u.getCameraTurnedOnTimer(), rawRealtimeUs, which);
7886
7887 // CPU stats (CPU_DATA & CPU_TIMES_AT_FREQ_DATA)
7888 final long cpuToken = proto.start(UidProto.CPU);
7889 proto.write(UidProto.Cpu.USER_DURATION_MS, roundUsToMs(u.getUserCpuTimeUs(which)));
7890 proto.write(UidProto.Cpu.SYSTEM_DURATION_MS, roundUsToMs(u.getSystemCpuTimeUs(which)));
7891
7892 final long[] cpuFreqs = getCpuFreqs();
7893 if (cpuFreqs != null) {
7894 final long[] cpuFreqTimeMs = u.getCpuFreqTimes(which);
7895 // If total cpuFreqTimes is null, then we don't need to check for
7896 // screenOffCpuFreqTimes.
7897 if (cpuFreqTimeMs != null && cpuFreqTimeMs.length == cpuFreqs.length) {
7898 long[] screenOffCpuFreqTimeMs = u.getScreenOffCpuFreqTimes(which);
7899 if (screenOffCpuFreqTimeMs == null) {
7900 screenOffCpuFreqTimeMs = new long[cpuFreqTimeMs.length];
7901 }
7902 for (int ic = 0; ic < cpuFreqTimeMs.length; ++ic) {
7903 long cToken = proto.start(UidProto.Cpu.BY_FREQUENCY);
7904 proto.write(UidProto.Cpu.ByFrequency.FREQUENCY_INDEX, ic + 1);
7905 proto.write(UidProto.Cpu.ByFrequency.TOTAL_DURATION_MS,
7906 cpuFreqTimeMs[ic]);
7907 proto.write(UidProto.Cpu.ByFrequency.SCREEN_OFF_DURATION_MS,
7908 screenOffCpuFreqTimeMs[ic]);
7909 proto.end(cToken);
7910 }
7911 }
7912 }
7913
7914 final long[] timesInFreqMs = new long[getCpuFreqCount()];
7915 final long[] timesInFreqScreenOffMs = new long[getCpuFreqCount()];
7916 for (int procState = 0; procState < Uid.NUM_PROCESS_STATE; ++procState) {
7917 if (u.getCpuFreqTimes(timesInFreqMs, procState)) {
7918 if (!u.getScreenOffCpuFreqTimes(timesInFreqScreenOffMs, procState)) {
7919 Arrays.fill(timesInFreqScreenOffMs, 0);
7920 }
7921 final long procToken = proto.start(UidProto.Cpu.BY_PROCESS_STATE);
7922 proto.write(UidProto.Cpu.ByProcessState.PROCESS_STATE, procState);
7923 for (int ic = 0; ic < timesInFreqMs.length; ++ic) {
7924 long cToken = proto.start(UidProto.Cpu.ByProcessState.BY_FREQUENCY);
7925 proto.write(UidProto.Cpu.ByFrequency.FREQUENCY_INDEX, ic + 1);
7926 proto.write(UidProto.Cpu.ByFrequency.TOTAL_DURATION_MS,
7927 timesInFreqMs[ic]);
7928 proto.write(UidProto.Cpu.ByFrequency.SCREEN_OFF_DURATION_MS,
7929 timesInFreqScreenOffMs[ic]);
7930 proto.end(cToken);
7931 }
7932 proto.end(procToken);
7933 }
7934 }
7935 proto.end(cpuToken);
7936
7937 // Flashlight (FLASHLIGHT_DATA)
7938 dumpTimer(proto, UidProto.FLASHLIGHT, u.getFlashlightTurnedOnTimer(),
7939 rawRealtimeUs, which);
7940
7941 // Foreground activity (FOREGROUND_ACTIVITY_DATA)
7942 dumpTimer(proto, UidProto.FOREGROUND_ACTIVITY, u.getForegroundActivityTimer(),
7943 rawRealtimeUs, which);
7944
7945 // Foreground service (FOREGROUND_SERVICE_DATA)
7946 dumpTimer(proto, UidProto.FOREGROUND_SERVICE, u.getForegroundServiceTimer(),
7947 rawRealtimeUs, which);
7948
7949 // Job completion (JOB_COMPLETION_DATA)
7950 final ArrayMap<String, SparseIntArray> completions = u.getJobCompletionStats();
7951 for (int ic = 0; ic < completions.size(); ++ic) {
7952 SparseIntArray types = completions.valueAt(ic);
7953 if (types != null) {
7954 final long jcToken = proto.start(UidProto.JOB_COMPLETION);
7955
7956 proto.write(UidProto.JobCompletion.NAME, completions.keyAt(ic));
7957
7958 for (int r : JobParameters.getJobStopReasonCodes()) {
7959 long rToken = proto.start(UidProto.JobCompletion.REASON_COUNT);
7960 proto.write(UidProto.JobCompletion.ReasonCount.NAME, r);
7961 proto.write(UidProto.JobCompletion.ReasonCount.COUNT, types.get(r, 0));
7962 proto.end(rToken);
7963 }
7964
7965 proto.end(jcToken);
7966 }
7967 }
7968
7969 // Scheduled jobs (JOB_DATA)
7970 final ArrayMap<String, ? extends Timer> jobs = u.getJobStats();
7971 for (int ij = jobs.size() - 1; ij >= 0; --ij) {
7972 final Timer timer = jobs.valueAt(ij);
7973 final Timer bgTimer = timer.getSubTimer();
7974 final long jToken = proto.start(UidProto.JOBS);
7975
7976 proto.write(UidProto.Job.NAME, jobs.keyAt(ij));
7977 // Background uses totalDurationMsLocked, while total uses totalTimeLocked
7978 dumpTimer(proto, UidProto.Job.TOTAL, timer, rawRealtimeUs, which);
7979 dumpTimer(proto, UidProto.Job.BACKGROUND, bgTimer, rawRealtimeUs, which);
7980
7981 proto.end(jToken);
7982 }
7983
7984 // Modem Controller (MODEM_CONTROLLER_DATA)
7985 dumpControllerActivityProto(proto, UidProto.MODEM_CONTROLLER,
7986 u.getModemControllerActivity(), which);
7987
7988 // Network stats (NETWORK_DATA)
7989 final long nToken = proto.start(UidProto.NETWORK);
7990 proto.write(UidProto.Network.MOBILE_BYTES_RX,
7991 u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
7992 proto.write(UidProto.Network.MOBILE_BYTES_TX,
7993 u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
7994 proto.write(UidProto.Network.WIFI_BYTES_RX,
7995 u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
7996 proto.write(UidProto.Network.WIFI_BYTES_TX,
7997 u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
7998 proto.write(UidProto.Network.BT_BYTES_RX,
7999 u.getNetworkActivityBytes(NETWORK_BT_RX_DATA, which));
8000 proto.write(UidProto.Network.BT_BYTES_TX,
8001 u.getNetworkActivityBytes(NETWORK_BT_TX_DATA, which));
8002 proto.write(UidProto.Network.MOBILE_PACKETS_RX,
8003 u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
8004 proto.write(UidProto.Network.MOBILE_PACKETS_TX,
8005 u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
8006 proto.write(UidProto.Network.WIFI_PACKETS_RX,
8007 u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
8008 proto.write(UidProto.Network.WIFI_PACKETS_TX,
8009 u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
8010 proto.write(UidProto.Network.MOBILE_ACTIVE_DURATION_MS,
8011 roundUsToMs(u.getMobileRadioActiveTime(which)));
8012 proto.write(UidProto.Network.MOBILE_ACTIVE_COUNT,
8013 u.getMobileRadioActiveCount(which));
8014 proto.write(UidProto.Network.MOBILE_WAKEUP_COUNT,
8015 u.getMobileRadioApWakeupCount(which));
8016 proto.write(UidProto.Network.WIFI_WAKEUP_COUNT,
8017 u.getWifiRadioApWakeupCount(which));
8018 proto.write(UidProto.Network.MOBILE_BYTES_BG_RX,
8019 u.getNetworkActivityBytes(NETWORK_MOBILE_BG_RX_DATA, which));
8020 proto.write(UidProto.Network.MOBILE_BYTES_BG_TX,
8021 u.getNetworkActivityBytes(NETWORK_MOBILE_BG_TX_DATA, which));
8022 proto.write(UidProto.Network.WIFI_BYTES_BG_RX,
8023 u.getNetworkActivityBytes(NETWORK_WIFI_BG_RX_DATA, which));
8024 proto.write(UidProto.Network.WIFI_BYTES_BG_TX,
8025 u.getNetworkActivityBytes(NETWORK_WIFI_BG_TX_DATA, which));
8026 proto.write(UidProto.Network.MOBILE_PACKETS_BG_RX,
8027 u.getNetworkActivityPackets(NETWORK_MOBILE_BG_RX_DATA, which));
8028 proto.write(UidProto.Network.MOBILE_PACKETS_BG_TX,
8029 u.getNetworkActivityPackets(NETWORK_MOBILE_BG_TX_DATA, which));
8030 proto.write(UidProto.Network.WIFI_PACKETS_BG_RX,
8031 u.getNetworkActivityPackets(NETWORK_WIFI_BG_RX_DATA, which));
8032 proto.write(UidProto.Network.WIFI_PACKETS_BG_TX,
8033 u.getNetworkActivityPackets(NETWORK_WIFI_BG_TX_DATA, which));
8034 proto.end(nToken);
8035
8036 // Power use item (POWER_USE_ITEM_DATA)
8037 UidBatteryConsumer consumer = uidToConsumer.get(uid);
8038 if (consumer != null) {
8039 final long bsToken = proto.start(UidProto.POWER_USE_ITEM);
8040 proto.write(UidProto.PowerUseItem.COMPUTED_POWER_MAH, consumer.getConsumedPower());
8041 proto.write(UidProto.PowerUseItem.SHOULD_HIDE,
8042 proportionalAttributionCalculator.isSystemBatteryConsumer(consumer));
8043 proto.write(UidProto.PowerUseItem.SCREEN_POWER_MAH,
8044 consumer.getConsumedPower(BatteryConsumer.POWER_COMPONENT_SCREEN));
8045 proto.write(UidProto.PowerUseItem.PROPORTIONAL_SMEAR_MAH,
8046 proportionalAttributionCalculator.getProportionalPowerMah(consumer));
8047 proto.end(bsToken);
8048 }
8049
8050 // Processes (PROCESS_DATA)
8051 final ArrayMap<String, ? extends BatteryStats.Uid.Proc> processStats =
8052 u.getProcessStats();
8053 for (int ipr = processStats.size() - 1; ipr >= 0; --ipr) {
8054 final Uid.Proc ps = processStats.valueAt(ipr);
8055 final long prToken = proto.start(UidProto.PROCESS);
8056
8057 proto.write(UidProto.Process.NAME, processStats.keyAt(ipr));
8058 proto.write(UidProto.Process.USER_DURATION_MS, ps.getUserTime(which));
8059 proto.write(UidProto.Process.SYSTEM_DURATION_MS, ps.getSystemTime(which));
8060 proto.write(UidProto.Process.FOREGROUND_DURATION_MS, ps.getForegroundTime(which));
8061 proto.write(UidProto.Process.START_COUNT, ps.getStarts(which));
8062 proto.write(UidProto.Process.ANR_COUNT, ps.getNumAnrs(which));
8063 proto.write(UidProto.Process.CRASH_COUNT, ps.getNumCrashes(which));
8064
8065 proto.end(prToken);
8066 }
8067
8068 // Sensors (SENSOR_DATA)
8069 final SparseArray<? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
8070 for (int ise = 0; ise < sensors.size(); ++ise) {
8071 final Uid.Sensor se = sensors.valueAt(ise);
8072 final Timer timer = se.getSensorTime();
8073 if (timer == null) {
8074 continue;
8075 }
8076 final Timer bgTimer = se.getSensorBackgroundTime();
8077 final int sensorNumber = sensors.keyAt(ise);
8078 final long seToken = proto.start(UidProto.SENSORS);
8079
8080 proto.write(UidProto.Sensor.ID, sensorNumber);
8081 // Background uses totalDurationMsLocked, while total uses totalTimeLocked
8082 dumpTimer(proto, UidProto.Sensor.APPORTIONED, timer, rawRealtimeUs, which);
8083 dumpTimer(proto, UidProto.Sensor.BACKGROUND, bgTimer, rawRealtimeUs, which);
8084
8085 proto.end(seToken);
8086 }
8087
8088 // State times (STATE_TIME_DATA)
8089 for (int ips = 0; ips < Uid.NUM_PROCESS_STATE; ++ips) {
8090 long durMs = roundUsToMs(u.getProcessStateTime(ips, rawRealtimeUs, which));
8091 if (durMs == 0) {
8092 continue;
8093 }
8094 final long stToken = proto.start(UidProto.STATES);
8095 proto.write(UidProto.StateTime.STATE, ips);
8096 proto.write(UidProto.StateTime.DURATION_MS, durMs);
8097 proto.end(stToken);
8098 }
8099
8100 // Syncs (SYNC_DATA)
8101 final ArrayMap<String, ? extends Timer> syncs = u.getSyncStats();
8102 for (int isy = syncs.size() - 1; isy >= 0; --isy) {
8103 final Timer timer = syncs.valueAt(isy);
8104 final Timer bgTimer = timer.getSubTimer();
8105 final long syToken = proto.start(UidProto.SYNCS);
8106
8107 proto.write(UidProto.Sync.NAME, syncs.keyAt(isy));
8108 // Background uses totalDurationMsLocked, while total uses totalTimeLocked
8109 dumpTimer(proto, UidProto.Sync.TOTAL, timer, rawRealtimeUs, which);
8110 dumpTimer(proto, UidProto.Sync.BACKGROUND, bgTimer, rawRealtimeUs, which);
8111
8112 proto.end(syToken);
8113 }
8114
8115 // User activity (USER_ACTIVITY_DATA)
8116 if (u.hasUserActivity()) {
8117 for (int i = 0; i < Uid.NUM_USER_ACTIVITY_TYPES; ++i) {
8118 int val = u.getUserActivityCount(i, which);
8119 if (val != 0) {
8120 final long uaToken = proto.start(UidProto.USER_ACTIVITY);
8121 proto.write(UidProto.UserActivity.NAME, i);
8122 proto.write(UidProto.UserActivity.COUNT, val);
8123 proto.end(uaToken);
8124 }
8125 }
8126 }
8127
8128 // Vibrator (VIBRATOR_DATA)
8129 dumpTimer(proto, UidProto.VIBRATOR, u.getVibratorOnTimer(), rawRealtimeUs, which);
8130
8131 // Video (VIDEO_DATA)
8132 dumpTimer(proto, UidProto.VIDEO, u.getVideoTurnedOnTimer(), rawRealtimeUs, which);
8133
8134 // Wakelocks (WAKELOCK_DATA)
8135 final ArrayMap<String, ? extends Uid.Wakelock> wakelocks = u.getWakelockStats();
8136 for (int iw = wakelocks.size() - 1; iw >= 0; --iw) {
8137 final Uid.Wakelock wl = wakelocks.valueAt(iw);
8138 final long wToken = proto.start(UidProto.WAKELOCKS);
8139 proto.write(UidProto.Wakelock.NAME, wakelocks.keyAt(iw));
8140 dumpTimer(proto, UidProto.Wakelock.FULL, wl.getWakeTime(WAKE_TYPE_FULL),
8141 rawRealtimeUs, which);
8142 final Timer pTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
8143 if (pTimer != null) {
8144 dumpTimer(proto, UidProto.Wakelock.PARTIAL, pTimer, rawRealtimeUs, which);
8145 dumpTimer(proto, UidProto.Wakelock.BACKGROUND_PARTIAL, pTimer.getSubTimer(),
8146 rawRealtimeUs, which);
8147 }
8148 dumpTimer(proto, UidProto.Wakelock.WINDOW, wl.getWakeTime(WAKE_TYPE_WINDOW),
8149 rawRealtimeUs, which);
8150 proto.end(wToken);
8151 }
8152
8153 // Wifi Multicast Wakelock (WIFI_MULTICAST_WAKELOCK_DATA)
8154 dumpTimer(proto, UidProto.WIFI_MULTICAST_WAKELOCK, u.getMulticastWakelockStats(),
8155 rawRealtimeUs, which);
8156
8157 // Wakeup alarms (WAKEUP_ALARM_DATA)
8158 for (int ipkg = packageStats.size() - 1; ipkg >= 0; --ipkg) {
8159 final Uid.Pkg ps = packageStats.valueAt(ipkg);
8160 final ArrayMap<String, ? extends Counter> alarms = ps.getWakeupAlarmStats();
8161 for (int iwa = alarms.size() - 1; iwa >= 0; --iwa) {
8162 final long waToken = proto.start(UidProto.WAKEUP_ALARM);
8163 proto.write(UidProto.WakeupAlarm.NAME, alarms.keyAt(iwa));
8164 proto.write(UidProto.WakeupAlarm.COUNT,
8165 alarms.valueAt(iwa).getCountLocked(which));
8166 proto.end(waToken);
8167 }
8168 }
8169
8170 // Wifi Controller (WIFI_CONTROLLER_DATA)
8171 dumpControllerActivityProto(proto, UidProto.WIFI_CONTROLLER,
8172 u.getWifiControllerActivity(), which);
8173
8174 // Wifi data (WIFI_DATA)
8175 final long wToken = proto.start(UidProto.WIFI);
8176 proto.write(UidProto.Wifi.FULL_WIFI_LOCK_DURATION_MS,
8177 roundUsToMs(u.getFullWifiLockTime(rawRealtimeUs, which)));
8178 dumpTimer(proto, UidProto.Wifi.APPORTIONED_SCAN, u.getWifiScanTimer(),
8179 rawRealtimeUs, which);
8180 proto.write(UidProto.Wifi.RUNNING_DURATION_MS,
8181 roundUsToMs(u.getWifiRunningTime(rawRealtimeUs, which)));
8182 dumpTimer(proto, UidProto.Wifi.BACKGROUND_SCAN, u.getWifiScanBackgroundTimer(),
8183 rawRealtimeUs, which);
8184 proto.end(wToken);
8185
8186 proto.end(uTkn);
8187 }
8188 }
8189
8190 private void dumpProtoHistoryLocked(ProtoOutputStream proto, int flags, long histStart) {
8191 if (!startIteratingHistoryLocked()) {
8192 return;
8193 }
8194
8195 proto.write(BatteryStatsServiceDumpHistoryProto.REPORT_VERSION, CHECKIN_VERSION);
8196 proto.write(BatteryStatsServiceDumpHistoryProto.PARCEL_VERSION, getParcelVersion());
8197 proto.write(BatteryStatsServiceDumpHistoryProto.START_PLATFORM_VERSION,
8198 getStartPlatformVersion());
8199 proto.write(BatteryStatsServiceDumpHistoryProto.END_PLATFORM_VERSION,
8200 getEndPlatformVersion());
8201 try {
8202 long token;
8203 // History string pool (HISTORY_STRING_POOL)
8204 for (int i = 0; i < getHistoryStringPoolSize(); ++i) {
8205 token = proto.start(BatteryStatsServiceDumpHistoryProto.KEYS);
8206 proto.write(BatteryStatsServiceDumpHistoryProto.Key.INDEX, i);
8207 proto.write(BatteryStatsServiceDumpHistoryProto.Key.UID, getHistoryTagPoolUid(i));
8208 proto.write(BatteryStatsServiceDumpHistoryProto.Key.TAG,
8209 getHistoryTagPoolString(i));
8210 proto.end(token);
8211 }
8212
8213 // History data (HISTORY_DATA)
8214 final HistoryPrinter hprinter = new HistoryPrinter();
8215 final HistoryItem rec = new HistoryItem();
8216 long lastTime = -1;
8217 long baseTime = -1;
8218 boolean printed = false;
8219 HistoryEventTracker tracker = null;
8220 while (getNextHistoryLocked(rec)) {
8221 lastTime = rec.time;
8222 if (baseTime < 0) {
8223 baseTime = lastTime;
8224 }
8225 if (rec.time >= histStart) {
8226 if (histStart >= 0 && !printed) {
8227 if (rec.cmd == HistoryItem.CMD_CURRENT_TIME
8228 || rec.cmd == HistoryItem.CMD_RESET
8229 || rec.cmd == HistoryItem.CMD_START
8230 || rec.cmd == HistoryItem.CMD_SHUTDOWN) {
8231 printed = true;
8232 hprinter.printNextItem(proto, rec, baseTime,
8233 (flags & DUMP_VERBOSE) != 0);
8234 rec.cmd = HistoryItem.CMD_UPDATE;
8235 } else if (rec.currentTime != 0) {
8236 printed = true;
8237 byte cmd = rec.cmd;
8238 rec.cmd = HistoryItem.CMD_CURRENT_TIME;
8239 hprinter.printNextItem(proto, rec, baseTime,
8240 (flags & DUMP_VERBOSE) != 0);
8241 rec.cmd = cmd;
8242 }
8243 if (tracker != null) {
8244 if (rec.cmd != HistoryItem.CMD_UPDATE) {
8245 hprinter.printNextItem(proto, rec, baseTime,
8246 (flags & DUMP_VERBOSE) != 0);
8247 rec.cmd = HistoryItem.CMD_UPDATE;
8248 }
8249 int oldEventCode = rec.eventCode;
8250 HistoryTag oldEventTag = rec.eventTag;
8251 rec.eventTag = new HistoryTag();
8252 for (int i = 0; i < HistoryItem.EVENT_COUNT; i++) {
8253 HashMap<String, SparseIntArray> active =
8254 tracker.getStateForEvent(i);
8255 if (active == null) {
8256 continue;
8257 }
8258 for (HashMap.Entry<String, SparseIntArray> ent
8259 : active.entrySet()) {
8260 SparseIntArray uids = ent.getValue();
8261 for (int j = 0; j < uids.size(); j++) {
8262 rec.eventCode = i;
8263 rec.eventTag.string = ent.getKey();
8264 rec.eventTag.uid = uids.keyAt(j);
8265 rec.eventTag.poolIdx = uids.valueAt(j);
8266 hprinter.printNextItem(proto, rec, baseTime,
8267 (flags & DUMP_VERBOSE) != 0);
8268 rec.wakeReasonTag = null;
8269 rec.wakelockTag = null;
8270 }
8271 }
8272 }
8273 rec.eventCode = oldEventCode;
8274 rec.eventTag = oldEventTag;
8275 tracker = null;
8276 }
8277 }
8278 hprinter.printNextItem(proto, rec, baseTime,
8279 (flags & DUMP_VERBOSE) != 0);
8280 }
8281 }
8282 if (histStart >= 0) {
8283 commitCurrentHistoryBatchLocked();
8284 proto.write(BatteryStatsServiceDumpHistoryProto.CSV_LINES,
8285 "NEXT: " + (lastTime + 1));
8286 }
8287 } finally {
8288 finishIteratingHistoryLocked();
8289 }
8290 }
8291
8292 private void dumpProtoSystemLocked(ProtoOutputStream proto, BatteryUsageStats stats) {
8293 final long sToken = proto.start(BatteryStatsProto.SYSTEM);
8294 final long rawUptimeUs = SystemClock.uptimeMillis() * 1000;
8295 final long rawRealtimeMs = SystemClock.elapsedRealtime();
8296 final long rawRealtimeUs = rawRealtimeMs * 1000;
8297 final int which = STATS_SINCE_CHARGED;
8298
8299 // Battery data (BATTERY_DATA)
8300 final long bToken = proto.start(SystemProto.BATTERY);
8301 proto.write(SystemProto.Battery.START_CLOCK_TIME_MS, getStartClockTime());
8302 proto.write(SystemProto.Battery.START_COUNT, getStartCount());
8303 proto.write(SystemProto.Battery.TOTAL_REALTIME_MS,
8304 computeRealtime(rawRealtimeUs, which) / 1000);
8305 proto.write(SystemProto.Battery.TOTAL_UPTIME_MS,
8306 computeUptime(rawUptimeUs, which) / 1000);
8307 proto.write(SystemProto.Battery.BATTERY_REALTIME_MS,
8308 computeBatteryRealtime(rawRealtimeUs, which) / 1000);
8309 proto.write(SystemProto.Battery.BATTERY_UPTIME_MS,
8310 computeBatteryUptime(rawUptimeUs, which) / 1000);
8311 proto.write(SystemProto.Battery.SCREEN_OFF_REALTIME_MS,
8312 computeBatteryScreenOffRealtime(rawRealtimeUs, which) / 1000);
8313 proto.write(SystemProto.Battery.SCREEN_OFF_UPTIME_MS,
8314 computeBatteryScreenOffUptime(rawUptimeUs, which) / 1000);
8315 proto.write(SystemProto.Battery.SCREEN_DOZE_DURATION_MS,
8316 getScreenDozeTime(rawRealtimeUs, which) / 1000);
8317 proto.write(SystemProto.Battery.ESTIMATED_BATTERY_CAPACITY_MAH,
8318 getEstimatedBatteryCapacity());
8319 proto.write(SystemProto.Battery.MIN_LEARNED_BATTERY_CAPACITY_UAH,
8320 getMinLearnedBatteryCapacity());
8321 proto.write(SystemProto.Battery.MAX_LEARNED_BATTERY_CAPACITY_UAH,
8322 getMaxLearnedBatteryCapacity());
8323 proto.end(bToken);
8324
8325 // Battery discharge (BATTERY_DISCHARGE_DATA)
8326 final long bdToken = proto.start(SystemProto.BATTERY_DISCHARGE);
8327 proto.write(SystemProto.BatteryDischarge.LOWER_BOUND_SINCE_CHARGE,
8328 getLowDischargeAmountSinceCharge());
8329 proto.write(SystemProto.BatteryDischarge.UPPER_BOUND_SINCE_CHARGE,
8330 getHighDischargeAmountSinceCharge());
8331 proto.write(SystemProto.BatteryDischarge.SCREEN_ON_SINCE_CHARGE,
8332 getDischargeAmountScreenOnSinceCharge());
8333 proto.write(SystemProto.BatteryDischarge.SCREEN_OFF_SINCE_CHARGE,
8334 getDischargeAmountScreenOffSinceCharge());
8335 proto.write(SystemProto.BatteryDischarge.SCREEN_DOZE_SINCE_CHARGE,
8336 getDischargeAmountScreenDozeSinceCharge());
8337 proto.write(SystemProto.BatteryDischarge.TOTAL_MAH,
8338 getUahDischarge(which) / 1000);
8339 proto.write(SystemProto.BatteryDischarge.TOTAL_MAH_SCREEN_OFF,
8340 getUahDischargeScreenOff(which) / 1000);
8341 proto.write(SystemProto.BatteryDischarge.TOTAL_MAH_SCREEN_DOZE,
8342 getUahDischargeScreenDoze(which) / 1000);
8343 proto.write(SystemProto.BatteryDischarge.TOTAL_MAH_LIGHT_DOZE,
8344 getUahDischargeLightDoze(which) / 1000);
8345 proto.write(SystemProto.BatteryDischarge.TOTAL_MAH_DEEP_DOZE,
8346 getUahDischargeDeepDoze(which) / 1000);
8347 proto.end(bdToken);
8348
8349 // Time remaining
8350 long timeRemainingUs = computeChargeTimeRemaining(rawRealtimeUs);
8351 // These are part of a oneof, so we should only set one of them.
8352 if (timeRemainingUs >= 0) {
8353 // Charge time remaining (CHARGE_TIME_REMAIN_DATA)
8354 proto.write(SystemProto.CHARGE_TIME_REMAINING_MS, timeRemainingUs / 1000);
8355 } else {
8356 timeRemainingUs = computeBatteryTimeRemaining(rawRealtimeUs);
8357 // Discharge time remaining (DISCHARGE_TIME_REMAIN_DATA)
8358 if (timeRemainingUs >= 0) {
8359 proto.write(SystemProto.DISCHARGE_TIME_REMAINING_MS, timeRemainingUs / 1000);
8360 } else {
8361 proto.write(SystemProto.DISCHARGE_TIME_REMAINING_MS, -1);
8362 }
8363 }
8364
8365 // Charge step (CHARGE_STEP_DATA)
8366 dumpDurationSteps(proto, SystemProto.CHARGE_STEP, getChargeLevelStepTracker());
8367
8368 // Phone data connection (DATA_CONNECTION_TIME_DATA and DATA_CONNECTION_COUNT_DATA)
8369 for (int i = 0; i < NUM_DATA_CONNECTION_TYPES; ++i) {
8370 // Map OTHER to TelephonyManager.NETWORK_TYPE_UNKNOWN and mark NONE as a boolean.
8371 boolean isNone = (i == DATA_CONNECTION_OUT_OF_SERVICE);
8372 int telephonyNetworkType = i;
8373 if (i == DATA_CONNECTION_OTHER || i == DATA_CONNECTION_EMERGENCY_SERVICE) {
8374 telephonyNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
8375 }
8376 final long pdcToken = proto.start(SystemProto.DATA_CONNECTION);
8377 if (isNone) {
8378 proto.write(SystemProto.DataConnection.IS_NONE, isNone);
8379 } else {
8380 proto.write(SystemProto.DataConnection.NAME, telephonyNetworkType);
8381 }
8382 dumpTimer(proto, SystemProto.DataConnection.TOTAL, getPhoneDataConnectionTimer(i),
8383 rawRealtimeUs, which);
8384 proto.end(pdcToken);
8385 }
8386
8387 // Discharge step (DISCHARGE_STEP_DATA)
8388 dumpDurationSteps(proto, SystemProto.DISCHARGE_STEP, getDischargeLevelStepTracker());
8389
8390 // CPU frequencies (GLOBAL_CPU_FREQ_DATA)
8391 final long[] cpuFreqs = getCpuFreqs();
8392 if (cpuFreqs != null) {
8393 for (long i : cpuFreqs) {
8394 proto.write(SystemProto.CPU_FREQUENCY, i);
8395 }
8396 }
8397
8398 // Bluetooth controller (GLOBAL_BLUETOOTH_CONTROLLER_DATA)
8399 dumpControllerActivityProto(proto, SystemProto.GLOBAL_BLUETOOTH_CONTROLLER,
8400 getBluetoothControllerActivity(), which);
8401
8402 // Modem controller (GLOBAL_MODEM_CONTROLLER_DATA)
8403 dumpControllerActivityProto(proto, SystemProto.GLOBAL_MODEM_CONTROLLER,
8404 getModemControllerActivity(), which);
8405
8406 // Global network data (GLOBAL_NETWORK_DATA)
8407 final long gnToken = proto.start(SystemProto.GLOBAL_NETWORK);
8408 proto.write(SystemProto.GlobalNetwork.MOBILE_BYTES_RX,
8409 getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
8410 proto.write(SystemProto.GlobalNetwork.MOBILE_BYTES_TX,
8411 getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
8412 proto.write(SystemProto.GlobalNetwork.MOBILE_PACKETS_RX,
8413 getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
8414 proto.write(SystemProto.GlobalNetwork.MOBILE_PACKETS_TX,
8415 getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
8416 proto.write(SystemProto.GlobalNetwork.WIFI_BYTES_RX,
8417 getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
8418 proto.write(SystemProto.GlobalNetwork.WIFI_BYTES_TX,
8419 getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
8420 proto.write(SystemProto.GlobalNetwork.WIFI_PACKETS_RX,
8421 getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
8422 proto.write(SystemProto.GlobalNetwork.WIFI_PACKETS_TX,
8423 getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
8424 proto.write(SystemProto.GlobalNetwork.BT_BYTES_RX,
8425 getNetworkActivityBytes(NETWORK_BT_RX_DATA, which));
8426 proto.write(SystemProto.GlobalNetwork.BT_BYTES_TX,
8427 getNetworkActivityBytes(NETWORK_BT_TX_DATA, which));
8428 proto.end(gnToken);
8429
8430 // Wifi controller (GLOBAL_WIFI_CONTROLLER_DATA)
8431 dumpControllerActivityProto(proto, SystemProto.GLOBAL_WIFI_CONTROLLER,
8432 getWifiControllerActivity(), which);
8433
8434
8435 // Global wifi (GLOBAL_WIFI_DATA)
8436 final long gwToken = proto.start(SystemProto.GLOBAL_WIFI);
8437 proto.write(SystemProto.GlobalWifi.ON_DURATION_MS,
8438 getWifiOnTime(rawRealtimeUs, which) / 1000);
8439 proto.write(SystemProto.GlobalWifi.RUNNING_DURATION_MS,
8440 getGlobalWifiRunningTime(rawRealtimeUs, which) / 1000);
8441 proto.end(gwToken);
8442
8443 // Kernel wakelock (KERNEL_WAKELOCK_DATA)
8444 final Map<String, ? extends Timer> kernelWakelocks = getKernelWakelockStats();
8445 for (Map.Entry<String, ? extends Timer> ent : kernelWakelocks.entrySet()) {
8446 final long kwToken = proto.start(SystemProto.KERNEL_WAKELOCK);
8447 proto.write(SystemProto.KernelWakelock.NAME, ent.getKey());
8448 dumpTimer(proto, SystemProto.KernelWakelock.TOTAL, ent.getValue(),
8449 rawRealtimeUs, which);
8450 proto.end(kwToken);
8451 }
8452
8453 // Misc (MISC_DATA)
8454 // Calculate wakelock times across all uids.
8455 long fullWakeLockTimeTotalUs = 0;
8456 long partialWakeLockTimeTotalUs = 0;
8457
8458 final SparseArray<? extends Uid> uidStats = getUidStats();
8459 for (int iu = 0; iu < uidStats.size(); iu++) {
8460 final Uid u = uidStats.valueAt(iu);
8461
8462 final ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> wakelocks =
8463 u.getWakelockStats();
8464 for (int iw = wakelocks.size() - 1; iw >= 0; --iw) {
8465 final Uid.Wakelock wl = wakelocks.valueAt(iw);
8466
8467 final Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
8468 if (fullWakeTimer != null) {
8469 fullWakeLockTimeTotalUs += fullWakeTimer.getTotalTimeLocked(rawRealtimeUs,
8470 which);
8471 }
8472
8473 final Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
8474 if (partialWakeTimer != null) {
8475 partialWakeLockTimeTotalUs += partialWakeTimer.getTotalTimeLocked(
8476 rawRealtimeUs, which);
8477 }
8478 }
8479 }
8480 final long mToken = proto.start(SystemProto.MISC);
8481 proto.write(SystemProto.Misc.SCREEN_ON_DURATION_MS,
8482 getScreenOnTime(rawRealtimeUs, which) / 1000);
8483 proto.write(SystemProto.Misc.PHONE_ON_DURATION_MS,
8484 getPhoneOnTime(rawRealtimeUs, which) / 1000);
8485 proto.write(SystemProto.Misc.FULL_WAKELOCK_TOTAL_DURATION_MS,
8486 fullWakeLockTimeTotalUs / 1000);
8487 proto.write(SystemProto.Misc.PARTIAL_WAKELOCK_TOTAL_DURATION_MS,
8488 partialWakeLockTimeTotalUs / 1000);
8489 proto.write(SystemProto.Misc.MOBILE_RADIO_ACTIVE_DURATION_MS,
8490 getMobileRadioActiveTime(rawRealtimeUs, which) / 1000);
8491 proto.write(SystemProto.Misc.MOBILE_RADIO_ACTIVE_ADJUSTED_TIME_MS,
8492 getMobileRadioActiveAdjustedTime(which) / 1000);
8493 proto.write(SystemProto.Misc.MOBILE_RADIO_ACTIVE_COUNT,
8494 getMobileRadioActiveCount(which));
8495 proto.write(SystemProto.Misc.MOBILE_RADIO_ACTIVE_UNKNOWN_DURATION_MS,
8496 getMobileRadioActiveUnknownTime(which) / 1000);
8497 proto.write(SystemProto.Misc.INTERACTIVE_DURATION_MS,
8498 getInteractiveTime(rawRealtimeUs, which) / 1000);
8499 proto.write(SystemProto.Misc.BATTERY_SAVER_MODE_ENABLED_DURATION_MS,
8500 getPowerSaveModeEnabledTime(rawRealtimeUs, which) / 1000);
8501 proto.write(SystemProto.Misc.NUM_CONNECTIVITY_CHANGES,
8502 getNumConnectivityChange(which));
8503 proto.write(SystemProto.Misc.DEEP_DOZE_ENABLED_DURATION_MS,
8504 getDeviceIdleModeTime(DEVICE_IDLE_MODE_DEEP, rawRealtimeUs, which) / 1000);
8505 proto.write(SystemProto.Misc.DEEP_DOZE_COUNT,
8506 getDeviceIdleModeCount(DEVICE_IDLE_MODE_DEEP, which));
8507 proto.write(SystemProto.Misc.DEEP_DOZE_IDLING_DURATION_MS,
8508 getDeviceIdlingTime(DEVICE_IDLE_MODE_DEEP, rawRealtimeUs, which) / 1000);
8509 proto.write(SystemProto.Misc.DEEP_DOZE_IDLING_COUNT,
8510 getDeviceIdlingCount(DEVICE_IDLE_MODE_DEEP, which));
8511 proto.write(SystemProto.Misc.LONGEST_DEEP_DOZE_DURATION_MS,
8512 getLongestDeviceIdleModeTime(DEVICE_IDLE_MODE_DEEP));
8513 proto.write(SystemProto.Misc.LIGHT_DOZE_ENABLED_DURATION_MS,
8514 getDeviceIdleModeTime(DEVICE_IDLE_MODE_LIGHT, rawRealtimeUs, which) / 1000);
8515 proto.write(SystemProto.Misc.LIGHT_DOZE_COUNT,
8516 getDeviceIdleModeCount(DEVICE_IDLE_MODE_LIGHT, which));
8517 proto.write(SystemProto.Misc.LIGHT_DOZE_IDLING_DURATION_MS,
8518 getDeviceIdlingTime(DEVICE_IDLE_MODE_LIGHT, rawRealtimeUs, which) / 1000);
8519 proto.write(SystemProto.Misc.LIGHT_DOZE_IDLING_COUNT,
8520 getDeviceIdlingCount(DEVICE_IDLE_MODE_LIGHT, which));
8521 proto.write(SystemProto.Misc.LONGEST_LIGHT_DOZE_DURATION_MS,
8522 getLongestDeviceIdleModeTime(DEVICE_IDLE_MODE_LIGHT));
8523 proto.end(mToken);
8524
8525 // Wifi multicast wakelock total stats (WIFI_MULTICAST_WAKELOCK_TOTAL_DATA)
8526 final long multicastWakeLockTimeTotalUs =
8527 getWifiMulticastWakelockTime(rawRealtimeUs, which);
8528 final int multicastWakeLockCountTotal = getWifiMulticastWakelockCount(which);
8529 final long wmctToken = proto.start(SystemProto.WIFI_MULTICAST_WAKELOCK_TOTAL);
8530 proto.write(SystemProto.WifiMulticastWakelockTotal.DURATION_MS,
8531 multicastWakeLockTimeTotalUs / 1000);
8532 proto.write(SystemProto.WifiMulticastWakelockTotal.COUNT,
8533 multicastWakeLockCountTotal);
8534 proto.end(wmctToken);
8535
8536 final BatteryConsumer deviceConsumer = stats.getAggregateBatteryConsumer(
8537 BatteryUsageStats.AGGREGATE_BATTERY_CONSUMER_SCOPE_DEVICE);
8538
8539 for (int powerComponent = 0; powerComponent < BatteryConsumer.POWER_COMPONENT_COUNT;
8540 powerComponent++) {
8541 int n = SystemProto.PowerUseItem.UNKNOWN_SIPPER;
8542 switch (powerComponent) {
8543 case BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY:
8544 n = SystemProto.PowerUseItem.AMBIENT_DISPLAY;
8545 break;
8546 case BatteryConsumer.POWER_COMPONENT_IDLE:
8547 n = SystemProto.PowerUseItem.IDLE;
8548 break;
8549 case BatteryConsumer.POWER_COMPONENT_MOBILE_RADIO:
8550 n = SystemProto.PowerUseItem.CELL;
8551 break;
8552 case BatteryConsumer.POWER_COMPONENT_PHONE:
8553 n = SystemProto.PowerUseItem.PHONE;
8554 break;
8555 case BatteryConsumer.POWER_COMPONENT_WIFI:
8556 n = SystemProto.PowerUseItem.WIFI;
8557 break;
8558 case BatteryConsumer.POWER_COMPONENT_BLUETOOTH:
8559 n = SystemProto.PowerUseItem.BLUETOOTH;
8560 break;
8561 case BatteryConsumer.POWER_COMPONENT_SCREEN:
8562 n = SystemProto.PowerUseItem.SCREEN;
8563 break;
8564 case BatteryConsumer.POWER_COMPONENT_FLASHLIGHT:
8565 n = SystemProto.PowerUseItem.FLASHLIGHT;
8566 break;
8567 case BatteryConsumer.POWER_COMPONENT_CAMERA:
8568 n = SystemProto.PowerUseItem.CAMERA;
8569 break;
8570 case BatteryConsumer.POWER_COMPONENT_MEMORY:
8571 n = SystemProto.PowerUseItem.MEMORY;
8572 break;
8573 }
8574 final long puiToken = proto.start(SystemProto.POWER_USE_ITEM);
8575 proto.write(SystemProto.PowerUseItem.NAME, n);
8576 proto.write(SystemProto.PowerUseItem.UID, 0);
8577 proto.write(SystemProto.PowerUseItem.COMPUTED_POWER_MAH,
8578 deviceConsumer.getConsumedPower(powerComponent));
8579 proto.write(SystemProto.PowerUseItem.SHOULD_HIDE,
8580 shouldHidePowerComponent(powerComponent));
8581 proto.write(SystemProto.PowerUseItem.SCREEN_POWER_MAH, 0);
8582 proto.write(SystemProto.PowerUseItem.PROPORTIONAL_SMEAR_MAH, 0);
8583 proto.end(puiToken);
8584 }
8585
8586 // Power use summary (POWER_USE_SUMMARY_DATA)
8587 final long pusToken = proto.start(SystemProto.POWER_USE_SUMMARY);
8588 proto.write(SystemProto.PowerUseSummary.BATTERY_CAPACITY_MAH,
8589 stats.getBatteryCapacity());
8590 proto.write(SystemProto.PowerUseSummary.COMPUTED_POWER_MAH, stats.getConsumedPower());
8591 proto.write(SystemProto.PowerUseSummary.MIN_DRAINED_POWER_MAH,
8592 stats.getDischargedPowerRange().getLower());
8593 proto.write(SystemProto.PowerUseSummary.MAX_DRAINED_POWER_MAH,
8594 stats.getDischargedPowerRange().getUpper());
8595 proto.end(pusToken);
8596
8597 // RPM stats (RESOURCE_POWER_MANAGER_DATA)
8598 final Map<String, ? extends Timer> rpmStats = getRpmStats();
8599 final Map<String, ? extends Timer> screenOffRpmStats = getScreenOffRpmStats();
8600 for (Map.Entry<String, ? extends Timer> ent : rpmStats.entrySet()) {
8601 final long rpmToken = proto.start(SystemProto.RESOURCE_POWER_MANAGER);
8602 proto.write(SystemProto.ResourcePowerManager.NAME, ent.getKey());
8603 dumpTimer(proto, SystemProto.ResourcePowerManager.TOTAL,
8604 ent.getValue(), rawRealtimeUs, which);
8605 dumpTimer(proto, SystemProto.ResourcePowerManager.SCREEN_OFF,
8606 screenOffRpmStats.get(ent.getKey()), rawRealtimeUs, which);
8607 proto.end(rpmToken);
8608 }
8609
8610 // Screen brightness (SCREEN_BRIGHTNESS_DATA)
8611 for (int i = 0; i < NUM_SCREEN_BRIGHTNESS_BINS; ++i) {
8612 final long sbToken = proto.start(SystemProto.SCREEN_BRIGHTNESS);
8613 proto.write(SystemProto.ScreenBrightness.NAME, i);
8614 dumpTimer(proto, SystemProto.ScreenBrightness.TOTAL, getScreenBrightnessTimer(i),
8615 rawRealtimeUs, which);
8616 proto.end(sbToken);
8617 }
8618
8619 // Signal scanning time (SIGNAL_SCANNING_TIME_DATA)
8620 dumpTimer(proto, SystemProto.SIGNAL_SCANNING, getPhoneSignalScanningTimer(), rawRealtimeUs,
8621 which);
8622
8623 // Phone signal strength (SIGNAL_STRENGTH_TIME_DATA and SIGNAL_STRENGTH_COUNT_DATA)
8624 for (int i = 0; i < CellSignalStrength.getNumSignalStrengthLevels(); ++i) {
8625 final long pssToken = proto.start(SystemProto.PHONE_SIGNAL_STRENGTH);
8626 proto.write(SystemProto.PhoneSignalStrength.NAME, i);
8627 dumpTimer(proto, SystemProto.PhoneSignalStrength.TOTAL, getPhoneSignalStrengthTimer(i),
8628 rawRealtimeUs, which);
8629 proto.end(pssToken);
8630 }
8631
8632 // Wakeup reasons (WAKEUP_REASON_DATA)
8633 final Map<String, ? extends Timer> wakeupReasons = getWakeupReasonStats();
8634 for (Map.Entry<String, ? extends Timer> ent : wakeupReasons.entrySet()) {
8635 final long wrToken = proto.start(SystemProto.WAKEUP_REASON);
8636 proto.write(SystemProto.WakeupReason.NAME, ent.getKey());
8637 dumpTimer(proto, SystemProto.WakeupReason.TOTAL, ent.getValue(), rawRealtimeUs, which);
8638 proto.end(wrToken);
8639 }
8640
8641 // Wifi signal strength (WIFI_SIGNAL_STRENGTH_TIME_DATA and WIFI_SIGNAL_STRENGTH_COUNT_DATA)
8642 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; ++i) {
8643 final long wssToken = proto.start(SystemProto.WIFI_SIGNAL_STRENGTH);
8644 proto.write(SystemProto.WifiSignalStrength.NAME, i);
8645 dumpTimer(proto, SystemProto.WifiSignalStrength.TOTAL, getWifiSignalStrengthTimer(i),
8646 rawRealtimeUs, which);
8647 proto.end(wssToken);
8648 }
8649
8650 // Wifi state (WIFI_STATE_TIME_DATA and WIFI_STATE_COUNT_DATA)
8651 for (int i = 0; i < NUM_WIFI_STATES; ++i) {
8652 final long wsToken = proto.start(SystemProto.WIFI_STATE);
8653 proto.write(SystemProto.WifiState.NAME, i);
8654 dumpTimer(proto, SystemProto.WifiState.TOTAL, getWifiStateTimer(i),
8655 rawRealtimeUs, which);
8656 proto.end(wsToken);
8657 }
8658
8659 // Wifi supplicant state (WIFI_SUPPL_STATE_TIME_DATA and WIFI_SUPPL_STATE_COUNT_DATA)
8660 for (int i = 0; i < NUM_WIFI_SUPPL_STATES; ++i) {
8661 final long wssToken = proto.start(SystemProto.WIFI_SUPPLICANT_STATE);
8662 proto.write(SystemProto.WifiSupplicantState.NAME, i);
8663 dumpTimer(proto, SystemProto.WifiSupplicantState.TOTAL, getWifiSupplStateTimer(i),
8664 rawRealtimeUs, which);
8665 proto.end(wssToken);
8666 }
8667
8668 proto.end(sToken);
8669 }
8670
8671 /**
8672 * Returns true if the device does not have data-capable telephony.
8673 */
8674 public static boolean checkWifiOnly(Context context) {
8675 final TelephonyManager tm = context.getSystemService(TelephonyManager.class);
8676 if (tm == null) {
8677 return false;
8678 }
8679 return !tm.isDataCapable();
8680 }
8681
8682 private BatteryUsageStats getBatteryUsageStats(Context context) {
8683 final BatteryUsageStatsProvider provider = new BatteryUsageStatsProvider(context, this);
8684 final BatteryUsageStatsQuery query =
8685 new BatteryUsageStatsQuery.Builder().setMaxStatsAgeMs(0).build();
8686 return provider.getBatteryUsageStats(query);
8687 }
8688
8689 private boolean shouldHidePowerComponent(int powerComponent) {
8690 return powerComponent == BatteryConsumer.POWER_COMPONENT_IDLE
8691 || powerComponent == BatteryConsumer.POWER_COMPONENT_MOBILE_RADIO
8692 || powerComponent == BatteryConsumer.POWER_COMPONENT_SCREEN
8693 || powerComponent == BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY;
8694 }
8695
8696 private static class ProportionalAttributionCalculator {
8697 private static final double SYSTEM_BATTERY_CONSUMER = -1;
8698 private final PackageManager mPackageManager;
8699 private final HashSet<String> mSystemAndServicePackages;
8700 private final SparseDoubleArray mProportionalPowerMah;
8701
8702 ProportionalAttributionCalculator(Context context, BatteryUsageStats stats) {
8703 mPackageManager = context.getPackageManager();
8704 final Resources resources = context.getResources();
8705 final String[] systemPackageArray = resources.getStringArray(
8706 com.android.internal.R.array.config_batteryPackageTypeSystem);
8707 final String[] servicePackageArray = resources.getStringArray(
8708 com.android.internal.R.array.config_batteryPackageTypeService);
8709 mSystemAndServicePackages =
8710 new HashSet<>(systemPackageArray.length + servicePackageArray.length);
8711 for (String packageName : systemPackageArray) {
8712 mSystemAndServicePackages.add(packageName);
8713 }
8714 for (String packageName : servicePackageArray) {
8715 mSystemAndServicePackages.add(packageName);
8716 }
8717
8718 final List<UidBatteryConsumer> uidBatteryConsumers = stats.getUidBatteryConsumers();
8719 mProportionalPowerMah = new SparseDoubleArray(uidBatteryConsumers.size());
8720 double systemPowerMah = 0;
8721 for (int i = uidBatteryConsumers.size() - 1; i >= 0; i--) {
8722 UidBatteryConsumer consumer = uidBatteryConsumers.get(i);
8723 final int uid = consumer.getUid();
8724 if (isSystemUid(uid)) {
8725 mProportionalPowerMah.put(uid, SYSTEM_BATTERY_CONSUMER);
8726 systemPowerMah += consumer.getConsumedPower();
8727 }
8728 }
8729
8730 final double totalRemainingPower = stats.getConsumedPower() - systemPowerMah;
8731 if (Math.abs(totalRemainingPower) > 1e-3) {
8732 for (int i = uidBatteryConsumers.size() - 1; i >= 0; i--) {
8733 UidBatteryConsumer consumer = uidBatteryConsumers.get(i);
8734 final int uid = consumer.getUid();
8735 if (mProportionalPowerMah.get(uid) != SYSTEM_BATTERY_CONSUMER) {
8736 final double power = consumer.getConsumedPower();
8737 mProportionalPowerMah.put(uid,
8738 power + systemPowerMah * power / totalRemainingPower);
8739 }
8740 }
8741 }
8742 }
8743
8744 boolean isSystemBatteryConsumer(UidBatteryConsumer consumer) {
8745 return mProportionalPowerMah.get(consumer.getUid()) < 0;
8746 }
8747
8748 double getProportionalPowerMah(UidBatteryConsumer consumer) {
8749 final double powerMah = mProportionalPowerMah.get(consumer.getUid());
8750 return powerMah >= 0 ? powerMah : 0;
8751 }
8752
8753 /**
8754 * Check whether the UID is one of the system UIDs or a service UID
8755 */
8756 private boolean isSystemUid(int uid) {
8757 if (uid >= Process.ROOT_UID && uid < Process.FIRST_APPLICATION_UID) {
8758 return true;
8759 }
8760
8761 final String[] packages = mPackageManager.getPackagesForUid(uid);
8762 if (packages == null) {
8763 return false;
8764 }
8765
8766 for (String packageName : packages) {
8767 if (mSystemAndServicePackages.contains(packageName)) {
8768 return true;
8769 }
8770 }
8771
8772 return false;
8773 }
8774 }
8775
8776 private static class UidMobileRadioStats {
8777 public final int uid;
8778 public final long rxPackets;
8779 public final long txPackets;
8780 public final long radioActiveMs;
8781 public final int radioActiveCount;
8782 public final double millisecondsPerPacket;
8783
8784 private UidMobileRadioStats(int uid, long rxPackets, long txPackets, long radioActiveMs,
8785 int radioActiveCount, double millisecondsPerPacket) {
8786 this.uid = uid;
8787 this.txPackets = txPackets;
8788 this.rxPackets = rxPackets;
8789 this.radioActiveMs = radioActiveMs;
8790 this.radioActiveCount = radioActiveCount;
8791 this.millisecondsPerPacket = millisecondsPerPacket;
8792 }
8793 }
8794
8795 private List<UidMobileRadioStats> getUidMobileRadioStats(
8796 List<UidBatteryConsumer> uidBatteryConsumers) {
8797 final SparseArray<? extends Uid> uidStats = getUidStats();
8798 List<UidMobileRadioStats> uidMobileRadioStats = Lists.newArrayList();
8799 for (int i = 0; i < uidBatteryConsumers.size(); i++) {
8800 final UidBatteryConsumer consumer = uidBatteryConsumers.get(i);
8801 if (consumer.getConsumedPower(BatteryConsumer.POWER_COMPONENT_MOBILE_RADIO) == 0) {
8802 continue;
8803 }
8804
8805 final int uid = consumer.getUid();
8806 final Uid u = uidStats.get(uid);
8807 final long rxPackets = u.getNetworkActivityPackets(
8808 BatteryStats.NETWORK_MOBILE_RX_DATA, STATS_SINCE_CHARGED);
8809 final long txPackets = u.getNetworkActivityPackets(
8810 BatteryStats.NETWORK_MOBILE_TX_DATA, STATS_SINCE_CHARGED);
8811 if (rxPackets == 0 && txPackets == 0) {
8812 continue;
8813 }
8814 final long radioActiveMs = u.getMobileRadioActiveTime(STATS_SINCE_CHARGED) / 1000;
8815 final int radioActiveCount = u.getMobileRadioActiveCount(STATS_SINCE_CHARGED);
8816 final double msPerPacket = (double) radioActiveMs / (rxPackets + txPackets);
8817 if (msPerPacket == 0) {
8818 continue;
8819 }
8820 uidMobileRadioStats.add(
8821 new UidMobileRadioStats(uid, rxPackets, txPackets, radioActiveMs,
8822 radioActiveCount, msPerPacket));
8823 }
8824 uidMobileRadioStats.sort(
8825 (lhs, rhs) -> Double.compare(rhs.millisecondsPerPacket, lhs.millisecondsPerPacket));
8826 return uidMobileRadioStats;
8827 }
8828 }