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