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