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