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