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