BatteryStats.java revision 0ffc988a7f47013805d5abeed1c20f159b3bd799
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.Formatter;
22import java.util.List;
23import java.util.Map;
24
25import android.content.pm.ApplicationInfo;
26import android.telephony.SignalStrength;
27import android.util.Log;
28import android.util.Printer;
29import android.util.SparseArray;
30import android.util.TimeUtils;
31
32/**
33 * A class providing access to battery usage statistics, including information on
34 * wakelocks, processes, packages, and services.  All times are represented in microseconds
35 * except where indicated otherwise.
36 * @hide
37 */
38public abstract class BatteryStats implements Parcelable {
39
40    private static final boolean LOCAL_LOGV = false;
41
42    /**
43     * A constant indicating a partial wake lock timer.
44     */
45    public static final int WAKE_TYPE_PARTIAL = 0;
46
47    /**
48     * A constant indicating a full wake lock timer.
49     */
50    public static final int WAKE_TYPE_FULL = 1;
51
52    /**
53     * A constant indicating a window wake lock timer.
54     */
55    public static final int WAKE_TYPE_WINDOW = 2;
56
57    /**
58     * A constant indicating a sensor timer.
59     */
60    public static final int SENSOR = 3;
61
62    /**
63     * A constant indicating a a wifi running timer
64     */
65    public static final int WIFI_RUNNING = 4;
66
67    /**
68     * A constant indicating a full wifi lock timer
69     */
70    public static final int FULL_WIFI_LOCK = 5;
71
72    /**
73     * A constant indicating a scan wifi lock timer
74     */
75    public static final int SCAN_WIFI_LOCK = 6;
76
77     /**
78      * A constant indicating a wifi multicast timer
79      */
80     public static final int WIFI_MULTICAST_ENABLED = 7;
81
82    /**
83     * A constant indicating an audio turn on timer
84     */
85    public static final int AUDIO_TURNED_ON = 7;
86
87    /**
88     * A constant indicating a video turn on timer
89     */
90    public static final int VIDEO_TURNED_ON = 8;
91
92    /**
93     * Include all of the data in the stats, including previously saved data.
94     */
95    public static final int STATS_SINCE_CHARGED = 0;
96
97    /**
98     * Include only the last run in the stats.
99     */
100    public static final int STATS_LAST = 1;
101
102    /**
103     * Include only the current run in the stats.
104     */
105    public static final int STATS_CURRENT = 2;
106
107    /**
108     * Include only the run since the last time the device was unplugged in the stats.
109     */
110    public static final int STATS_SINCE_UNPLUGGED = 3;
111
112    // NOTE: Update this list if you add/change any stats above.
113    // These characters are supposed to represent "total", "last", "current",
114    // and "unplugged". They were shortened for efficiency sake.
115    private static final String[] STAT_NAMES = { "t", "l", "c", "u" };
116
117    /**
118     * Bump the version on this if the checkin format changes.
119     */
120    private static final int BATTERY_STATS_CHECKIN_VERSION = 5;
121
122    private static final long BYTES_PER_KB = 1024;
123    private static final long BYTES_PER_MB = 1048576; // 1024^2
124    private static final long BYTES_PER_GB = 1073741824; //1024^3
125
126
127    private static final String UID_DATA = "uid";
128    private static final String APK_DATA = "apk";
129    private static final String PROCESS_DATA = "pr";
130    private static final String SENSOR_DATA = "sr";
131    private static final String WAKELOCK_DATA = "wl";
132    private static final String KERNEL_WAKELOCK_DATA = "kwl";
133    private static final String NETWORK_DATA = "nt";
134    private static final String USER_ACTIVITY_DATA = "ua";
135    private static final String BATTERY_DATA = "bt";
136    private static final String BATTERY_DISCHARGE_DATA = "dc";
137    private static final String BATTERY_LEVEL_DATA = "lv";
138    private static final String WIFI_LOCK_DATA = "wfl";
139    private static final String MISC_DATA = "m";
140    private static final String SCREEN_BRIGHTNESS_DATA = "br";
141    private static final String SIGNAL_STRENGTH_TIME_DATA = "sgt";
142    private static final String SIGNAL_SCANNING_TIME_DATA = "sst";
143    private static final String SIGNAL_STRENGTH_COUNT_DATA = "sgc";
144    private static final String DATA_CONNECTION_TIME_DATA = "dct";
145    private static final String DATA_CONNECTION_COUNT_DATA = "dcc";
146
147    private final StringBuilder mFormatBuilder = new StringBuilder(32);
148    private final Formatter mFormatter = new Formatter(mFormatBuilder);
149
150    /**
151     * State for keeping track of counting information.
152     */
153    public static abstract class Counter {
154
155        /**
156         * Returns the count associated with this Counter for the
157         * selected type of statistics.
158         *
159         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
160         */
161        public abstract int getCountLocked(int which);
162
163        /**
164         * Temporary for debugging.
165         */
166        public abstract void logState(Printer pw, String prefix);
167    }
168
169    /**
170     * State for keeping track of timing information.
171     */
172    public static abstract class Timer {
173
174        /**
175         * Returns the count associated with this Timer for the
176         * selected type of statistics.
177         *
178         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
179         */
180        public abstract int getCountLocked(int which);
181
182        /**
183         * Returns the total time in microseconds associated with this Timer for the
184         * selected type of statistics.
185         *
186         * @param batteryRealtime system realtime on  battery in microseconds
187         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
188         * @return a time in microseconds
189         */
190        public abstract long getTotalTimeLocked(long batteryRealtime, int which);
191
192        /**
193         * Temporary for debugging.
194         */
195        public abstract void logState(Printer pw, String prefix);
196    }
197
198    /**
199     * The statistics associated with a particular uid.
200     */
201    public static abstract class Uid {
202
203        /**
204         * Returns a mapping containing wakelock statistics.
205         *
206         * @return a Map from Strings to Uid.Wakelock objects.
207         */
208        public abstract Map<String, ? extends Wakelock> getWakelockStats();
209
210        /**
211         * The statistics associated with a particular wake lock.
212         */
213        public static abstract class Wakelock {
214            public abstract Timer getWakeTime(int type);
215        }
216
217        /**
218         * Returns a mapping containing sensor statistics.
219         *
220         * @return a Map from Integer sensor ids to Uid.Sensor objects.
221         */
222        public abstract Map<Integer, ? extends Sensor> getSensorStats();
223
224        /**
225         * Returns a mapping containing active process data.
226         */
227        public abstract SparseArray<? extends Pid> getPidStats();
228
229        /**
230         * Returns a mapping containing process statistics.
231         *
232         * @return a Map from Strings to Uid.Proc objects.
233         */
234        public abstract Map<String, ? extends Proc> getProcessStats();
235
236        /**
237         * Returns a mapping containing package statistics.
238         *
239         * @return a Map from Strings to Uid.Pkg objects.
240         */
241        public abstract Map<String, ? extends Pkg> getPackageStats();
242
243        /**
244         * {@hide}
245         */
246        public abstract int getUid();
247
248        /**
249         * {@hide}
250         */
251        public abstract long getTcpBytesReceived(int which);
252
253        /**
254         * {@hide}
255         */
256        public abstract long getTcpBytesSent(int which);
257
258        public abstract void noteWifiRunningLocked();
259        public abstract void noteWifiStoppedLocked();
260        public abstract void noteFullWifiLockAcquiredLocked();
261        public abstract void noteFullWifiLockReleasedLocked();
262        public abstract void noteScanWifiLockAcquiredLocked();
263        public abstract void noteScanWifiLockReleasedLocked();
264        public abstract void noteWifiMulticastEnabledLocked();
265        public abstract void noteWifiMulticastDisabledLocked();
266        public abstract void noteAudioTurnedOnLocked();
267        public abstract void noteAudioTurnedOffLocked();
268        public abstract void noteVideoTurnedOnLocked();
269        public abstract void noteVideoTurnedOffLocked();
270        public abstract long getWifiRunningTime(long batteryRealtime, int which);
271        public abstract long getFullWifiLockTime(long batteryRealtime, int which);
272        public abstract long getScanWifiLockTime(long batteryRealtime, int which);
273        public abstract long getWifiMulticastTime(long batteryRealtime,
274                                                  int which);
275        public abstract long getAudioTurnedOnTime(long batteryRealtime, int which);
276        public abstract long getVideoTurnedOnTime(long batteryRealtime, int which);
277
278        /**
279         * Note that these must match the constants in android.os.LocalPowerManager.
280         */
281        static final String[] USER_ACTIVITY_TYPES = {
282            "other", "cheek", "touch", "long_touch", "touch_up", "button", "unknown"
283        };
284
285        public static final int NUM_USER_ACTIVITY_TYPES = 7;
286
287        public abstract void noteUserActivityLocked(int type);
288        public abstract boolean hasUserActivity();
289        public abstract int getUserActivityCount(int type, int which);
290
291        public static abstract class Sensor {
292            // Magic sensor number for the GPS.
293            public static final int GPS = -10000;
294
295            public abstract int getHandle();
296
297            public abstract Timer getSensorTime();
298        }
299
300        public class Pid {
301            public long mWakeSum;
302            public long mWakeStart;
303        }
304
305        /**
306         * The statistics associated with a particular process.
307         */
308        public static abstract class Proc {
309
310            public static class ExcessivePower {
311                public static final int TYPE_WAKE = 1;
312                public static final int TYPE_CPU = 2;
313
314                public int type;
315                public long overTime;
316                public long usedTime;
317            }
318
319            /**
320             * Returns the total time (in 1/100 sec) spent executing in user code.
321             *
322             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
323             */
324            public abstract long getUserTime(int which);
325
326            /**
327             * Returns the total time (in 1/100 sec) spent executing in system code.
328             *
329             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
330             */
331            public abstract long getSystemTime(int which);
332
333            /**
334             * Returns the number of times the process has been started.
335             *
336             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
337             */
338            public abstract int getStarts(int which);
339
340            /**
341             * Returns the cpu time spent in microseconds while the process was in the foreground.
342             * @param which one of STATS_TOTAL, STATS_LAST, STATS_CURRENT or STATS_UNPLUGGED
343             * @return foreground cpu time in microseconds
344             */
345            public abstract long getForegroundTime(int which);
346
347            /**
348             * Returns the approximate cpu time spent in microseconds, at a certain CPU speed.
349             * @param speedStep the index of the CPU speed. This is not the actual speed of the
350             * CPU.
351             * @param which one of STATS_TOTAL, STATS_LAST, STATS_CURRENT or STATS_UNPLUGGED
352             * @see BatteryStats#getCpuSpeedSteps()
353             */
354            public abstract long getTimeAtCpuSpeedStep(int speedStep, int which);
355
356            public abstract int countExcessivePowers();
357
358            public abstract ExcessivePower getExcessivePower(int i);
359        }
360
361        /**
362         * The statistics associated with a particular package.
363         */
364        public static abstract class Pkg {
365
366            /**
367             * Returns the number of times this package has done something that could wake up the
368             * device from sleep.
369             *
370             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
371             */
372            public abstract int getWakeups(int which);
373
374            /**
375             * Returns a mapping containing service statistics.
376             */
377            public abstract Map<String, ? extends Serv> getServiceStats();
378
379            /**
380             * The statistics associated with a particular service.
381             */
382            public abstract class Serv {
383
384                /**
385                 * Returns the amount of time spent started.
386                 *
387                 * @param batteryUptime elapsed uptime on battery in microseconds.
388                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
389                 * @return
390                 */
391                public abstract long getStartTime(long batteryUptime, int which);
392
393                /**
394                 * Returns the total number of times startService() has been called.
395                 *
396                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
397                 */
398                public abstract int getStarts(int which);
399
400                /**
401                 * Returns the total number times the service has been launched.
402                 *
403                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
404                 */
405                public abstract int getLaunches(int which);
406            }
407        }
408    }
409
410    public final static class HistoryItem implements Parcelable {
411        public HistoryItem next;
412
413        public long time;
414
415        public static final byte CMD_NULL = -1;
416        public static final byte CMD_UPDATE = 0;
417        public static final byte CMD_START = 1;
418        public static final byte CMD_OVERFLOW = 2;
419
420        public byte cmd;
421
422        public byte batteryLevel;
423        public byte batteryStatus;
424        public byte batteryHealth;
425        public byte batteryPlugType;
426
427        public char batteryTemperature;
428        public char batteryVoltage;
429
430        // Constants from SCREEN_BRIGHTNESS_*
431        public static final int STATE_BRIGHTNESS_MASK = 0x000000f;
432        public static final int STATE_BRIGHTNESS_SHIFT = 0;
433        // Constants from SIGNAL_STRENGTH_*
434        public static final int STATE_SIGNAL_STRENGTH_MASK = 0x00000f0;
435        public static final int STATE_SIGNAL_STRENGTH_SHIFT = 4;
436        // Constants from ServiceState.STATE_*
437        public static final int STATE_PHONE_STATE_MASK = 0x0000f00;
438        public static final int STATE_PHONE_STATE_SHIFT = 8;
439        // Constants from DATA_CONNECTION_*
440        public static final int STATE_DATA_CONNECTION_MASK = 0x000f000;
441        public static final int STATE_DATA_CONNECTION_SHIFT = 12;
442
443        public static final int STATE_BATTERY_PLUGGED_FLAG = 1<<30;
444        public static final int STATE_SCREEN_ON_FLAG = 1<<29;
445        public static final int STATE_GPS_ON_FLAG = 1<<28;
446        public static final int STATE_PHONE_IN_CALL_FLAG = 1<<27;
447        public static final int STATE_PHONE_SCANNING_FLAG = 1<<26;
448        public static final int STATE_WIFI_ON_FLAG = 1<<25;
449        public static final int STATE_WIFI_RUNNING_FLAG = 1<<24;
450        public static final int STATE_WIFI_FULL_LOCK_FLAG = 1<<23;
451        public static final int STATE_WIFI_SCAN_LOCK_FLAG = 1<<22;
452        public static final int STATE_WIFI_MULTICAST_ON_FLAG = 1<<21;
453        public static final int STATE_BLUETOOTH_ON_FLAG = 1<<20;
454        public static final int STATE_AUDIO_ON_FLAG = 1<<19;
455        public static final int STATE_VIDEO_ON_FLAG = 1<<18;
456        public static final int STATE_WAKE_LOCK_FLAG = 1<<17;
457        public static final int STATE_SENSOR_ON_FLAG = 1<<16;
458
459        public static final int MOST_INTERESTING_STATES =
460            STATE_BATTERY_PLUGGED_FLAG | STATE_SCREEN_ON_FLAG
461            | STATE_GPS_ON_FLAG | STATE_PHONE_IN_CALL_FLAG;
462
463        public int states;
464
465        public HistoryItem() {
466        }
467
468        public HistoryItem(long time, Parcel src) {
469            this.time = time;
470            readFromParcel(src);
471        }
472
473        public int describeContents() {
474            return 0;
475        }
476
477        public void writeToParcel(Parcel dest, int flags) {
478            dest.writeLong(time);
479            int bat = (((int)cmd)&0xff)
480                    | ((((int)batteryLevel)<<8)&0xff00)
481                    | ((((int)batteryStatus)<<16)&0xf0000)
482                    | ((((int)batteryHealth)<<20)&0xf00000)
483                    | ((((int)batteryPlugType)<<24)&0xf000000);
484            dest.writeInt(bat);
485            bat = (((int)batteryTemperature)&0xffff)
486                    | ((((int)batteryVoltage)<<16)&0xffff0000);
487            dest.writeInt(bat);
488            dest.writeInt(states);
489        }
490
491        public void writeDelta(Parcel dest, HistoryItem last) {
492            writeToParcel(dest, 0);
493        }
494
495        private void readFromParcel(Parcel src) {
496            int bat = src.readInt();
497            cmd = (byte)(bat&0xff);
498            batteryLevel = (byte)((bat>>8)&0xff);
499            batteryStatus = (byte)((bat>>16)&0xf);
500            batteryHealth = (byte)((bat>>20)&0xf);
501            batteryPlugType = (byte)((bat>>24)&0xf);
502            bat = src.readInt();
503            batteryTemperature = (char)(bat&0xffff);
504            batteryVoltage = (char)((bat>>16)&0xffff);
505            states = src.readInt();
506        }
507
508        public void readDelta(Parcel src, HistoryItem last) {
509            time = src.readLong();
510            readFromParcel(src);
511        }
512
513        public void setTo(HistoryItem o) {
514            time = o.time;
515            cmd = o.cmd;
516            batteryLevel = o.batteryLevel;
517            batteryStatus = o.batteryStatus;
518            batteryHealth = o.batteryHealth;
519            batteryPlugType = o.batteryPlugType;
520            batteryTemperature = o.batteryTemperature;
521            batteryVoltage = o.batteryVoltage;
522            states = o.states;
523        }
524
525        public void setTo(long time, byte cmd, HistoryItem o) {
526            this.time = time;
527            this.cmd = cmd;
528            batteryLevel = o.batteryLevel;
529            batteryStatus = o.batteryStatus;
530            batteryHealth = o.batteryHealth;
531            batteryPlugType = o.batteryPlugType;
532            batteryTemperature = o.batteryTemperature;
533            batteryVoltage = o.batteryVoltage;
534            states = o.states;
535        }
536
537        public boolean same(HistoryItem o) {
538            return batteryLevel == o.batteryLevel
539                    && batteryStatus == o.batteryStatus
540                    && batteryHealth == o.batteryHealth
541                    && batteryPlugType == o.batteryPlugType
542                    && batteryTemperature == o.batteryTemperature
543                    && batteryVoltage == o.batteryVoltage
544                    && states == o.states;
545        }
546    }
547
548    public static final class BitDescription {
549        public final int mask;
550        public final int shift;
551        public final String name;
552        public final String[] values;
553
554        public BitDescription(int mask, String name) {
555            this.mask = mask;
556            this.shift = -1;
557            this.name = name;
558            this.values = null;
559        }
560
561        public BitDescription(int mask, int shift, String name, String[] values) {
562            this.mask = mask;
563            this.shift = shift;
564            this.name = name;
565            this.values = values;
566        }
567    }
568
569    public abstract boolean startIteratingHistoryLocked();
570
571    public abstract boolean getNextHistoryLocked(HistoryItem out);
572
573    public abstract void finishIteratingHistoryLocked();
574
575    public abstract boolean startIteratingOldHistoryLocked();
576
577    public abstract boolean getNextOldHistoryLocked(HistoryItem out);
578
579    public abstract void finishIteratingOldHistoryLocked();
580
581    /**
582     * Return the base time offset for the battery history.
583     */
584    public abstract long getHistoryBaseTime();
585
586    /**
587     * Returns the number of times the device has been started.
588     */
589    public abstract int getStartCount();
590
591    /**
592     * Returns the time in microseconds that the screen has been on while the device was
593     * running on battery.
594     *
595     * {@hide}
596     */
597    public abstract long getScreenOnTime(long batteryRealtime, int which);
598
599    public static final int SCREEN_BRIGHTNESS_DARK = 0;
600    public static final int SCREEN_BRIGHTNESS_DIM = 1;
601    public static final int SCREEN_BRIGHTNESS_MEDIUM = 2;
602    public static final int SCREEN_BRIGHTNESS_LIGHT = 3;
603    public static final int SCREEN_BRIGHTNESS_BRIGHT = 4;
604
605    static final String[] SCREEN_BRIGHTNESS_NAMES = {
606        "dark", "dim", "medium", "light", "bright"
607    };
608
609    public static final int NUM_SCREEN_BRIGHTNESS_BINS = 5;
610
611    /**
612     * Returns the time in microseconds that the screen has been on with
613     * the given brightness
614     *
615     * {@hide}
616     */
617    public abstract long getScreenBrightnessTime(int brightnessBin,
618            long batteryRealtime, int which);
619
620    public abstract int getInputEventCount(int which);
621
622    /**
623     * Returns the time in microseconds that the phone has been on while the device was
624     * running on battery.
625     *
626     * {@hide}
627     */
628    public abstract long getPhoneOnTime(long batteryRealtime, int which);
629
630    /**
631     * Returns the time in microseconds that the phone has been running with
632     * the given signal strength.
633     *
634     * {@hide}
635     */
636    public abstract long getPhoneSignalStrengthTime(int strengthBin,
637            long batteryRealtime, int which);
638
639    /**
640     * Returns the time in microseconds that the phone has been trying to
641     * acquire a signal.
642     *
643     * {@hide}
644     */
645    public abstract long getPhoneSignalScanningTime(
646            long batteryRealtime, int which);
647
648    /**
649     * Returns the number of times the phone has entered the given signal strength.
650     *
651     * {@hide}
652     */
653    public abstract int getPhoneSignalStrengthCount(int strengthBin, int which);
654
655    public static final int DATA_CONNECTION_NONE = 0;
656    public static final int DATA_CONNECTION_GPRS = 1;
657    public static final int DATA_CONNECTION_EDGE = 2;
658    public static final int DATA_CONNECTION_UMTS = 3;
659    public static final int DATA_CONNECTION_CDMA = 4;
660    public static final int DATA_CONNECTION_EVDO_0 = 5;
661    public static final int DATA_CONNECTION_EVDO_A = 6;
662    public static final int DATA_CONNECTION_1xRTT = 7;
663    public static final int DATA_CONNECTION_HSDPA = 8;
664    public static final int DATA_CONNECTION_HSUPA = 9;
665    public static final int DATA_CONNECTION_HSPA = 10;
666    public static final int DATA_CONNECTION_IDEN = 11;
667    public static final int DATA_CONNECTION_EVDO_B = 12;
668    public static final int DATA_CONNECTION_LTE = 13;
669    public static final int DATA_CONNECTION_EHRPD = 14;
670    public static final int DATA_CONNECTION_OTHER = 15;
671
672    static final String[] DATA_CONNECTION_NAMES = {
673        "none", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A",
674        "1xrtt", "hsdpa", "hsupa", "hspa", "iden", "evdo_b", "lte",
675        "ehrpd", "other"
676    };
677
678    public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER+1;
679
680    /**
681     * Returns the time in microseconds that the phone has been running with
682     * the given data connection.
683     *
684     * {@hide}
685     */
686    public abstract long getPhoneDataConnectionTime(int dataType,
687            long batteryRealtime, int which);
688
689    /**
690     * Returns the number of times the phone has entered the given data
691     * connection type.
692     *
693     * {@hide}
694     */
695    public abstract int getPhoneDataConnectionCount(int dataType, int which);
696
697    public static final BitDescription[] HISTORY_STATE_DESCRIPTIONS
698            = new BitDescription[] {
699        new BitDescription(HistoryItem.STATE_BATTERY_PLUGGED_FLAG, "plugged"),
700        new BitDescription(HistoryItem.STATE_SCREEN_ON_FLAG, "screen"),
701        new BitDescription(HistoryItem.STATE_GPS_ON_FLAG, "gps"),
702        new BitDescription(HistoryItem.STATE_PHONE_IN_CALL_FLAG, "phone_in_call"),
703        new BitDescription(HistoryItem.STATE_PHONE_SCANNING_FLAG, "phone_scanning"),
704        new BitDescription(HistoryItem.STATE_WIFI_ON_FLAG, "wifi"),
705        new BitDescription(HistoryItem.STATE_WIFI_RUNNING_FLAG, "wifi_running"),
706        new BitDescription(HistoryItem.STATE_WIFI_FULL_LOCK_FLAG, "wifi_full_lock"),
707        new BitDescription(HistoryItem.STATE_WIFI_SCAN_LOCK_FLAG, "wifi_scan_lock"),
708        new BitDescription(HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG, "wifi_multicast"),
709        new BitDescription(HistoryItem.STATE_BLUETOOTH_ON_FLAG, "bluetooth"),
710        new BitDescription(HistoryItem.STATE_AUDIO_ON_FLAG, "audio"),
711        new BitDescription(HistoryItem.STATE_VIDEO_ON_FLAG, "video"),
712        new BitDescription(HistoryItem.STATE_WAKE_LOCK_FLAG, "wake_lock"),
713        new BitDescription(HistoryItem.STATE_SENSOR_ON_FLAG, "sensor"),
714        new BitDescription(HistoryItem.STATE_BRIGHTNESS_MASK,
715                HistoryItem.STATE_BRIGHTNESS_SHIFT, "brightness",
716                SCREEN_BRIGHTNESS_NAMES),
717        new BitDescription(HistoryItem.STATE_SIGNAL_STRENGTH_MASK,
718                HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT, "signal_strength",
719                SignalStrength.SIGNAL_STRENGTH_NAMES),
720        new BitDescription(HistoryItem.STATE_PHONE_STATE_MASK,
721                HistoryItem.STATE_PHONE_STATE_SHIFT, "phone_state",
722                new String[] {"in", "out", "emergency", "off"}),
723        new BitDescription(HistoryItem.STATE_DATA_CONNECTION_MASK,
724                HistoryItem.STATE_DATA_CONNECTION_SHIFT, "data_conn",
725                DATA_CONNECTION_NAMES),
726    };
727
728    /**
729     * Returns the time in microseconds that wifi has been on while the device was
730     * running on battery.
731     *
732     * {@hide}
733     */
734    public abstract long getWifiOnTime(long batteryRealtime, int which);
735
736    /**
737     * Returns the time in microseconds that wifi has been on and the driver has
738     * been in the running state while the device was running on battery.
739     *
740     * {@hide}
741     */
742    public abstract long getGlobalWifiRunningTime(long batteryRealtime, int which);
743
744    /**
745     * Returns the time in microseconds that bluetooth has been on while the device was
746     * running on battery.
747     *
748     * {@hide}
749     */
750    public abstract long getBluetoothOnTime(long batteryRealtime, int which);
751
752    /**
753     * Return whether we are currently running on battery.
754     */
755    public abstract boolean getIsOnBattery();
756
757    /**
758     * Returns a SparseArray containing the statistics for each uid.
759     */
760    public abstract SparseArray<? extends Uid> getUidStats();
761
762    /**
763     * Returns the current battery uptime in microseconds.
764     *
765     * @param curTime the amount of elapsed realtime in microseconds.
766     */
767    public abstract long getBatteryUptime(long curTime);
768
769    /**
770     * @deprecated use getRadioDataUptime
771     */
772    public long getRadioDataUptimeMs() {
773        return getRadioDataUptime() / 1000;
774    }
775
776    /**
777     * Returns the time that the radio was on for data transfers.
778     * @return the uptime in microseconds while unplugged
779     */
780    public abstract long getRadioDataUptime();
781
782    /**
783     * Returns the current battery realtime in microseconds.
784     *
785     * @param curTime the amount of elapsed realtime in microseconds.
786     */
787    public abstract long getBatteryRealtime(long curTime);
788
789    /**
790     * Returns the battery percentage level at the last time the device was unplugged from power, or
791     * the last time it booted on battery power.
792     */
793    public abstract int getDischargeStartLevel();
794
795    /**
796     * Returns the current battery percentage level if we are in a discharge cycle, otherwise
797     * returns the level at the last plug event.
798     */
799    public abstract int getDischargeCurrentLevel();
800
801    /**
802     * Get the amount the battery has discharged since the stats were
803     * last reset after charging, as a lower-end approximation.
804     */
805    public abstract int getLowDischargeAmountSinceCharge();
806
807    /**
808     * Get the amount the battery has discharged since the stats were
809     * last reset after charging, as an upper-end approximation.
810     */
811    public abstract int getHighDischargeAmountSinceCharge();
812
813    /**
814     * Get the amount the battery has discharged while the screen was on,
815     * since the last time power was unplugged.
816     */
817    public abstract int getDischargeAmountScreenOn();
818
819    /**
820     * Get the amount the battery has discharged while the screen was on,
821     * since the last time the device was charged.
822     */
823    public abstract int getDischargeAmountScreenOnSinceCharge();
824
825    /**
826     * Get the amount the battery has discharged while the screen was off,
827     * since the last time power was unplugged.
828     */
829    public abstract int getDischargeAmountScreenOff();
830
831    /**
832     * Get the amount the battery has discharged while the screen was off,
833     * since the last time the device was charged.
834     */
835    public abstract int getDischargeAmountScreenOffSinceCharge();
836
837    /**
838     * Returns the total, last, or current battery uptime in microseconds.
839     *
840     * @param curTime the elapsed realtime in microseconds.
841     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
842     */
843    public abstract long computeBatteryUptime(long curTime, int which);
844
845    /**
846     * Returns the total, last, or current battery realtime in microseconds.
847     *
848     * @param curTime the current elapsed realtime in microseconds.
849     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
850     */
851    public abstract long computeBatteryRealtime(long curTime, int which);
852
853    /**
854     * Returns the total, last, or current uptime in microseconds.
855     *
856     * @param curTime the current elapsed realtime in microseconds.
857     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
858     */
859    public abstract long computeUptime(long curTime, int which);
860
861    /**
862     * Returns the total, last, or current realtime in microseconds.
863     * *
864     * @param curTime the current elapsed realtime in microseconds.
865     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
866     */
867    public abstract long computeRealtime(long curTime, int which);
868
869    public abstract Map<String, ? extends Timer> getKernelWakelockStats();
870
871    /** Returns the number of different speeds that the CPU can run at */
872    public abstract int getCpuSpeedSteps();
873
874    private final static void formatTimeRaw(StringBuilder out, long seconds) {
875        long days = seconds / (60 * 60 * 24);
876        if (days != 0) {
877            out.append(days);
878            out.append("d ");
879        }
880        long used = days * 60 * 60 * 24;
881
882        long hours = (seconds - used) / (60 * 60);
883        if (hours != 0 || used != 0) {
884            out.append(hours);
885            out.append("h ");
886        }
887        used += hours * 60 * 60;
888
889        long mins = (seconds-used) / 60;
890        if (mins != 0 || used != 0) {
891            out.append(mins);
892            out.append("m ");
893        }
894        used += mins * 60;
895
896        if (seconds != 0 || used != 0) {
897            out.append(seconds-used);
898            out.append("s ");
899        }
900    }
901
902    private final static void formatTime(StringBuilder sb, long time) {
903        long sec = time / 100;
904        formatTimeRaw(sb, sec);
905        sb.append((time - (sec * 100)) * 10);
906        sb.append("ms ");
907    }
908
909    private final static void formatTimeMs(StringBuilder sb, long time) {
910        long sec = time / 1000;
911        formatTimeRaw(sb, sec);
912        sb.append(time - (sec * 1000));
913        sb.append("ms ");
914    }
915
916    private final String formatRatioLocked(long num, long den) {
917        if (den == 0L) {
918            return "---%";
919        }
920        float perc = ((float)num) / ((float)den) * 100;
921        mFormatBuilder.setLength(0);
922        mFormatter.format("%.1f%%", perc);
923        return mFormatBuilder.toString();
924    }
925
926    private final String formatBytesLocked(long bytes) {
927        mFormatBuilder.setLength(0);
928
929        if (bytes < BYTES_PER_KB) {
930            return bytes + "B";
931        } else if (bytes < BYTES_PER_MB) {
932            mFormatter.format("%.2fKB", bytes / (double) BYTES_PER_KB);
933            return mFormatBuilder.toString();
934        } else if (bytes < BYTES_PER_GB){
935            mFormatter.format("%.2fMB", bytes / (double) BYTES_PER_MB);
936            return mFormatBuilder.toString();
937        } else {
938            mFormatter.format("%.2fGB", bytes / (double) BYTES_PER_GB);
939            return mFormatBuilder.toString();
940        }
941    }
942
943    /**
944     *
945     * @param sb a StringBuilder object.
946     * @param timer a Timer object contining the wakelock times.
947     * @param batteryRealtime the current on-battery time in microseconds.
948     * @param name the name of the wakelock.
949     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
950     * @param linePrefix a String to be prepended to each line of output.
951     * @return the line prefix
952     */
953    private static final String printWakeLock(StringBuilder sb, Timer timer,
954            long batteryRealtime, String name, int which, String linePrefix) {
955
956        if (timer != null) {
957            // Convert from microseconds to milliseconds with rounding
958            long totalTimeMicros = timer.getTotalTimeLocked(batteryRealtime, which);
959            long totalTimeMillis = (totalTimeMicros + 500) / 1000;
960
961            int count = timer.getCountLocked(which);
962            if (totalTimeMillis != 0) {
963                sb.append(linePrefix);
964                formatTimeMs(sb, totalTimeMillis);
965                if (name != null) sb.append(name);
966                sb.append(' ');
967                sb.append('(');
968                sb.append(count);
969                sb.append(" times)");
970                return ", ";
971            }
972        }
973        return linePrefix;
974    }
975
976    /**
977     * Checkin version of wakelock printer. Prints simple comma-separated list.
978     *
979     * @param sb a StringBuilder object.
980     * @param timer a Timer object contining the wakelock times.
981     * @param now the current time in microseconds.
982     * @param name the name of the wakelock.
983     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
984     * @param linePrefix a String to be prepended to each line of output.
985     * @return the line prefix
986     */
987    private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, long now,
988            String name, int which, String linePrefix) {
989        long totalTimeMicros = 0;
990        int count = 0;
991        if (timer != null) {
992            totalTimeMicros = timer.getTotalTimeLocked(now, which);
993            count = timer.getCountLocked(which);
994        }
995        sb.append(linePrefix);
996        sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding
997        sb.append(',');
998        sb.append(name != null ? name + "," : "");
999        sb.append(count);
1000        return ",";
1001    }
1002
1003    /**
1004     * Dump a comma-separated line of values for terse checkin mode.
1005     *
1006     * @param pw the PageWriter to dump log to
1007     * @param category category of data (e.g. "total", "last", "unplugged", "current" )
1008     * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" ,  "process", "network")
1009     * @param args type-dependent data arguments
1010     */
1011    private static final void dumpLine(PrintWriter pw, int uid, String category, String type,
1012           Object... args ) {
1013        pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
1014        pw.print(uid); pw.print(',');
1015        pw.print(category); pw.print(',');
1016        pw.print(type);
1017
1018        for (Object arg : args) {
1019            pw.print(',');
1020            pw.print(arg);
1021        }
1022        pw.print('\n');
1023    }
1024
1025    /**
1026     * Checkin server version of dump to produce more compact, computer-readable log.
1027     *
1028     * NOTE: all times are expressed in 'ms'.
1029     */
1030    public final void dumpCheckinLocked(PrintWriter pw, int which, int reqUid) {
1031        final long rawUptime = SystemClock.uptimeMillis() * 1000;
1032        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
1033        final long batteryUptime = getBatteryUptime(rawUptime);
1034        final long batteryRealtime = getBatteryRealtime(rawRealtime);
1035        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
1036        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
1037        final long totalRealtime = computeRealtime(rawRealtime, which);
1038        final long totalUptime = computeUptime(rawUptime, which);
1039        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1040        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1041        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1042        final long wifiRunningTime = getGlobalWifiRunningTime(batteryRealtime, which);
1043        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1044
1045        StringBuilder sb = new StringBuilder(128);
1046
1047        SparseArray<? extends Uid> uidStats = getUidStats();
1048        final int NU = uidStats.size();
1049
1050        String category = STAT_NAMES[which];
1051
1052        // Dump "battery" stat
1053        dumpLine(pw, 0 /* uid */, category, BATTERY_DATA,
1054                which == STATS_SINCE_CHARGED ? getStartCount() : "N/A",
1055                whichBatteryRealtime / 1000, whichBatteryUptime / 1000,
1056                totalRealtime / 1000, totalUptime / 1000);
1057
1058        // Calculate total network and wakelock times across all uids.
1059        long rxTotal = 0;
1060        long txTotal = 0;
1061        long fullWakeLockTimeTotal = 0;
1062        long partialWakeLockTimeTotal = 0;
1063
1064        for (int iu = 0; iu < NU; iu++) {
1065            Uid u = uidStats.valueAt(iu);
1066            rxTotal += u.getTcpBytesReceived(which);
1067            txTotal += u.getTcpBytesSent(which);
1068
1069            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1070            if (wakelocks.size() > 0) {
1071                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1072                        : wakelocks.entrySet()) {
1073                    Uid.Wakelock wl = ent.getValue();
1074
1075                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1076                    if (fullWakeTimer != null) {
1077                        fullWakeLockTimeTotal += fullWakeTimer.getTotalTimeLocked(batteryRealtime, which);
1078                    }
1079
1080                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1081                    if (partialWakeTimer != null) {
1082                        partialWakeLockTimeTotal += partialWakeTimer.getTotalTimeLocked(
1083                            batteryRealtime, which);
1084                    }
1085                }
1086            }
1087        }
1088
1089        // Dump misc stats
1090        dumpLine(pw, 0 /* uid */, category, MISC_DATA,
1091                screenOnTime / 1000, phoneOnTime / 1000, wifiOnTime / 1000,
1092                wifiRunningTime / 1000, bluetoothOnTime / 1000, rxTotal, txTotal,
1093                fullWakeLockTimeTotal, partialWakeLockTimeTotal,
1094                getInputEventCount(which));
1095
1096        // Dump screen brightness stats
1097        Object[] args = new Object[NUM_SCREEN_BRIGHTNESS_BINS];
1098        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1099            args[i] = getScreenBrightnessTime(i, batteryRealtime, which) / 1000;
1100        }
1101        dumpLine(pw, 0 /* uid */, category, SCREEN_BRIGHTNESS_DATA, args);
1102
1103        // Dump signal strength stats
1104        args = new Object[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
1105        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
1106            args[i] = getPhoneSignalStrengthTime(i, batteryRealtime, which) / 1000;
1107        }
1108        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_TIME_DATA, args);
1109        dumpLine(pw, 0 /* uid */, category, SIGNAL_SCANNING_TIME_DATA,
1110                getPhoneSignalScanningTime(batteryRealtime, which) / 1000);
1111        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
1112            args[i] = getPhoneSignalStrengthCount(i, which);
1113        }
1114        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_COUNT_DATA, args);
1115
1116        // Dump network type stats
1117        args = new Object[NUM_DATA_CONNECTION_TYPES];
1118        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1119            args[i] = getPhoneDataConnectionTime(i, batteryRealtime, which) / 1000;
1120        }
1121        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_TIME_DATA, args);
1122        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1123            args[i] = getPhoneDataConnectionCount(i, which);
1124        }
1125        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_COUNT_DATA, args);
1126
1127        if (which == STATS_SINCE_UNPLUGGED) {
1128            dumpLine(pw, 0 /* uid */, category, BATTERY_LEVEL_DATA, getDischargeStartLevel(),
1129                    getDischargeCurrentLevel());
1130        }
1131
1132        if (which == STATS_SINCE_UNPLUGGED) {
1133            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
1134                    getDischargeStartLevel()-getDischargeCurrentLevel(),
1135                    getDischargeStartLevel()-getDischargeCurrentLevel(),
1136                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
1137        } else {
1138            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
1139                    getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(),
1140                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
1141        }
1142
1143        if (reqUid < 0) {
1144            Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1145            if (kernelWakelocks.size() > 0) {
1146                for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1147                    sb.setLength(0);
1148                    printWakeLockCheckin(sb, ent.getValue(), batteryRealtime, null, which, "");
1149
1150                    dumpLine(pw, 0 /* uid */, category, KERNEL_WAKELOCK_DATA, ent.getKey(),
1151                            sb.toString());
1152                }
1153            }
1154        }
1155
1156        for (int iu = 0; iu < NU; iu++) {
1157            final int uid = uidStats.keyAt(iu);
1158            if (reqUid >= 0 && uid != reqUid) {
1159                continue;
1160            }
1161            Uid u = uidStats.valueAt(iu);
1162            // Dump Network stats per uid, if any
1163            long rx = u.getTcpBytesReceived(which);
1164            long tx = u.getTcpBytesSent(which);
1165            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
1166            long scanWifiLockOnTime = u.getScanWifiLockTime(batteryRealtime, which);
1167            long uidWifiRunningTime = u.getWifiRunningTime(batteryRealtime, which);
1168
1169            if (rx > 0 || tx > 0) dumpLine(pw, uid, category, NETWORK_DATA, rx, tx);
1170
1171            if (fullWifiLockOnTime != 0 || scanWifiLockOnTime != 0
1172                    || uidWifiRunningTime != 0) {
1173                dumpLine(pw, uid, category, WIFI_LOCK_DATA,
1174                        fullWifiLockOnTime, scanWifiLockOnTime, uidWifiRunningTime);
1175            }
1176
1177            if (u.hasUserActivity()) {
1178                args = new Object[Uid.NUM_USER_ACTIVITY_TYPES];
1179                boolean hasData = false;
1180                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
1181                    int val = u.getUserActivityCount(i, which);
1182                    args[i] = val;
1183                    if (val != 0) hasData = true;
1184                }
1185                if (hasData) {
1186                    dumpLine(pw, 0 /* uid */, category, USER_ACTIVITY_DATA, args);
1187                }
1188            }
1189
1190            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1191            if (wakelocks.size() > 0) {
1192                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1193                        : wakelocks.entrySet()) {
1194                    Uid.Wakelock wl = ent.getValue();
1195                    String linePrefix = "";
1196                    sb.setLength(0);
1197                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL),
1198                            batteryRealtime, "f", which, linePrefix);
1199                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL),
1200                            batteryRealtime, "p", which, linePrefix);
1201                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW),
1202                            batteryRealtime, "w", which, linePrefix);
1203
1204                    // Only log if we had at lease one wakelock...
1205                    if (sb.length() > 0) {
1206                       dumpLine(pw, uid, category, WAKELOCK_DATA, ent.getKey(), sb.toString());
1207                    }
1208                }
1209            }
1210
1211            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
1212            if (sensors.size() > 0)  {
1213                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
1214                        : sensors.entrySet()) {
1215                    Uid.Sensor se = ent.getValue();
1216                    int sensorNumber = ent.getKey();
1217                    Timer timer = se.getSensorTime();
1218                    if (timer != null) {
1219                        // Convert from microseconds to milliseconds with rounding
1220                        long totalTime = (timer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
1221                        int count = timer.getCountLocked(which);
1222                        if (totalTime != 0) {
1223                            dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count);
1224                        }
1225                    }
1226                }
1227            }
1228
1229            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
1230            if (processStats.size() > 0) {
1231                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
1232                        : processStats.entrySet()) {
1233                    Uid.Proc ps = ent.getValue();
1234
1235                    long userTime = ps.getUserTime(which);
1236                    long systemTime = ps.getSystemTime(which);
1237                    int starts = ps.getStarts(which);
1238
1239                    if (userTime != 0 || systemTime != 0 || starts != 0) {
1240                        dumpLine(pw, uid, category, PROCESS_DATA,
1241                                ent.getKey(), // proc
1242                                userTime * 10, // cpu time in ms
1243                                systemTime * 10, // user time in ms
1244                                starts); // process starts
1245                    }
1246                }
1247            }
1248
1249            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
1250            if (packageStats.size() > 0) {
1251                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
1252                        : packageStats.entrySet()) {
1253
1254                    Uid.Pkg ps = ent.getValue();
1255                    int wakeups = ps.getWakeups(which);
1256                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
1257                    for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
1258                            : serviceStats.entrySet()) {
1259                        BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
1260                        long startTime = ss.getStartTime(batteryUptime, which);
1261                        int starts = ss.getStarts(which);
1262                        int launches = ss.getLaunches(which);
1263                        if (startTime != 0 || starts != 0 || launches != 0) {
1264                            dumpLine(pw, uid, category, APK_DATA,
1265                                    wakeups, // wakeup alarms
1266                                    ent.getKey(), // Apk
1267                                    sent.getKey(), // service
1268                                    startTime / 1000, // time spent started, in ms
1269                                    starts,
1270                                    launches);
1271                        }
1272                    }
1273                }
1274            }
1275        }
1276    }
1277
1278    @SuppressWarnings("unused")
1279    public final void dumpLocked(PrintWriter pw, String prefix, int which, int reqUid) {
1280        final long rawUptime = SystemClock.uptimeMillis() * 1000;
1281        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
1282        final long batteryUptime = getBatteryUptime(rawUptime);
1283        final long batteryRealtime = getBatteryRealtime(rawRealtime);
1284
1285        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
1286        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
1287        final long totalRealtime = computeRealtime(rawRealtime, which);
1288        final long totalUptime = computeUptime(rawUptime, which);
1289
1290        StringBuilder sb = new StringBuilder(128);
1291
1292        SparseArray<? extends Uid> uidStats = getUidStats();
1293        final int NU = uidStats.size();
1294
1295        sb.setLength(0);
1296        sb.append(prefix);
1297                sb.append("  Time on battery: ");
1298                formatTimeMs(sb, whichBatteryRealtime / 1000); sb.append("(");
1299                sb.append(formatRatioLocked(whichBatteryRealtime, totalRealtime));
1300                sb.append(") realtime, ");
1301                formatTimeMs(sb, whichBatteryUptime / 1000);
1302                sb.append("("); sb.append(formatRatioLocked(whichBatteryUptime, totalRealtime));
1303                sb.append(") uptime");
1304        pw.println(sb.toString());
1305        sb.setLength(0);
1306        sb.append(prefix);
1307                sb.append("  Total run time: ");
1308                formatTimeMs(sb, totalRealtime / 1000);
1309                sb.append("realtime, ");
1310                formatTimeMs(sb, totalUptime / 1000);
1311                sb.append("uptime, ");
1312        pw.println(sb.toString());
1313
1314        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1315        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1316        final long wifiRunningTime = getGlobalWifiRunningTime(batteryRealtime, which);
1317        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1318        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1319        sb.setLength(0);
1320        sb.append(prefix);
1321                sb.append("  Screen on: "); formatTimeMs(sb, screenOnTime / 1000);
1322                sb.append("("); sb.append(formatRatioLocked(screenOnTime, whichBatteryRealtime));
1323                sb.append("), Input events: "); sb.append(getInputEventCount(which));
1324                sb.append(", Active phone call: "); formatTimeMs(sb, phoneOnTime / 1000);
1325                sb.append("("); sb.append(formatRatioLocked(phoneOnTime, whichBatteryRealtime));
1326                sb.append(")");
1327        pw.println(sb.toString());
1328        sb.setLength(0);
1329        sb.append(prefix);
1330        sb.append("  Screen brightnesses: ");
1331        boolean didOne = false;
1332        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1333            final long time = getScreenBrightnessTime(i, batteryRealtime, which);
1334            if (time == 0) {
1335                continue;
1336            }
1337            if (didOne) sb.append(", ");
1338            didOne = true;
1339            sb.append(SCREEN_BRIGHTNESS_NAMES[i]);
1340            sb.append(" ");
1341            formatTimeMs(sb, time/1000);
1342            sb.append("(");
1343            sb.append(formatRatioLocked(time, screenOnTime));
1344            sb.append(")");
1345        }
1346        if (!didOne) sb.append("No activity");
1347        pw.println(sb.toString());
1348
1349        // Calculate total network and wakelock times across all uids.
1350        long rxTotal = 0;
1351        long txTotal = 0;
1352        long fullWakeLockTimeTotalMicros = 0;
1353        long partialWakeLockTimeTotalMicros = 0;
1354
1355        if (reqUid < 0) {
1356            Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1357            if (kernelWakelocks.size() > 0) {
1358                for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1359
1360                    String linePrefix = ": ";
1361                    sb.setLength(0);
1362                    sb.append(prefix);
1363                    sb.append("  Kernel Wake lock ");
1364                    sb.append(ent.getKey());
1365                    linePrefix = printWakeLock(sb, ent.getValue(), batteryRealtime, null, which,
1366                            linePrefix);
1367                    if (!linePrefix.equals(": ")) {
1368                        sb.append(" realtime");
1369                        // Only print out wake locks that were held
1370                        pw.println(sb.toString());
1371                    }
1372                }
1373            }
1374        }
1375
1376        for (int iu = 0; iu < NU; iu++) {
1377            Uid u = uidStats.valueAt(iu);
1378            rxTotal += u.getTcpBytesReceived(which);
1379            txTotal += u.getTcpBytesSent(which);
1380
1381            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1382            if (wakelocks.size() > 0) {
1383                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1384                        : wakelocks.entrySet()) {
1385                    Uid.Wakelock wl = ent.getValue();
1386
1387                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1388                    if (fullWakeTimer != null) {
1389                        fullWakeLockTimeTotalMicros += fullWakeTimer.getTotalTimeLocked(
1390                                batteryRealtime, which);
1391                    }
1392
1393                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1394                    if (partialWakeTimer != null) {
1395                        partialWakeLockTimeTotalMicros += partialWakeTimer.getTotalTimeLocked(
1396                                batteryRealtime, which);
1397                    }
1398                }
1399            }
1400        }
1401
1402        pw.print(prefix);
1403                pw.print("  Total received: "); pw.print(formatBytesLocked(rxTotal));
1404                pw.print(", Total sent: "); pw.println(formatBytesLocked(txTotal));
1405        sb.setLength(0);
1406        sb.append(prefix);
1407                sb.append("  Total full wakelock time: "); formatTimeMs(sb,
1408                        (fullWakeLockTimeTotalMicros + 500) / 1000);
1409                sb.append(", Total partial waklock time: "); formatTimeMs(sb,
1410                        (partialWakeLockTimeTotalMicros + 500) / 1000);
1411        pw.println(sb.toString());
1412
1413        sb.setLength(0);
1414        sb.append(prefix);
1415        sb.append("  Signal levels: ");
1416        didOne = false;
1417        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
1418            final long time = getPhoneSignalStrengthTime(i, batteryRealtime, which);
1419            if (time == 0) {
1420                continue;
1421            }
1422            if (didOne) sb.append(", ");
1423            didOne = true;
1424            sb.append(SignalStrength.SIGNAL_STRENGTH_NAMES[i]);
1425            sb.append(" ");
1426            formatTimeMs(sb, time/1000);
1427            sb.append("(");
1428            sb.append(formatRatioLocked(time, whichBatteryRealtime));
1429            sb.append(") ");
1430            sb.append(getPhoneSignalStrengthCount(i, which));
1431            sb.append("x");
1432        }
1433        if (!didOne) sb.append("No activity");
1434        pw.println(sb.toString());
1435
1436        sb.setLength(0);
1437        sb.append(prefix);
1438        sb.append("  Signal scanning time: ");
1439        formatTimeMs(sb, getPhoneSignalScanningTime(batteryRealtime, which) / 1000);
1440        pw.println(sb.toString());
1441
1442        sb.setLength(0);
1443        sb.append(prefix);
1444        sb.append("  Radio types: ");
1445        didOne = false;
1446        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1447            final long time = getPhoneDataConnectionTime(i, batteryRealtime, which);
1448            if (time == 0) {
1449                continue;
1450            }
1451            if (didOne) sb.append(", ");
1452            didOne = true;
1453            sb.append(DATA_CONNECTION_NAMES[i]);
1454            sb.append(" ");
1455            formatTimeMs(sb, time/1000);
1456            sb.append("(");
1457            sb.append(formatRatioLocked(time, whichBatteryRealtime));
1458            sb.append(") ");
1459            sb.append(getPhoneDataConnectionCount(i, which));
1460            sb.append("x");
1461        }
1462        if (!didOne) sb.append("No activity");
1463        pw.println(sb.toString());
1464
1465        sb.setLength(0);
1466        sb.append(prefix);
1467        sb.append("  Radio data uptime when unplugged: ");
1468        sb.append(getRadioDataUptime() / 1000);
1469        sb.append(" ms");
1470        pw.println(sb.toString());
1471
1472        sb.setLength(0);
1473        sb.append(prefix);
1474                sb.append("  Wifi on: "); formatTimeMs(sb, wifiOnTime / 1000);
1475                sb.append("("); sb.append(formatRatioLocked(wifiOnTime, whichBatteryRealtime));
1476                sb.append("), Wifi running: "); formatTimeMs(sb, wifiRunningTime / 1000);
1477                sb.append("("); sb.append(formatRatioLocked(wifiRunningTime, whichBatteryRealtime));
1478                sb.append("), Bluetooth on: "); formatTimeMs(sb, bluetoothOnTime / 1000);
1479                sb.append("("); sb.append(formatRatioLocked(bluetoothOnTime, whichBatteryRealtime));
1480                sb.append(")");
1481        pw.println(sb.toString());
1482
1483        pw.println(" ");
1484
1485        if (which == STATS_SINCE_UNPLUGGED) {
1486            if (getIsOnBattery()) {
1487                pw.print(prefix); pw.println("  Device is currently unplugged");
1488                pw.print(prefix); pw.print("    Discharge cycle start level: ");
1489                        pw.println(getDischargeStartLevel());
1490                pw.print(prefix); pw.print("    Discharge cycle current level: ");
1491                        pw.println(getDischargeCurrentLevel());
1492            } else {
1493                pw.print(prefix); pw.println("  Device is currently plugged into power");
1494                pw.print(prefix); pw.print("    Last discharge cycle start level: ");
1495                        pw.println(getDischargeStartLevel());
1496                pw.print(prefix); pw.print("    Last discharge cycle end level: ");
1497                        pw.println(getDischargeCurrentLevel());
1498            }
1499            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
1500                    pw.println(getDischargeAmountScreenOn());
1501            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
1502                    pw.println(getDischargeAmountScreenOff());
1503            pw.println(" ");
1504        } else {
1505            pw.print(prefix); pw.println("  Device battery use since last full charge");
1506            pw.print(prefix); pw.print("    Amount discharged (lower bound): ");
1507                    pw.println(getLowDischargeAmountSinceCharge());
1508            pw.print(prefix); pw.print("    Amount discharged (upper bound): ");
1509                    pw.println(getHighDischargeAmountSinceCharge());
1510            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
1511                    pw.println(getDischargeAmountScreenOnSinceCharge());
1512            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
1513                    pw.println(getDischargeAmountScreenOffSinceCharge());
1514            pw.println(" ");
1515        }
1516
1517
1518        for (int iu=0; iu<NU; iu++) {
1519            final int uid = uidStats.keyAt(iu);
1520            if (reqUid >= 0 && uid != reqUid && uid != Process.SYSTEM_UID) {
1521                continue;
1522            }
1523
1524            Uid u = uidStats.valueAt(iu);
1525
1526            pw.println(prefix + "  #" + uid + ":");
1527            boolean uidActivity = false;
1528
1529            long tcpReceived = u.getTcpBytesReceived(which);
1530            long tcpSent = u.getTcpBytesSent(which);
1531            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
1532            long scanWifiLockOnTime = u.getScanWifiLockTime(batteryRealtime, which);
1533            long uidWifiRunningTime = u.getWifiRunningTime(batteryRealtime, which);
1534
1535            if (tcpReceived != 0 || tcpSent != 0) {
1536                pw.print(prefix); pw.print("    Network: ");
1537                        pw.print(formatBytesLocked(tcpReceived)); pw.print(" received, ");
1538                        pw.print(formatBytesLocked(tcpSent)); pw.println(" sent");
1539            }
1540
1541            if (u.hasUserActivity()) {
1542                boolean hasData = false;
1543                for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1544                    int val = u.getUserActivityCount(i, which);
1545                    if (val != 0) {
1546                        if (!hasData) {
1547                            sb.setLength(0);
1548                            sb.append("    User activity: ");
1549                            hasData = true;
1550                        } else {
1551                            sb.append(", ");
1552                        }
1553                        sb.append(val);
1554                        sb.append(" ");
1555                        sb.append(Uid.USER_ACTIVITY_TYPES[i]);
1556                    }
1557                }
1558                if (hasData) {
1559                    pw.println(sb.toString());
1560                }
1561            }
1562
1563            if (fullWifiLockOnTime != 0 || scanWifiLockOnTime != 0
1564                    || uidWifiRunningTime != 0) {
1565                sb.setLength(0);
1566                sb.append(prefix); sb.append("    Wifi Running: ");
1567                        formatTimeMs(sb, uidWifiRunningTime / 1000);
1568                        sb.append("("); sb.append(formatRatioLocked(uidWifiRunningTime,
1569                                whichBatteryRealtime)); sb.append(")\n");
1570                sb.append(prefix); sb.append("    Full Wifi Lock: ");
1571                        formatTimeMs(sb, fullWifiLockOnTime / 1000);
1572                        sb.append("("); sb.append(formatRatioLocked(fullWifiLockOnTime,
1573                                whichBatteryRealtime)); sb.append(")\n");
1574                sb.append(prefix); sb.append("    Scan Wifi Lock: ");
1575                        formatTimeMs(sb, scanWifiLockOnTime / 1000);
1576                        sb.append("("); sb.append(formatRatioLocked(scanWifiLockOnTime,
1577                                whichBatteryRealtime)); sb.append(")");
1578                pw.println(sb.toString());
1579            }
1580
1581            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1582            if (wakelocks.size() > 0) {
1583                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1584                    : wakelocks.entrySet()) {
1585                    Uid.Wakelock wl = ent.getValue();
1586                    String linePrefix = ": ";
1587                    sb.setLength(0);
1588                    sb.append(prefix);
1589                    sb.append("    Wake lock ");
1590                    sb.append(ent.getKey());
1591                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), batteryRealtime,
1592                            "full", which, linePrefix);
1593                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), batteryRealtime,
1594                            "partial", which, linePrefix);
1595                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), batteryRealtime,
1596                            "window", which, linePrefix);
1597                    if (!linePrefix.equals(": ")) {
1598                        sb.append(" realtime");
1599                        // Only print out wake locks that were held
1600                        pw.println(sb.toString());
1601                        uidActivity = true;
1602                    }
1603                }
1604            }
1605
1606            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
1607            if (sensors.size() > 0) {
1608                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
1609                    : sensors.entrySet()) {
1610                    Uid.Sensor se = ent.getValue();
1611                    int sensorNumber = ent.getKey();
1612                    sb.setLength(0);
1613                    sb.append(prefix);
1614                    sb.append("    Sensor ");
1615                    int handle = se.getHandle();
1616                    if (handle == Uid.Sensor.GPS) {
1617                        sb.append("GPS");
1618                    } else {
1619                        sb.append(handle);
1620                    }
1621                    sb.append(": ");
1622
1623                    Timer timer = se.getSensorTime();
1624                    if (timer != null) {
1625                        // Convert from microseconds to milliseconds with rounding
1626                        long totalTime = (timer.getTotalTimeLocked(
1627                                batteryRealtime, which) + 500) / 1000;
1628                        int count = timer.getCountLocked(which);
1629                        //timer.logState();
1630                        if (totalTime != 0) {
1631                            formatTimeMs(sb, totalTime);
1632                            sb.append("realtime (");
1633                            sb.append(count);
1634                            sb.append(" times)");
1635                        } else {
1636                            sb.append("(not used)");
1637                        }
1638                    } else {
1639                        sb.append("(not used)");
1640                    }
1641
1642                    pw.println(sb.toString());
1643                    uidActivity = true;
1644                }
1645            }
1646
1647            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
1648            if (processStats.size() > 0) {
1649                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
1650                    : processStats.entrySet()) {
1651                    Uid.Proc ps = ent.getValue();
1652                    long userTime;
1653                    long systemTime;
1654                    int starts;
1655                    int numExcessive;
1656
1657                    userTime = ps.getUserTime(which);
1658                    systemTime = ps.getSystemTime(which);
1659                    starts = ps.getStarts(which);
1660                    numExcessive = which == STATS_SINCE_CHARGED
1661                            ? ps.countExcessivePowers() : 0;
1662
1663                    if (userTime != 0 || systemTime != 0 || starts != 0
1664                            || numExcessive != 0) {
1665                        sb.setLength(0);
1666                        sb.append(prefix); sb.append("    Proc ");
1667                                sb.append(ent.getKey()); sb.append(":\n");
1668                        sb.append(prefix); sb.append("      CPU: ");
1669                                formatTime(sb, userTime); sb.append("usr + ");
1670                                formatTime(sb, systemTime); sb.append("krn");
1671                        if (starts != 0) {
1672                            sb.append("\n"); sb.append(prefix); sb.append("      ");
1673                                    sb.append(starts); sb.append(" proc starts");
1674                        }
1675                        pw.println(sb.toString());
1676                        for (int e=0; e<numExcessive; e++) {
1677                            Uid.Proc.ExcessivePower ew = ps.getExcessivePower(e);
1678                            if (ew != null) {
1679                                pw.print(prefix); pw.print("      * Killed for ");
1680                                        if (ew.type == Uid.Proc.ExcessivePower.TYPE_WAKE) {
1681                                            pw.print("wake lock");
1682                                        } else if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) {
1683                                            pw.print("cpu");
1684                                        } else {
1685                                            pw.print("unknown");
1686                                        }
1687                                        pw.print(" use: ");
1688                                        TimeUtils.formatDuration(ew.usedTime, pw);
1689                                        pw.print(" over ");
1690                                        TimeUtils.formatDuration(ew.overTime, pw);
1691                                        pw.print(" (");
1692                                        pw.print((ew.usedTime*100)/ew.overTime);
1693                                        pw.println("%)");
1694                            }
1695                        }
1696                        uidActivity = true;
1697                    }
1698                }
1699            }
1700
1701            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
1702            if (packageStats.size() > 0) {
1703                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
1704                    : packageStats.entrySet()) {
1705                    pw.print(prefix); pw.print("    Apk "); pw.print(ent.getKey()); pw.println(":");
1706                    boolean apkActivity = false;
1707                    Uid.Pkg ps = ent.getValue();
1708                    int wakeups = ps.getWakeups(which);
1709                    if (wakeups != 0) {
1710                        pw.print(prefix); pw.print("      ");
1711                                pw.print(wakeups); pw.println(" wakeup alarms");
1712                        apkActivity = true;
1713                    }
1714                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
1715                    if (serviceStats.size() > 0) {
1716                        for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
1717                                : serviceStats.entrySet()) {
1718                            BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
1719                            long startTime = ss.getStartTime(batteryUptime, which);
1720                            int starts = ss.getStarts(which);
1721                            int launches = ss.getLaunches(which);
1722                            if (startTime != 0 || starts != 0 || launches != 0) {
1723                                sb.setLength(0);
1724                                sb.append(prefix); sb.append("      Service ");
1725                                        sb.append(sent.getKey()); sb.append(":\n");
1726                                sb.append(prefix); sb.append("        Created for: ");
1727                                        formatTimeMs(sb, startTime / 1000);
1728                                        sb.append(" uptime\n");
1729                                sb.append(prefix); sb.append("        Starts: ");
1730                                        sb.append(starts);
1731                                        sb.append(", launches: "); sb.append(launches);
1732                                pw.println(sb.toString());
1733                                apkActivity = true;
1734                            }
1735                        }
1736                    }
1737                    if (!apkActivity) {
1738                        pw.print(prefix); pw.println("      (nothing executed)");
1739                    }
1740                    uidActivity = true;
1741                }
1742            }
1743            if (!uidActivity) {
1744                pw.print(prefix); pw.println("    (nothing executed)");
1745            }
1746        }
1747    }
1748
1749    static void printBitDescriptions(PrintWriter pw, int oldval, int newval, BitDescription[] descriptions) {
1750        int diff = oldval ^ newval;
1751        if (diff == 0) return;
1752        for (int i=0; i<descriptions.length; i++) {
1753            BitDescription bd = descriptions[i];
1754            if ((diff&bd.mask) != 0) {
1755                if (bd.shift < 0) {
1756                    pw.print((newval&bd.mask) != 0 ? " +" : " -");
1757                    pw.print(bd.name);
1758                } else {
1759                    pw.print(" ");
1760                    pw.print(bd.name);
1761                    pw.print("=");
1762                    int val = (newval&bd.mask)>>bd.shift;
1763                    if (bd.values != null && val >= 0 && val < bd.values.length) {
1764                        pw.print(bd.values[val]);
1765                    } else {
1766                        pw.print(val);
1767                    }
1768                }
1769            }
1770        }
1771    }
1772
1773    public void prepareForDumpLocked() {
1774    }
1775
1776    public static class HistoryPrinter {
1777        int oldState = 0;
1778        int oldStatus = -1;
1779        int oldHealth = -1;
1780        int oldPlug = -1;
1781        int oldTemp = -1;
1782        int oldVolt = -1;
1783
1784        public void printNextItem(PrintWriter pw, HistoryItem rec, long now) {
1785            pw.print("  ");
1786            TimeUtils.formatDuration(rec.time-now, pw, TimeUtils.HUNDRED_DAY_FIELD_LEN);
1787            pw.print(" ");
1788            if (rec.cmd == HistoryItem.CMD_START) {
1789                pw.println(" START");
1790            } else if (rec.cmd == HistoryItem.CMD_OVERFLOW) {
1791                pw.println(" *OVERFLOW*");
1792            } else {
1793                if (rec.batteryLevel < 10) pw.print("00");
1794                else if (rec.batteryLevel < 100) pw.print("0");
1795                pw.print(rec.batteryLevel);
1796                pw.print(" ");
1797                if (rec.states < 0x10) pw.print("0000000");
1798                else if (rec.states < 0x100) pw.print("000000");
1799                else if (rec.states < 0x1000) pw.print("00000");
1800                else if (rec.states < 0x10000) pw.print("0000");
1801                else if (rec.states < 0x100000) pw.print("000");
1802                else if (rec.states < 0x1000000) pw.print("00");
1803                else if (rec.states < 0x10000000) pw.print("0");
1804                pw.print(Integer.toHexString(rec.states));
1805                if (oldStatus != rec.batteryStatus) {
1806                    oldStatus = rec.batteryStatus;
1807                    pw.print(" status=");
1808                    switch (oldStatus) {
1809                        case BatteryManager.BATTERY_STATUS_UNKNOWN:
1810                            pw.print("unknown");
1811                            break;
1812                        case BatteryManager.BATTERY_STATUS_CHARGING:
1813                            pw.print("charging");
1814                            break;
1815                        case BatteryManager.BATTERY_STATUS_DISCHARGING:
1816                            pw.print("discharging");
1817                            break;
1818                        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
1819                            pw.print("not-charging");
1820                            break;
1821                        case BatteryManager.BATTERY_STATUS_FULL:
1822                            pw.print("full");
1823                            break;
1824                        default:
1825                            pw.print(oldStatus);
1826                            break;
1827                    }
1828                }
1829                if (oldHealth != rec.batteryHealth) {
1830                    oldHealth = rec.batteryHealth;
1831                    pw.print(" health=");
1832                    switch (oldHealth) {
1833                        case BatteryManager.BATTERY_HEALTH_UNKNOWN:
1834                            pw.print("unknown");
1835                            break;
1836                        case BatteryManager.BATTERY_HEALTH_GOOD:
1837                            pw.print("good");
1838                            break;
1839                        case BatteryManager.BATTERY_HEALTH_OVERHEAT:
1840                            pw.print("overheat");
1841                            break;
1842                        case BatteryManager.BATTERY_HEALTH_DEAD:
1843                            pw.print("dead");
1844                            break;
1845                        case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
1846                            pw.print("over-voltage");
1847                            break;
1848                        case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
1849                            pw.print("failure");
1850                            break;
1851                        default:
1852                            pw.print(oldHealth);
1853                            break;
1854                    }
1855                }
1856                if (oldPlug != rec.batteryPlugType) {
1857                    oldPlug = rec.batteryPlugType;
1858                    pw.print(" plug=");
1859                    switch (oldPlug) {
1860                        case 0:
1861                            pw.print("none");
1862                            break;
1863                        case BatteryManager.BATTERY_PLUGGED_AC:
1864                            pw.print("ac");
1865                            break;
1866                        case BatteryManager.BATTERY_PLUGGED_USB:
1867                            pw.print("usb");
1868                            break;
1869                        default:
1870                            pw.print(oldPlug);
1871                            break;
1872                    }
1873                }
1874                if (oldTemp != rec.batteryTemperature) {
1875                    oldTemp = rec.batteryTemperature;
1876                    pw.print(" temp=");
1877                    pw.print(oldTemp);
1878                }
1879                if (oldVolt != rec.batteryVoltage) {
1880                    oldVolt = rec.batteryVoltage;
1881                    pw.print(" volt=");
1882                    pw.print(oldVolt);
1883                }
1884                printBitDescriptions(pw, oldState, rec.states,
1885                        HISTORY_STATE_DESCRIPTIONS);
1886                pw.println();
1887            }
1888            oldState = rec.states;
1889        }
1890    }
1891
1892    /**
1893     * Dumps a human-readable summary of the battery statistics to the given PrintWriter.
1894     *
1895     * @param pw a Printer to receive the dump output.
1896     */
1897    @SuppressWarnings("unused")
1898    public void dumpLocked(PrintWriter pw) {
1899        prepareForDumpLocked();
1900
1901        long now = getHistoryBaseTime() + SystemClock.elapsedRealtime();
1902
1903        final HistoryItem rec = new HistoryItem();
1904        if (startIteratingHistoryLocked()) {
1905            pw.println("Battery History:");
1906            HistoryPrinter hprinter = new HistoryPrinter();
1907            while (getNextHistoryLocked(rec)) {
1908                hprinter.printNextItem(pw, rec, now);
1909            }
1910            finishIteratingHistoryLocked();
1911            pw.println("");
1912        }
1913
1914        if (startIteratingOldHistoryLocked()) {
1915            pw.println("Old battery History:");
1916            HistoryPrinter hprinter = new HistoryPrinter();
1917            while (getNextOldHistoryLocked(rec)) {
1918                hprinter.printNextItem(pw, rec, now);
1919            }
1920            finishIteratingOldHistoryLocked();
1921            pw.println("");
1922        }
1923
1924        SparseArray<? extends Uid> uidStats = getUidStats();
1925        final int NU = uidStats.size();
1926        boolean didPid = false;
1927        long nowRealtime = SystemClock.elapsedRealtime();
1928        StringBuilder sb = new StringBuilder(64);
1929        for (int i=0; i<NU; i++) {
1930            Uid uid = uidStats.valueAt(i);
1931            SparseArray<? extends Uid.Pid> pids = uid.getPidStats();
1932            if (pids != null) {
1933                for (int j=0; j<pids.size(); j++) {
1934                    Uid.Pid pid = pids.valueAt(j);
1935                    if (!didPid) {
1936                        pw.println("Per-PID Stats:");
1937                        didPid = true;
1938                    }
1939                    long time = pid.mWakeSum + (pid.mWakeStart != 0
1940                            ? (nowRealtime - pid.mWakeStart) : 0);
1941                    pw.print("  PID "); pw.print(pids.keyAt(j));
1942                            pw.print(" wake time: ");
1943                            TimeUtils.formatDuration(time, pw);
1944                            pw.println("");
1945                }
1946            }
1947        }
1948        if (didPid) {
1949            pw.println("");
1950        }
1951
1952        pw.println("Statistics since last charge:");
1953        pw.println("  System starts: " + getStartCount()
1954                + ", currently on battery: " + getIsOnBattery());
1955        dumpLocked(pw, "", STATS_SINCE_CHARGED, -1);
1956        pw.println("");
1957        pw.println("Statistics since last unplugged:");
1958        dumpLocked(pw, "", STATS_SINCE_UNPLUGGED, -1);
1959    }
1960
1961    @SuppressWarnings("unused")
1962    public void dumpCheckinLocked(PrintWriter pw, String[] args, List<ApplicationInfo> apps) {
1963        prepareForDumpLocked();
1964
1965        boolean isUnpluggedOnly = false;
1966
1967        for (String arg : args) {
1968            if ("-u".equals(arg)) {
1969                if (LOCAL_LOGV) Log.v("BatteryStats", "Dumping unplugged data");
1970                isUnpluggedOnly = true;
1971            }
1972        }
1973
1974        if (apps != null) {
1975            SparseArray<ArrayList<String>> uids = new SparseArray<ArrayList<String>>();
1976            for (int i=0; i<apps.size(); i++) {
1977                ApplicationInfo ai = apps.get(i);
1978                ArrayList<String> pkgs = uids.get(ai.uid);
1979                if (pkgs == null) {
1980                    pkgs = new ArrayList<String>();
1981                    uids.put(ai.uid, pkgs);
1982                }
1983                pkgs.add(ai.packageName);
1984            }
1985            SparseArray<? extends Uid> uidStats = getUidStats();
1986            final int NU = uidStats.size();
1987            String[] lineArgs = new String[2];
1988            for (int i=0; i<NU; i++) {
1989                int uid = uidStats.keyAt(i);
1990                ArrayList<String> pkgs = uids.get(uid);
1991                if (pkgs != null) {
1992                    for (int j=0; j<pkgs.size(); j++) {
1993                        lineArgs[0] = Integer.toString(uid);
1994                        lineArgs[1] = pkgs.get(j);
1995                        dumpLine(pw, 0 /* uid */, "i" /* category */, UID_DATA,
1996                                (Object[])lineArgs);
1997                    }
1998                }
1999            }
2000        }
2001        if (isUnpluggedOnly) {
2002            dumpCheckinLocked(pw, STATS_SINCE_UNPLUGGED, -1);
2003        }
2004        else {
2005            dumpCheckinLocked(pw, STATS_SINCE_CHARGED, -1);
2006            dumpCheckinLocked(pw, STATS_SINCE_UNPLUGGED, -1);
2007        }
2008    }
2009}
2010