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