BatteryStats.java revision c1b40e361c6cd3bdc53499f17ac09f45e6873059
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_LTE = 13;
663    public static final int DATA_CONNECTION_EHRPD = 14;
664    public static final int DATA_CONNECTION_OTHER = 15;
665
666    static final String[] DATA_CONNECTION_NAMES = {
667        "none", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A",
668        "1xrtt", "hsdpa", "hsupa", "hspa", "iden", "evdo_b", "lte",
669        "ehrpd", "other"
670    };
671
672    public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER+1;
673
674    /**
675     * Returns the time in microseconds that the phone has been running with
676     * the given data connection.
677     *
678     * {@hide}
679     */
680    public abstract long getPhoneDataConnectionTime(int dataType,
681            long batteryRealtime, int which);
682
683    /**
684     * Returns the number of times the phone has entered the given data
685     * connection type.
686     *
687     * {@hide}
688     */
689    public abstract int getPhoneDataConnectionCount(int dataType, int which);
690
691    public static final BitDescription[] HISTORY_STATE_DESCRIPTIONS
692            = new BitDescription[] {
693        new BitDescription(HistoryItem.STATE_BATTERY_PLUGGED_FLAG, "plugged"),
694        new BitDescription(HistoryItem.STATE_SCREEN_ON_FLAG, "screen"),
695        new BitDescription(HistoryItem.STATE_GPS_ON_FLAG, "gps"),
696        new BitDescription(HistoryItem.STATE_PHONE_IN_CALL_FLAG, "phone_in_call"),
697        new BitDescription(HistoryItem.STATE_PHONE_SCANNING_FLAG, "phone_scanning"),
698        new BitDescription(HistoryItem.STATE_WIFI_ON_FLAG, "wifi"),
699        new BitDescription(HistoryItem.STATE_WIFI_RUNNING_FLAG, "wifi_running"),
700        new BitDescription(HistoryItem.STATE_WIFI_FULL_LOCK_FLAG, "wifi_full_lock"),
701        new BitDescription(HistoryItem.STATE_WIFI_SCAN_LOCK_FLAG, "wifi_scan_lock"),
702        new BitDescription(HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG, "wifi_multicast"),
703        new BitDescription(HistoryItem.STATE_BLUETOOTH_ON_FLAG, "bluetooth"),
704        new BitDescription(HistoryItem.STATE_AUDIO_ON_FLAG, "audio"),
705        new BitDescription(HistoryItem.STATE_VIDEO_ON_FLAG, "video"),
706        new BitDescription(HistoryItem.STATE_WAKE_LOCK_FLAG, "wake_lock"),
707        new BitDescription(HistoryItem.STATE_SENSOR_ON_FLAG, "sensor"),
708        new BitDescription(HistoryItem.STATE_BRIGHTNESS_MASK,
709                HistoryItem.STATE_BRIGHTNESS_SHIFT, "brightness",
710                SCREEN_BRIGHTNESS_NAMES),
711        new BitDescription(HistoryItem.STATE_SIGNAL_STRENGTH_MASK,
712                HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT, "signal_strength",
713                SIGNAL_STRENGTH_NAMES),
714        new BitDescription(HistoryItem.STATE_PHONE_STATE_MASK,
715                HistoryItem.STATE_PHONE_STATE_SHIFT, "phone_state",
716                new String[] {"in", "out", "emergency", "off"}),
717        new BitDescription(HistoryItem.STATE_DATA_CONNECTION_MASK,
718                HistoryItem.STATE_DATA_CONNECTION_SHIFT, "data_conn",
719                DATA_CONNECTION_NAMES),
720    };
721
722    /**
723     * Returns the time in microseconds that wifi has been on while the device was
724     * running on battery.
725     *
726     * {@hide}
727     */
728    public abstract long getWifiOnTime(long batteryRealtime, int which);
729
730    /**
731     * Returns the time in microseconds that wifi has been on and the driver has
732     * been in the running state while the device was running on battery.
733     *
734     * {@hide}
735     */
736    public abstract long getGlobalWifiRunningTime(long batteryRealtime, int which);
737
738    /**
739     * Returns the time in microseconds that bluetooth has been on while the device was
740     * running on battery.
741     *
742     * {@hide}
743     */
744    public abstract long getBluetoothOnTime(long batteryRealtime, int which);
745
746    /**
747     * Return whether we are currently running on battery.
748     */
749    public abstract boolean getIsOnBattery();
750
751    /**
752     * Returns a SparseArray containing the statistics for each uid.
753     */
754    public abstract SparseArray<? extends Uid> getUidStats();
755
756    /**
757     * Returns the current battery uptime in microseconds.
758     *
759     * @param curTime the amount of elapsed realtime in microseconds.
760     */
761    public abstract long getBatteryUptime(long curTime);
762
763    /**
764     * @deprecated use getRadioDataUptime
765     */
766    public long getRadioDataUptimeMs() {
767        return getRadioDataUptime() / 1000;
768    }
769
770    /**
771     * Returns the time that the radio was on for data transfers.
772     * @return the uptime in microseconds while unplugged
773     */
774    public abstract long getRadioDataUptime();
775
776    /**
777     * Returns the current battery realtime in microseconds.
778     *
779     * @param curTime the amount of elapsed realtime in microseconds.
780     */
781    public abstract long getBatteryRealtime(long curTime);
782
783    /**
784     * Returns the battery percentage level at the last time the device was unplugged from power, or
785     * the last time it booted on battery power.
786     */
787    public abstract int getDischargeStartLevel();
788
789    /**
790     * Returns the current battery percentage level if we are in a discharge cycle, otherwise
791     * returns the level at the last plug event.
792     */
793    public abstract int getDischargeCurrentLevel();
794
795    /**
796     * Get the amount the battery has discharged since the stats were
797     * last reset after charging, as a lower-end approximation.
798     */
799    public abstract int getLowDischargeAmountSinceCharge();
800
801    /**
802     * Get the amount the battery has discharged since the stats were
803     * last reset after charging, as an upper-end approximation.
804     */
805    public abstract int getHighDischargeAmountSinceCharge();
806
807    /**
808     * Get the amount the battery has discharged while the screen was on,
809     * since the last time power was unplugged.
810     */
811    public abstract int getDischargeAmountScreenOn();
812
813    /**
814     * Get the amount the battery has discharged while the screen was on,
815     * since the last time the device was charged.
816     */
817    public abstract int getDischargeAmountScreenOnSinceCharge();
818
819    /**
820     * Get the amount the battery has discharged while the screen was off,
821     * since the last time power was unplugged.
822     */
823    public abstract int getDischargeAmountScreenOff();
824
825    /**
826     * Get the amount the battery has discharged while the screen was off,
827     * since the last time the device was charged.
828     */
829    public abstract int getDischargeAmountScreenOffSinceCharge();
830
831    /**
832     * Returns the total, last, or current battery uptime in microseconds.
833     *
834     * @param curTime the elapsed realtime in microseconds.
835     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
836     */
837    public abstract long computeBatteryUptime(long curTime, int which);
838
839    /**
840     * Returns the total, last, or current battery realtime in microseconds.
841     *
842     * @param curTime the current elapsed realtime in microseconds.
843     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
844     */
845    public abstract long computeBatteryRealtime(long curTime, int which);
846
847    /**
848     * Returns the total, last, or current uptime in microseconds.
849     *
850     * @param curTime the current elapsed realtime in microseconds.
851     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
852     */
853    public abstract long computeUptime(long curTime, int which);
854
855    /**
856     * Returns the total, last, or current realtime in microseconds.
857     * *
858     * @param curTime the current elapsed realtime in microseconds.
859     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
860     */
861    public abstract long computeRealtime(long curTime, int which);
862
863    public abstract Map<String, ? extends Timer> getKernelWakelockStats();
864
865    /** Returns the number of different speeds that the CPU can run at */
866    public abstract int getCpuSpeedSteps();
867
868    private final static void formatTimeRaw(StringBuilder out, long seconds) {
869        long days = seconds / (60 * 60 * 24);
870        if (days != 0) {
871            out.append(days);
872            out.append("d ");
873        }
874        long used = days * 60 * 60 * 24;
875
876        long hours = (seconds - used) / (60 * 60);
877        if (hours != 0 || used != 0) {
878            out.append(hours);
879            out.append("h ");
880        }
881        used += hours * 60 * 60;
882
883        long mins = (seconds-used) / 60;
884        if (mins != 0 || used != 0) {
885            out.append(mins);
886            out.append("m ");
887        }
888        used += mins * 60;
889
890        if (seconds != 0 || used != 0) {
891            out.append(seconds-used);
892            out.append("s ");
893        }
894    }
895
896    private final static void formatTime(StringBuilder sb, long time) {
897        long sec = time / 100;
898        formatTimeRaw(sb, sec);
899        sb.append((time - (sec * 100)) * 10);
900        sb.append("ms ");
901    }
902
903    private final static void formatTimeMs(StringBuilder sb, long time) {
904        long sec = time / 1000;
905        formatTimeRaw(sb, sec);
906        sb.append(time - (sec * 1000));
907        sb.append("ms ");
908    }
909
910    private final String formatRatioLocked(long num, long den) {
911        if (den == 0L) {
912            return "---%";
913        }
914        float perc = ((float)num) / ((float)den) * 100;
915        mFormatBuilder.setLength(0);
916        mFormatter.format("%.1f%%", perc);
917        return mFormatBuilder.toString();
918    }
919
920    private final String formatBytesLocked(long bytes) {
921        mFormatBuilder.setLength(0);
922
923        if (bytes < BYTES_PER_KB) {
924            return bytes + "B";
925        } else if (bytes < BYTES_PER_MB) {
926            mFormatter.format("%.2fKB", bytes / (double) BYTES_PER_KB);
927            return mFormatBuilder.toString();
928        } else if (bytes < BYTES_PER_GB){
929            mFormatter.format("%.2fMB", bytes / (double) BYTES_PER_MB);
930            return mFormatBuilder.toString();
931        } else {
932            mFormatter.format("%.2fGB", bytes / (double) BYTES_PER_GB);
933            return mFormatBuilder.toString();
934        }
935    }
936
937    /**
938     *
939     * @param sb a StringBuilder object.
940     * @param timer a Timer object contining the wakelock times.
941     * @param batteryRealtime the current on-battery time in microseconds.
942     * @param name the name of the wakelock.
943     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
944     * @param linePrefix a String to be prepended to each line of output.
945     * @return the line prefix
946     */
947    private static final String printWakeLock(StringBuilder sb, Timer timer,
948            long batteryRealtime, String name, int which, String linePrefix) {
949
950        if (timer != null) {
951            // Convert from microseconds to milliseconds with rounding
952            long totalTimeMicros = timer.getTotalTimeLocked(batteryRealtime, which);
953            long totalTimeMillis = (totalTimeMicros + 500) / 1000;
954
955            int count = timer.getCountLocked(which);
956            if (totalTimeMillis != 0) {
957                sb.append(linePrefix);
958                formatTimeMs(sb, totalTimeMillis);
959                if (name != null) sb.append(name);
960                sb.append(' ');
961                sb.append('(');
962                sb.append(count);
963                sb.append(" times)");
964                return ", ";
965            }
966        }
967        return linePrefix;
968    }
969
970    /**
971     * Checkin version of wakelock printer. Prints simple comma-separated list.
972     *
973     * @param sb a StringBuilder object.
974     * @param timer a Timer object contining the wakelock times.
975     * @param now the current time in microseconds.
976     * @param name the name of the wakelock.
977     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
978     * @param linePrefix a String to be prepended to each line of output.
979     * @return the line prefix
980     */
981    private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, long now,
982            String name, int which, String linePrefix) {
983        long totalTimeMicros = 0;
984        int count = 0;
985        if (timer != null) {
986            totalTimeMicros = timer.getTotalTimeLocked(now, which);
987            count = timer.getCountLocked(which);
988        }
989        sb.append(linePrefix);
990        sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding
991        sb.append(',');
992        sb.append(name != null ? name + "," : "");
993        sb.append(count);
994        return ",";
995    }
996
997    /**
998     * Dump a comma-separated line of values for terse checkin mode.
999     *
1000     * @param pw the PageWriter to dump log to
1001     * @param category category of data (e.g. "total", "last", "unplugged", "current" )
1002     * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" ,  "process", "network")
1003     * @param args type-dependent data arguments
1004     */
1005    private static final void dumpLine(PrintWriter pw, int uid, String category, String type,
1006           Object... args ) {
1007        pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
1008        pw.print(uid); pw.print(',');
1009        pw.print(category); pw.print(',');
1010        pw.print(type);
1011
1012        for (Object arg : args) {
1013            pw.print(',');
1014            pw.print(arg);
1015        }
1016        pw.print('\n');
1017    }
1018
1019    /**
1020     * Checkin server version of dump to produce more compact, computer-readable log.
1021     *
1022     * NOTE: all times are expressed in 'ms'.
1023     */
1024    public final void dumpCheckinLocked(PrintWriter pw, int which, int reqUid) {
1025        final long rawUptime = SystemClock.uptimeMillis() * 1000;
1026        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
1027        final long batteryUptime = getBatteryUptime(rawUptime);
1028        final long batteryRealtime = getBatteryRealtime(rawRealtime);
1029        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
1030        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
1031        final long totalRealtime = computeRealtime(rawRealtime, which);
1032        final long totalUptime = computeUptime(rawUptime, which);
1033        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1034        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1035        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1036        final long wifiRunningTime = getGlobalWifiRunningTime(batteryRealtime, which);
1037        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1038
1039        StringBuilder sb = new StringBuilder(128);
1040
1041        SparseArray<? extends Uid> uidStats = getUidStats();
1042        final int NU = uidStats.size();
1043
1044        String category = STAT_NAMES[which];
1045
1046        // Dump "battery" stat
1047        dumpLine(pw, 0 /* uid */, category, BATTERY_DATA,
1048                which == STATS_SINCE_CHARGED ? getStartCount() : "N/A",
1049                whichBatteryRealtime / 1000, whichBatteryUptime / 1000,
1050                totalRealtime / 1000, totalUptime / 1000);
1051
1052        // Calculate total network and wakelock times across all uids.
1053        long rxTotal = 0;
1054        long txTotal = 0;
1055        long fullWakeLockTimeTotal = 0;
1056        long partialWakeLockTimeTotal = 0;
1057
1058        for (int iu = 0; iu < NU; iu++) {
1059            Uid u = uidStats.valueAt(iu);
1060            rxTotal += u.getTcpBytesReceived(which);
1061            txTotal += u.getTcpBytesSent(which);
1062
1063            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1064            if (wakelocks.size() > 0) {
1065                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1066                        : wakelocks.entrySet()) {
1067                    Uid.Wakelock wl = ent.getValue();
1068
1069                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1070                    if (fullWakeTimer != null) {
1071                        fullWakeLockTimeTotal += fullWakeTimer.getTotalTimeLocked(batteryRealtime, which);
1072                    }
1073
1074                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1075                    if (partialWakeTimer != null) {
1076                        partialWakeLockTimeTotal += partialWakeTimer.getTotalTimeLocked(
1077                            batteryRealtime, which);
1078                    }
1079                }
1080            }
1081        }
1082
1083        // Dump misc stats
1084        dumpLine(pw, 0 /* uid */, category, MISC_DATA,
1085                screenOnTime / 1000, phoneOnTime / 1000, wifiOnTime / 1000,
1086                wifiRunningTime / 1000, bluetoothOnTime / 1000, rxTotal, txTotal,
1087                fullWakeLockTimeTotal, partialWakeLockTimeTotal,
1088                getInputEventCount(which));
1089
1090        // Dump screen brightness stats
1091        Object[] args = new Object[NUM_SCREEN_BRIGHTNESS_BINS];
1092        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1093            args[i] = getScreenBrightnessTime(i, batteryRealtime, which) / 1000;
1094        }
1095        dumpLine(pw, 0 /* uid */, category, SCREEN_BRIGHTNESS_DATA, args);
1096
1097        // Dump signal strength stats
1098        args = new Object[NUM_SIGNAL_STRENGTH_BINS];
1099        for (int i=0; i<NUM_SIGNAL_STRENGTH_BINS; i++) {
1100            args[i] = getPhoneSignalStrengthTime(i, batteryRealtime, which) / 1000;
1101        }
1102        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_TIME_DATA, args);
1103        dumpLine(pw, 0 /* uid */, category, SIGNAL_SCANNING_TIME_DATA,
1104                getPhoneSignalScanningTime(batteryRealtime, which) / 1000);
1105        for (int i=0; i<NUM_SIGNAL_STRENGTH_BINS; i++) {
1106            args[i] = getPhoneSignalStrengthCount(i, which);
1107        }
1108        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_COUNT_DATA, args);
1109
1110        // Dump network type stats
1111        args = new Object[NUM_DATA_CONNECTION_TYPES];
1112        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1113            args[i] = getPhoneDataConnectionTime(i, batteryRealtime, which) / 1000;
1114        }
1115        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_TIME_DATA, args);
1116        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1117            args[i] = getPhoneDataConnectionCount(i, which);
1118        }
1119        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_COUNT_DATA, args);
1120
1121        if (which == STATS_SINCE_UNPLUGGED) {
1122            dumpLine(pw, 0 /* uid */, category, BATTERY_LEVEL_DATA, getDischargeStartLevel(),
1123                    getDischargeCurrentLevel());
1124        }
1125
1126        if (which == STATS_SINCE_UNPLUGGED) {
1127            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
1128                    getDischargeStartLevel()-getDischargeCurrentLevel(),
1129                    getDischargeStartLevel()-getDischargeCurrentLevel(),
1130                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
1131        } else {
1132            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
1133                    getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(),
1134                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
1135        }
1136
1137        if (reqUid < 0) {
1138            Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1139            if (kernelWakelocks.size() > 0) {
1140                for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1141                    sb.setLength(0);
1142                    printWakeLockCheckin(sb, ent.getValue(), batteryRealtime, null, which, "");
1143
1144                    dumpLine(pw, 0 /* uid */, category, KERNEL_WAKELOCK_DATA, ent.getKey(),
1145                            sb.toString());
1146                }
1147            }
1148        }
1149
1150        for (int iu = 0; iu < NU; iu++) {
1151            final int uid = uidStats.keyAt(iu);
1152            if (reqUid >= 0 && uid != reqUid) {
1153                continue;
1154            }
1155            Uid u = uidStats.valueAt(iu);
1156            // Dump Network stats per uid, if any
1157            long rx = u.getTcpBytesReceived(which);
1158            long tx = u.getTcpBytesSent(which);
1159            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
1160            long scanWifiLockOnTime = u.getScanWifiLockTime(batteryRealtime, which);
1161            long uidWifiRunningTime = u.getWifiRunningTime(batteryRealtime, which);
1162
1163            if (rx > 0 || tx > 0) dumpLine(pw, uid, category, NETWORK_DATA, rx, tx);
1164
1165            if (fullWifiLockOnTime != 0 || scanWifiLockOnTime != 0
1166                    || uidWifiRunningTime != 0) {
1167                dumpLine(pw, uid, category, WIFI_LOCK_DATA,
1168                        fullWifiLockOnTime, scanWifiLockOnTime, uidWifiRunningTime);
1169            }
1170
1171            if (u.hasUserActivity()) {
1172                args = new Object[Uid.NUM_USER_ACTIVITY_TYPES];
1173                boolean hasData = false;
1174                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
1175                    int val = u.getUserActivityCount(i, which);
1176                    args[i] = val;
1177                    if (val != 0) hasData = true;
1178                }
1179                if (hasData) {
1180                    dumpLine(pw, 0 /* uid */, category, USER_ACTIVITY_DATA, args);
1181                }
1182            }
1183
1184            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1185            if (wakelocks.size() > 0) {
1186                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1187                        : wakelocks.entrySet()) {
1188                    Uid.Wakelock wl = ent.getValue();
1189                    String linePrefix = "";
1190                    sb.setLength(0);
1191                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL),
1192                            batteryRealtime, "f", which, linePrefix);
1193                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL),
1194                            batteryRealtime, "p", which, linePrefix);
1195                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW),
1196                            batteryRealtime, "w", which, linePrefix);
1197
1198                    // Only log if we had at lease one wakelock...
1199                    if (sb.length() > 0) {
1200                       dumpLine(pw, uid, category, WAKELOCK_DATA, ent.getKey(), sb.toString());
1201                    }
1202                }
1203            }
1204
1205            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
1206            if (sensors.size() > 0)  {
1207                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
1208                        : sensors.entrySet()) {
1209                    Uid.Sensor se = ent.getValue();
1210                    int sensorNumber = ent.getKey();
1211                    Timer timer = se.getSensorTime();
1212                    if (timer != null) {
1213                        // Convert from microseconds to milliseconds with rounding
1214                        long totalTime = (timer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
1215                        int count = timer.getCountLocked(which);
1216                        if (totalTime != 0) {
1217                            dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count);
1218                        }
1219                    }
1220                }
1221            }
1222
1223            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
1224            if (processStats.size() > 0) {
1225                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
1226                        : processStats.entrySet()) {
1227                    Uid.Proc ps = ent.getValue();
1228
1229                    long userTime = ps.getUserTime(which);
1230                    long systemTime = ps.getSystemTime(which);
1231                    int starts = ps.getStarts(which);
1232
1233                    if (userTime != 0 || systemTime != 0 || starts != 0) {
1234                        dumpLine(pw, uid, category, PROCESS_DATA,
1235                                ent.getKey(), // proc
1236                                userTime * 10, // cpu time in ms
1237                                systemTime * 10, // user time in ms
1238                                starts); // process starts
1239                    }
1240                }
1241            }
1242
1243            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
1244            if (packageStats.size() > 0) {
1245                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
1246                        : packageStats.entrySet()) {
1247
1248                    Uid.Pkg ps = ent.getValue();
1249                    int wakeups = ps.getWakeups(which);
1250                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
1251                    for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
1252                            : serviceStats.entrySet()) {
1253                        BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
1254                        long startTime = ss.getStartTime(batteryUptime, which);
1255                        int starts = ss.getStarts(which);
1256                        int launches = ss.getLaunches(which);
1257                        if (startTime != 0 || starts != 0 || launches != 0) {
1258                            dumpLine(pw, uid, category, APK_DATA,
1259                                    wakeups, // wakeup alarms
1260                                    ent.getKey(), // Apk
1261                                    sent.getKey(), // service
1262                                    startTime / 1000, // time spent started, in ms
1263                                    starts,
1264                                    launches);
1265                        }
1266                    }
1267                }
1268            }
1269        }
1270    }
1271
1272    @SuppressWarnings("unused")
1273    public final void dumpLocked(PrintWriter pw, String prefix, int which, int reqUid) {
1274        final long rawUptime = SystemClock.uptimeMillis() * 1000;
1275        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
1276        final long batteryUptime = getBatteryUptime(rawUptime);
1277        final long batteryRealtime = getBatteryRealtime(rawRealtime);
1278
1279        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
1280        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
1281        final long totalRealtime = computeRealtime(rawRealtime, which);
1282        final long totalUptime = computeUptime(rawUptime, which);
1283
1284        StringBuilder sb = new StringBuilder(128);
1285
1286        SparseArray<? extends Uid> uidStats = getUidStats();
1287        final int NU = uidStats.size();
1288
1289        sb.setLength(0);
1290        sb.append(prefix);
1291                sb.append("  Time on battery: ");
1292                formatTimeMs(sb, whichBatteryRealtime / 1000); sb.append("(");
1293                sb.append(formatRatioLocked(whichBatteryRealtime, totalRealtime));
1294                sb.append(") realtime, ");
1295                formatTimeMs(sb, whichBatteryUptime / 1000);
1296                sb.append("("); sb.append(formatRatioLocked(whichBatteryUptime, totalRealtime));
1297                sb.append(") uptime");
1298        pw.println(sb.toString());
1299        sb.setLength(0);
1300        sb.append(prefix);
1301                sb.append("  Total run time: ");
1302                formatTimeMs(sb, totalRealtime / 1000);
1303                sb.append("realtime, ");
1304                formatTimeMs(sb, totalUptime / 1000);
1305                sb.append("uptime, ");
1306        pw.println(sb.toString());
1307
1308        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1309        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1310        final long wifiRunningTime = getGlobalWifiRunningTime(batteryRealtime, which);
1311        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1312        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1313        sb.setLength(0);
1314        sb.append(prefix);
1315                sb.append("  Screen on: "); formatTimeMs(sb, screenOnTime / 1000);
1316                sb.append("("); sb.append(formatRatioLocked(screenOnTime, whichBatteryRealtime));
1317                sb.append("), Input events: "); sb.append(getInputEventCount(which));
1318                sb.append(", Active phone call: "); formatTimeMs(sb, phoneOnTime / 1000);
1319                sb.append("("); sb.append(formatRatioLocked(phoneOnTime, whichBatteryRealtime));
1320                sb.append(")");
1321        pw.println(sb.toString());
1322        sb.setLength(0);
1323        sb.append(prefix);
1324        sb.append("  Screen brightnesses: ");
1325        boolean didOne = false;
1326        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1327            final long time = getScreenBrightnessTime(i, batteryRealtime, which);
1328            if (time == 0) {
1329                continue;
1330            }
1331            if (didOne) sb.append(", ");
1332            didOne = true;
1333            sb.append(SCREEN_BRIGHTNESS_NAMES[i]);
1334            sb.append(" ");
1335            formatTimeMs(sb, time/1000);
1336            sb.append("(");
1337            sb.append(formatRatioLocked(time, screenOnTime));
1338            sb.append(")");
1339        }
1340        if (!didOne) sb.append("No activity");
1341        pw.println(sb.toString());
1342
1343        // Calculate total network and wakelock times across all uids.
1344        long rxTotal = 0;
1345        long txTotal = 0;
1346        long fullWakeLockTimeTotalMicros = 0;
1347        long partialWakeLockTimeTotalMicros = 0;
1348
1349        if (reqUid < 0) {
1350            Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1351            if (kernelWakelocks.size() > 0) {
1352                for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1353
1354                    String linePrefix = ": ";
1355                    sb.setLength(0);
1356                    sb.append(prefix);
1357                    sb.append("  Kernel Wake lock ");
1358                    sb.append(ent.getKey());
1359                    linePrefix = printWakeLock(sb, ent.getValue(), batteryRealtime, null, which,
1360                            linePrefix);
1361                    if (!linePrefix.equals(": ")) {
1362                        sb.append(" realtime");
1363                        // Only print out wake locks that were held
1364                        pw.println(sb.toString());
1365                    }
1366                }
1367            }
1368        }
1369
1370        for (int iu = 0; iu < NU; iu++) {
1371            Uid u = uidStats.valueAt(iu);
1372            rxTotal += u.getTcpBytesReceived(which);
1373            txTotal += u.getTcpBytesSent(which);
1374
1375            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1376            if (wakelocks.size() > 0) {
1377                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1378                        : wakelocks.entrySet()) {
1379                    Uid.Wakelock wl = ent.getValue();
1380
1381                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1382                    if (fullWakeTimer != null) {
1383                        fullWakeLockTimeTotalMicros += fullWakeTimer.getTotalTimeLocked(
1384                                batteryRealtime, which);
1385                    }
1386
1387                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1388                    if (partialWakeTimer != null) {
1389                        partialWakeLockTimeTotalMicros += partialWakeTimer.getTotalTimeLocked(
1390                                batteryRealtime, which);
1391                    }
1392                }
1393            }
1394        }
1395
1396        pw.print(prefix);
1397                pw.print("  Total received: "); pw.print(formatBytesLocked(rxTotal));
1398                pw.print(", Total sent: "); pw.println(formatBytesLocked(txTotal));
1399        sb.setLength(0);
1400        sb.append(prefix);
1401                sb.append("  Total full wakelock time: "); formatTimeMs(sb,
1402                        (fullWakeLockTimeTotalMicros + 500) / 1000);
1403                sb.append(", Total partial waklock time: "); formatTimeMs(sb,
1404                        (partialWakeLockTimeTotalMicros + 500) / 1000);
1405        pw.println(sb.toString());
1406
1407        sb.setLength(0);
1408        sb.append(prefix);
1409        sb.append("  Signal levels: ");
1410        didOne = false;
1411        for (int i=0; i<NUM_SIGNAL_STRENGTH_BINS; i++) {
1412            final long time = getPhoneSignalStrengthTime(i, batteryRealtime, which);
1413            if (time == 0) {
1414                continue;
1415            }
1416            if (didOne) sb.append(", ");
1417            didOne = true;
1418            sb.append(SIGNAL_STRENGTH_NAMES[i]);
1419            sb.append(" ");
1420            formatTimeMs(sb, time/1000);
1421            sb.append("(");
1422            sb.append(formatRatioLocked(time, whichBatteryRealtime));
1423            sb.append(") ");
1424            sb.append(getPhoneSignalStrengthCount(i, which));
1425            sb.append("x");
1426        }
1427        if (!didOne) sb.append("No activity");
1428        pw.println(sb.toString());
1429
1430        sb.setLength(0);
1431        sb.append(prefix);
1432        sb.append("  Signal scanning time: ");
1433        formatTimeMs(sb, getPhoneSignalScanningTime(batteryRealtime, which) / 1000);
1434        pw.println(sb.toString());
1435
1436        sb.setLength(0);
1437        sb.append(prefix);
1438        sb.append("  Radio types: ");
1439        didOne = false;
1440        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1441            final long time = getPhoneDataConnectionTime(i, batteryRealtime, which);
1442            if (time == 0) {
1443                continue;
1444            }
1445            if (didOne) sb.append(", ");
1446            didOne = true;
1447            sb.append(DATA_CONNECTION_NAMES[i]);
1448            sb.append(" ");
1449            formatTimeMs(sb, time/1000);
1450            sb.append("(");
1451            sb.append(formatRatioLocked(time, whichBatteryRealtime));
1452            sb.append(") ");
1453            sb.append(getPhoneDataConnectionCount(i, which));
1454            sb.append("x");
1455        }
1456        if (!didOne) sb.append("No activity");
1457        pw.println(sb.toString());
1458
1459        sb.setLength(0);
1460        sb.append(prefix);
1461        sb.append("  Radio data uptime when unplugged: ");
1462        sb.append(getRadioDataUptime() / 1000);
1463        sb.append(" ms");
1464        pw.println(sb.toString());
1465
1466        sb.setLength(0);
1467        sb.append(prefix);
1468                sb.append("  Wifi on: "); formatTimeMs(sb, wifiOnTime / 1000);
1469                sb.append("("); sb.append(formatRatioLocked(wifiOnTime, whichBatteryRealtime));
1470                sb.append("), Wifi running: "); formatTimeMs(sb, wifiRunningTime / 1000);
1471                sb.append("("); sb.append(formatRatioLocked(wifiRunningTime, whichBatteryRealtime));
1472                sb.append("), Bluetooth on: "); formatTimeMs(sb, bluetoothOnTime / 1000);
1473                sb.append("("); sb.append(formatRatioLocked(bluetoothOnTime, whichBatteryRealtime));
1474                sb.append(")");
1475        pw.println(sb.toString());
1476
1477        pw.println(" ");
1478
1479        if (which == STATS_SINCE_UNPLUGGED) {
1480            if (getIsOnBattery()) {
1481                pw.print(prefix); pw.println("  Device is currently unplugged");
1482                pw.print(prefix); pw.print("    Discharge cycle start level: ");
1483                        pw.println(getDischargeStartLevel());
1484                pw.print(prefix); pw.print("    Discharge cycle current level: ");
1485                        pw.println(getDischargeCurrentLevel());
1486            } else {
1487                pw.print(prefix); pw.println("  Device is currently plugged into power");
1488                pw.print(prefix); pw.print("    Last discharge cycle start level: ");
1489                        pw.println(getDischargeStartLevel());
1490                pw.print(prefix); pw.print("    Last discharge cycle end level: ");
1491                        pw.println(getDischargeCurrentLevel());
1492            }
1493            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
1494                    pw.println(getDischargeAmountScreenOn());
1495            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
1496                    pw.println(getDischargeAmountScreenOff());
1497            pw.println(" ");
1498        } else {
1499            pw.print(prefix); pw.println("  Device battery use since last full charge");
1500            pw.print(prefix); pw.print("    Amount discharged (lower bound): ");
1501                    pw.println(getLowDischargeAmountSinceCharge());
1502            pw.print(prefix); pw.print("    Amount discharged (upper bound): ");
1503                    pw.println(getHighDischargeAmountSinceCharge());
1504            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
1505                    pw.println(getDischargeAmountScreenOnSinceCharge());
1506            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
1507                    pw.println(getDischargeAmountScreenOffSinceCharge());
1508            pw.println(" ");
1509        }
1510
1511
1512        for (int iu=0; iu<NU; iu++) {
1513            final int uid = uidStats.keyAt(iu);
1514            if (reqUid >= 0 && uid != reqUid && uid != Process.SYSTEM_UID) {
1515                continue;
1516            }
1517
1518            Uid u = uidStats.valueAt(iu);
1519
1520            pw.println(prefix + "  #" + uid + ":");
1521            boolean uidActivity = false;
1522
1523            long tcpReceived = u.getTcpBytesReceived(which);
1524            long tcpSent = u.getTcpBytesSent(which);
1525            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
1526            long scanWifiLockOnTime = u.getScanWifiLockTime(batteryRealtime, which);
1527            long uidWifiRunningTime = u.getWifiRunningTime(batteryRealtime, which);
1528
1529            if (tcpReceived != 0 || tcpSent != 0) {
1530                pw.print(prefix); pw.print("    Network: ");
1531                        pw.print(formatBytesLocked(tcpReceived)); pw.print(" received, ");
1532                        pw.print(formatBytesLocked(tcpSent)); pw.println(" sent");
1533            }
1534
1535            if (u.hasUserActivity()) {
1536                boolean hasData = false;
1537                for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1538                    int val = u.getUserActivityCount(i, which);
1539                    if (val != 0) {
1540                        if (!hasData) {
1541                            sb.setLength(0);
1542                            sb.append("    User activity: ");
1543                            hasData = true;
1544                        } else {
1545                            sb.append(", ");
1546                        }
1547                        sb.append(val);
1548                        sb.append(" ");
1549                        sb.append(Uid.USER_ACTIVITY_TYPES[i]);
1550                    }
1551                }
1552                if (hasData) {
1553                    pw.println(sb.toString());
1554                }
1555            }
1556
1557            if (fullWifiLockOnTime != 0 || scanWifiLockOnTime != 0
1558                    || uidWifiRunningTime != 0) {
1559                sb.setLength(0);
1560                sb.append(prefix); sb.append("    Wifi Running: ");
1561                        formatTimeMs(sb, uidWifiRunningTime / 1000);
1562                        sb.append("("); sb.append(formatRatioLocked(uidWifiRunningTime,
1563                                whichBatteryRealtime)); sb.append(")\n");
1564                sb.append(prefix); sb.append("    Full Wifi Lock: ");
1565                        formatTimeMs(sb, fullWifiLockOnTime / 1000);
1566                        sb.append("("); sb.append(formatRatioLocked(fullWifiLockOnTime,
1567                                whichBatteryRealtime)); sb.append(")\n");
1568                sb.append(prefix); sb.append("    Scan Wifi Lock: ");
1569                        formatTimeMs(sb, scanWifiLockOnTime / 1000);
1570                        sb.append("("); sb.append(formatRatioLocked(scanWifiLockOnTime,
1571                                whichBatteryRealtime)); sb.append(")");
1572                pw.println(sb.toString());
1573            }
1574
1575            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1576            if (wakelocks.size() > 0) {
1577                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1578                    : wakelocks.entrySet()) {
1579                    Uid.Wakelock wl = ent.getValue();
1580                    String linePrefix = ": ";
1581                    sb.setLength(0);
1582                    sb.append(prefix);
1583                    sb.append("    Wake lock ");
1584                    sb.append(ent.getKey());
1585                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), batteryRealtime,
1586                            "full", which, linePrefix);
1587                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), batteryRealtime,
1588                            "partial", which, linePrefix);
1589                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), batteryRealtime,
1590                            "window", which, linePrefix);
1591                    if (!linePrefix.equals(": ")) {
1592                        sb.append(" realtime");
1593                        // Only print out wake locks that were held
1594                        pw.println(sb.toString());
1595                        uidActivity = true;
1596                    }
1597                }
1598            }
1599
1600            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
1601            if (sensors.size() > 0) {
1602                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
1603                    : sensors.entrySet()) {
1604                    Uid.Sensor se = ent.getValue();
1605                    int sensorNumber = ent.getKey();
1606                    sb.setLength(0);
1607                    sb.append(prefix);
1608                    sb.append("    Sensor ");
1609                    int handle = se.getHandle();
1610                    if (handle == Uid.Sensor.GPS) {
1611                        sb.append("GPS");
1612                    } else {
1613                        sb.append(handle);
1614                    }
1615                    sb.append(": ");
1616
1617                    Timer timer = se.getSensorTime();
1618                    if (timer != null) {
1619                        // Convert from microseconds to milliseconds with rounding
1620                        long totalTime = (timer.getTotalTimeLocked(
1621                                batteryRealtime, which) + 500) / 1000;
1622                        int count = timer.getCountLocked(which);
1623                        //timer.logState();
1624                        if (totalTime != 0) {
1625                            formatTimeMs(sb, totalTime);
1626                            sb.append("realtime (");
1627                            sb.append(count);
1628                            sb.append(" times)");
1629                        } else {
1630                            sb.append("(not used)");
1631                        }
1632                    } else {
1633                        sb.append("(not used)");
1634                    }
1635
1636                    pw.println(sb.toString());
1637                    uidActivity = true;
1638                }
1639            }
1640
1641            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
1642            if (processStats.size() > 0) {
1643                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
1644                    : processStats.entrySet()) {
1645                    Uid.Proc ps = ent.getValue();
1646                    long userTime;
1647                    long systemTime;
1648                    int starts;
1649                    int numExcessive;
1650
1651                    userTime = ps.getUserTime(which);
1652                    systemTime = ps.getSystemTime(which);
1653                    starts = ps.getStarts(which);
1654                    numExcessive = which == STATS_SINCE_CHARGED
1655                            ? ps.countExcessivePowers() : 0;
1656
1657                    if (userTime != 0 || systemTime != 0 || starts != 0
1658                            || numExcessive != 0) {
1659                        sb.setLength(0);
1660                        sb.append(prefix); sb.append("    Proc ");
1661                                sb.append(ent.getKey()); sb.append(":\n");
1662                        sb.append(prefix); sb.append("      CPU: ");
1663                                formatTime(sb, userTime); sb.append("usr + ");
1664                                formatTime(sb, systemTime); sb.append("krn");
1665                        if (starts != 0) {
1666                            sb.append("\n"); sb.append(prefix); sb.append("      ");
1667                                    sb.append(starts); sb.append(" proc starts");
1668                        }
1669                        pw.println(sb.toString());
1670                        for (int e=0; e<numExcessive; e++) {
1671                            Uid.Proc.ExcessivePower ew = ps.getExcessivePower(e);
1672                            if (ew != null) {
1673                                pw.print(prefix); pw.print("      * Killed for ");
1674                                        if (ew.type == Uid.Proc.ExcessivePower.TYPE_WAKE) {
1675                                            pw.print("wake lock");
1676                                        } else if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) {
1677                                            pw.print("cpu");
1678                                        } else {
1679                                            pw.print("unknown");
1680                                        }
1681                                        pw.print(" use: ");
1682                                        TimeUtils.formatDuration(ew.usedTime, pw);
1683                                        pw.print(" over ");
1684                                        TimeUtils.formatDuration(ew.overTime, pw);
1685                                        pw.print(" (");
1686                                        pw.print((ew.usedTime*100)/ew.overTime);
1687                                        pw.println("%)");
1688                            }
1689                        }
1690                        uidActivity = true;
1691                    }
1692                }
1693            }
1694
1695            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
1696            if (packageStats.size() > 0) {
1697                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
1698                    : packageStats.entrySet()) {
1699                    pw.print(prefix); pw.print("    Apk "); pw.print(ent.getKey()); pw.println(":");
1700                    boolean apkActivity = false;
1701                    Uid.Pkg ps = ent.getValue();
1702                    int wakeups = ps.getWakeups(which);
1703                    if (wakeups != 0) {
1704                        pw.print(prefix); pw.print("      ");
1705                                pw.print(wakeups); pw.println(" wakeup alarms");
1706                        apkActivity = true;
1707                    }
1708                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
1709                    if (serviceStats.size() > 0) {
1710                        for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
1711                                : serviceStats.entrySet()) {
1712                            BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
1713                            long startTime = ss.getStartTime(batteryUptime, which);
1714                            int starts = ss.getStarts(which);
1715                            int launches = ss.getLaunches(which);
1716                            if (startTime != 0 || starts != 0 || launches != 0) {
1717                                sb.setLength(0);
1718                                sb.append(prefix); sb.append("      Service ");
1719                                        sb.append(sent.getKey()); sb.append(":\n");
1720                                sb.append(prefix); sb.append("        Created for: ");
1721                                        formatTimeMs(sb, startTime / 1000);
1722                                        sb.append(" uptime\n");
1723                                sb.append(prefix); sb.append("        Starts: ");
1724                                        sb.append(starts);
1725                                        sb.append(", launches: "); sb.append(launches);
1726                                pw.println(sb.toString());
1727                                apkActivity = true;
1728                            }
1729                        }
1730                    }
1731                    if (!apkActivity) {
1732                        pw.print(prefix); pw.println("      (nothing executed)");
1733                    }
1734                    uidActivity = true;
1735                }
1736            }
1737            if (!uidActivity) {
1738                pw.print(prefix); pw.println("    (nothing executed)");
1739            }
1740        }
1741    }
1742
1743    void printBitDescriptions(PrintWriter pw, int oldval, int newval, BitDescription[] descriptions) {
1744        int diff = oldval ^ newval;
1745        if (diff == 0) return;
1746        for (int i=0; i<descriptions.length; i++) {
1747            BitDescription bd = descriptions[i];
1748            if ((diff&bd.mask) != 0) {
1749                if (bd.shift < 0) {
1750                    pw.print((newval&bd.mask) != 0 ? " +" : " -");
1751                    pw.print(bd.name);
1752                } else {
1753                    pw.print(" ");
1754                    pw.print(bd.name);
1755                    pw.print("=");
1756                    int val = (newval&bd.mask)>>bd.shift;
1757                    if (bd.values != null && val >= 0 && val < bd.values.length) {
1758                        pw.print(bd.values[val]);
1759                    } else {
1760                        pw.print(val);
1761                    }
1762                }
1763            }
1764        }
1765    }
1766
1767    /**
1768     * Dumps a human-readable summary of the battery statistics to the given PrintWriter.
1769     *
1770     * @param pw a Printer to receive the dump output.
1771     */
1772    @SuppressWarnings("unused")
1773    public void dumpLocked(PrintWriter pw) {
1774        final HistoryItem rec = new HistoryItem();
1775        if (startIteratingHistoryLocked()) {
1776            pw.println("Battery History:");
1777            long now = getHistoryBaseTime() + SystemClock.elapsedRealtime();
1778            int oldState = 0;
1779            int oldStatus = -1;
1780            int oldHealth = -1;
1781            int oldPlug = -1;
1782            int oldTemp = -1;
1783            int oldVolt = -1;
1784            while (getNextHistoryLocked(rec)) {
1785                pw.print("  ");
1786                TimeUtils.formatDuration(rec.time-now, pw, TimeUtils.HUNDRED_DAY_FIELD_LEN);
1787                pw.print(" ");
1788                if (rec.cmd == HistoryItem.CMD_START) {
1789                    pw.println(" START");
1790                } else if (rec.cmd == HistoryItem.CMD_OVERFLOW) {
1791                    pw.println(" *OVERFLOW*");
1792                } else {
1793                    if (rec.batteryLevel < 10) pw.print("00");
1794                    else if (rec.batteryLevel < 100) pw.print("0");
1795                    pw.print(rec.batteryLevel);
1796                    pw.print(" ");
1797                    if (rec.states < 0x10) pw.print("0000000");
1798                    else if (rec.states < 0x100) pw.print("000000");
1799                    else if (rec.states < 0x1000) pw.print("00000");
1800                    else if (rec.states < 0x10000) pw.print("0000");
1801                    else if (rec.states < 0x100000) pw.print("000");
1802                    else if (rec.states < 0x1000000) pw.print("00");
1803                    else if (rec.states < 0x10000000) pw.print("0");
1804                    pw.print(Integer.toHexString(rec.states));
1805                    if (oldStatus != rec.batteryStatus) {
1806                        oldStatus = rec.batteryStatus;
1807                        pw.print(" status=");
1808                        switch (oldStatus) {
1809                            case BatteryManager.BATTERY_STATUS_UNKNOWN:
1810                                pw.print("unknown");
1811                                break;
1812                            case BatteryManager.BATTERY_STATUS_CHARGING:
1813                                pw.print("charging");
1814                                break;
1815                            case BatteryManager.BATTERY_STATUS_DISCHARGING:
1816                                pw.print("discharging");
1817                                break;
1818                            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
1819                                pw.print("not-charging");
1820                                break;
1821                            case BatteryManager.BATTERY_STATUS_FULL:
1822                                pw.print("full");
1823                                break;
1824                            default:
1825                                pw.print(oldStatus);
1826                                break;
1827                        }
1828                    }
1829                    if (oldHealth != rec.batteryHealth) {
1830                        oldHealth = rec.batteryHealth;
1831                        pw.print(" health=");
1832                        switch (oldHealth) {
1833                            case BatteryManager.BATTERY_HEALTH_UNKNOWN:
1834                                pw.print("unknown");
1835                                break;
1836                            case BatteryManager.BATTERY_HEALTH_GOOD:
1837                                pw.print("good");
1838                                break;
1839                            case BatteryManager.BATTERY_HEALTH_OVERHEAT:
1840                                pw.print("overheat");
1841                                break;
1842                            case BatteryManager.BATTERY_HEALTH_DEAD:
1843                                pw.print("dead");
1844                                break;
1845                            case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
1846                                pw.print("over-voltage");
1847                                break;
1848                            case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
1849                                pw.print("failure");
1850                                break;
1851                            default:
1852                                pw.print(oldHealth);
1853                                break;
1854                        }
1855                    }
1856                    if (oldPlug != rec.batteryPlugType) {
1857                        oldPlug = rec.batteryPlugType;
1858                        pw.print(" plug=");
1859                        switch (oldPlug) {
1860                            case 0:
1861                                pw.print("none");
1862                                break;
1863                            case BatteryManager.BATTERY_PLUGGED_AC:
1864                                pw.print("ac");
1865                                break;
1866                            case BatteryManager.BATTERY_PLUGGED_USB:
1867                                pw.print("usb");
1868                                break;
1869                            default:
1870                                pw.print(oldPlug);
1871                                break;
1872                        }
1873                    }
1874                    if (oldTemp != rec.batteryTemperature) {
1875                        oldTemp = rec.batteryTemperature;
1876                        pw.print(" temp=");
1877                        pw.print(oldTemp);
1878                    }
1879                    if (oldVolt != rec.batteryVoltage) {
1880                        oldVolt = rec.batteryVoltage;
1881                        pw.print(" volt=");
1882                        pw.print(oldVolt);
1883                    }
1884                    printBitDescriptions(pw, oldState, rec.states,
1885                            HISTORY_STATE_DESCRIPTIONS);
1886                    pw.println();
1887                }
1888                oldState = rec.states;
1889            }
1890            pw.println("");
1891        }
1892
1893        SparseArray<? extends Uid> uidStats = getUidStats();
1894        final int NU = uidStats.size();
1895        boolean didPid = false;
1896        long nowRealtime = SystemClock.elapsedRealtime();
1897        StringBuilder sb = new StringBuilder(64);
1898        for (int i=0; i<NU; i++) {
1899            Uid uid = uidStats.valueAt(i);
1900            SparseArray<? extends Uid.Pid> pids = uid.getPidStats();
1901            if (pids != null) {
1902                for (int j=0; j<pids.size(); j++) {
1903                    Uid.Pid pid = pids.valueAt(j);
1904                    if (!didPid) {
1905                        pw.println("Per-PID Stats:");
1906                        didPid = true;
1907                    }
1908                    long time = pid.mWakeSum + (pid.mWakeStart != 0
1909                            ? (nowRealtime - pid.mWakeStart) : 0);
1910                    pw.print("  PID "); pw.print(pids.keyAt(j));
1911                            pw.print(" wake time: ");
1912                            TimeUtils.formatDuration(time, pw);
1913                            pw.println("");
1914                }
1915            }
1916        }
1917        if (didPid) {
1918            pw.println("");
1919        }
1920
1921        pw.println("Statistics since last charge:");
1922        pw.println("  System starts: " + getStartCount()
1923                + ", currently on battery: " + getIsOnBattery());
1924        dumpLocked(pw, "", STATS_SINCE_CHARGED, -1);
1925        pw.println("");
1926        pw.println("Statistics since last unplugged:");
1927        dumpLocked(pw, "", STATS_SINCE_UNPLUGGED, -1);
1928    }
1929
1930    @SuppressWarnings("unused")
1931    public void dumpCheckinLocked(PrintWriter pw, String[] args, List<ApplicationInfo> apps) {
1932        boolean isUnpluggedOnly = false;
1933
1934        for (String arg : args) {
1935            if ("-u".equals(arg)) {
1936                if (LOCAL_LOGV) Log.v("BatteryStats", "Dumping unplugged data");
1937                isUnpluggedOnly = true;
1938            }
1939        }
1940
1941        if (apps != null) {
1942            SparseArray<ArrayList<String>> uids = new SparseArray<ArrayList<String>>();
1943            for (int i=0; i<apps.size(); i++) {
1944                ApplicationInfo ai = apps.get(i);
1945                ArrayList<String> pkgs = uids.get(ai.uid);
1946                if (pkgs == null) {
1947                    pkgs = new ArrayList<String>();
1948                    uids.put(ai.uid, pkgs);
1949                }
1950                pkgs.add(ai.packageName);
1951            }
1952            SparseArray<? extends Uid> uidStats = getUidStats();
1953            final int NU = uidStats.size();
1954            String[] lineArgs = new String[2];
1955            for (int i=0; i<NU; i++) {
1956                int uid = uidStats.keyAt(i);
1957                ArrayList<String> pkgs = uids.get(uid);
1958                if (pkgs != null) {
1959                    for (int j=0; j<pkgs.size(); j++) {
1960                        lineArgs[0] = Integer.toString(uid);
1961                        lineArgs[1] = pkgs.get(j);
1962                        dumpLine(pw, 0 /* uid */, "i" /* category */, UID_DATA,
1963                                (Object[])lineArgs);
1964                    }
1965                }
1966            }
1967        }
1968        if (isUnpluggedOnly) {
1969            dumpCheckinLocked(pw, STATS_SINCE_UNPLUGGED, -1);
1970        }
1971        else {
1972            dumpCheckinLocked(pw, STATS_SINCE_CHARGED, -1);
1973            dumpCheckinLocked(pw, STATS_SINCE_UNPLUGGED, -1);
1974        }
1975    }
1976}
1977