BatteryStats.java revision 77b987f1a1bb6028a871de01065b94c4cfff0b5c
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.Collections;
22import java.util.Comparator;
23import java.util.Formatter;
24import java.util.List;
25import java.util.Map;
26
27import android.content.Context;
28import android.content.pm.ApplicationInfo;
29import android.telephony.SignalStrength;
30import android.text.format.DateFormat;
31import android.util.Printer;
32import android.util.SparseArray;
33import android.util.TimeUtils;
34import com.android.internal.os.BatterySipper;
35import com.android.internal.os.BatteryStatsHelper;
36
37/**
38 * A class providing access to battery usage statistics, including information on
39 * wakelocks, processes, packages, and services.  All times are represented in microseconds
40 * except where indicated otherwise.
41 * @hide
42 */
43public abstract class BatteryStats implements Parcelable {
44
45    private static final boolean LOCAL_LOGV = false;
46
47    /** @hide */
48    public static final String SERVICE_NAME = "batterystats";
49
50    /**
51     * A constant indicating a partial wake lock timer.
52     */
53    public static final int WAKE_TYPE_PARTIAL = 0;
54
55    /**
56     * A constant indicating a full wake lock timer.
57     */
58    public static final int WAKE_TYPE_FULL = 1;
59
60    /**
61     * A constant indicating a window wake lock timer.
62     */
63    public static final int WAKE_TYPE_WINDOW = 2;
64
65    /**
66     * A constant indicating a sensor timer.
67     */
68    public static final int SENSOR = 3;
69
70    /**
71     * A constant indicating a a wifi running timer
72     */
73    public static final int WIFI_RUNNING = 4;
74
75    /**
76     * A constant indicating a full wifi lock timer
77     */
78    public static final int FULL_WIFI_LOCK = 5;
79
80    /**
81     * A constant indicating a wifi scan
82     */
83    public static final int WIFI_SCAN = 6;
84
85     /**
86      * A constant indicating a wifi multicast timer
87      */
88     public static final int WIFI_MULTICAST_ENABLED = 7;
89
90    /**
91     * A constant indicating an audio turn on timer
92     */
93    public static final int AUDIO_TURNED_ON = 7;
94
95    /**
96     * A constant indicating a video turn on timer
97     */
98    public static final int VIDEO_TURNED_ON = 8;
99
100    /**
101     * A constant indicating a vibrator on timer
102     */
103    public static final int VIBRATOR_ON = 9;
104
105    /**
106     * A constant indicating a foreground activity timer
107     */
108    public static final int FOREGROUND_ACTIVITY = 10;
109
110    /**
111     * A constant indicating a wifi batched scan is active
112     */
113    public static final int WIFI_BATCHED_SCAN = 11;
114
115    /**
116     * Include all of the data in the stats, including previously saved data.
117     */
118    public static final int STATS_SINCE_CHARGED = 0;
119
120    /**
121     * Include only the last run in the stats.
122     */
123    public static final int STATS_LAST = 1;
124
125    /**
126     * Include only the current run in the stats.
127     */
128    public static final int STATS_CURRENT = 2;
129
130    /**
131     * Include only the run since the last time the device was unplugged in the stats.
132     */
133    public static final int STATS_SINCE_UNPLUGGED = 3;
134
135    // NOTE: Update this list if you add/change any stats above.
136    // These characters are supposed to represent "total", "last", "current",
137    // and "unplugged". They were shortened for efficiency sake.
138    private static final String[] STAT_NAMES = { "t", "l", "c", "u" };
139
140    /**
141     * Bump the version on this if the checkin format changes.
142     */
143    private static final int BATTERY_STATS_CHECKIN_VERSION = 7;
144
145    private static final long BYTES_PER_KB = 1024;
146    private static final long BYTES_PER_MB = 1048576; // 1024^2
147    private static final long BYTES_PER_GB = 1073741824; //1024^3
148
149
150    private static final String UID_DATA = "uid";
151    private static final String APK_DATA = "apk";
152    private static final String PROCESS_DATA = "pr";
153    private static final String SENSOR_DATA = "sr";
154    private static final String VIBRATOR_DATA = "vib";
155    private static final String FOREGROUND_DATA = "fg";
156    private static final String WAKELOCK_DATA = "wl";
157    private static final String KERNEL_WAKELOCK_DATA = "kwl";
158    private static final String NETWORK_DATA = "nt";
159    private static final String USER_ACTIVITY_DATA = "ua";
160    private static final String BATTERY_DATA = "bt";
161    private static final String BATTERY_DISCHARGE_DATA = "dc";
162    private static final String BATTERY_LEVEL_DATA = "lv";
163    private static final String WIFI_DATA = "wfl";
164    private static final String MISC_DATA = "m";
165    private static final String GLOBAL_NETWORK_DATA = "gn";
166    private static final String HISTORY_STRING_POOL = "hsp";
167    private static final String HISTORY_DATA = "h";
168    private static final String SCREEN_BRIGHTNESS_DATA = "br";
169    private static final String SIGNAL_STRENGTH_TIME_DATA = "sgt";
170    private static final String SIGNAL_SCANNING_TIME_DATA = "sst";
171    private static final String SIGNAL_STRENGTH_COUNT_DATA = "sgc";
172    private static final String DATA_CONNECTION_TIME_DATA = "dct";
173    private static final String DATA_CONNECTION_COUNT_DATA = "dcc";
174    private static final String WIFI_STATE_TIME_DATA = "wst";
175    private static final String WIFI_STATE_COUNT_DATA = "wsc";
176    private static final String BLUETOOTH_STATE_TIME_DATA = "bst";
177    private static final String BLUETOOTH_STATE_COUNT_DATA = "bsc";
178    private static final String POWER_USE_SUMMARY_DATA = "pws";
179    private static final String POWER_USE_ITEM_DATA = "pwi";
180
181    private final StringBuilder mFormatBuilder = new StringBuilder(32);
182    private final Formatter mFormatter = new Formatter(mFormatBuilder);
183
184    /**
185     * State for keeping track of counting information.
186     */
187    public static abstract class Counter {
188
189        /**
190         * Returns the count associated with this Counter for the
191         * selected type of statistics.
192         *
193         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
194         */
195        public abstract int getCountLocked(int which);
196
197        /**
198         * Temporary for debugging.
199         */
200        public abstract void logState(Printer pw, String prefix);
201    }
202
203    /**
204     * State for keeping track of timing information.
205     */
206    public static abstract class Timer {
207
208        /**
209         * Returns the count associated with this Timer for the
210         * selected type of statistics.
211         *
212         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
213         */
214        public abstract int getCountLocked(int which);
215
216        /**
217         * Returns the total time in microseconds associated with this Timer for the
218         * selected type of statistics.
219         *
220         * @param batteryRealtime system realtime on  battery in microseconds
221         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
222         * @return a time in microseconds
223         */
224        public abstract long getTotalTimeLocked(long batteryRealtime, int which);
225
226        /**
227         * Temporary for debugging.
228         */
229        public abstract void logState(Printer pw, String prefix);
230    }
231
232    /**
233     * The statistics associated with a particular uid.
234     */
235    public static abstract class Uid {
236
237        /**
238         * Returns a mapping containing wakelock statistics.
239         *
240         * @return a Map from Strings to Uid.Wakelock objects.
241         */
242        public abstract Map<String, ? extends Wakelock> getWakelockStats();
243
244        /**
245         * The statistics associated with a particular wake lock.
246         */
247        public static abstract class Wakelock {
248            public abstract Timer getWakeTime(int type);
249        }
250
251        /**
252         * Returns a mapping containing sensor statistics.
253         *
254         * @return a Map from Integer sensor ids to Uid.Sensor objects.
255         */
256        public abstract Map<Integer, ? extends Sensor> getSensorStats();
257
258        /**
259         * Returns a mapping containing active process data.
260         */
261        public abstract SparseArray<? extends Pid> getPidStats();
262
263        /**
264         * Returns a mapping containing process statistics.
265         *
266         * @return a Map from Strings to Uid.Proc objects.
267         */
268        public abstract Map<String, ? extends Proc> getProcessStats();
269
270        /**
271         * Returns a mapping containing package statistics.
272         *
273         * @return a Map from Strings to Uid.Pkg objects.
274         */
275        public abstract Map<String, ? extends Pkg> getPackageStats();
276
277        /**
278         * {@hide}
279         */
280        public abstract int getUid();
281
282        public abstract void noteWifiRunningLocked(long elapsedRealtime);
283        public abstract void noteWifiStoppedLocked(long elapsedRealtime);
284        public abstract void noteFullWifiLockAcquiredLocked(long elapsedRealtime);
285        public abstract void noteFullWifiLockReleasedLocked(long elapsedRealtime);
286        public abstract void noteWifiScanStartedLocked(long elapsedRealtime);
287        public abstract void noteWifiScanStoppedLocked(long elapsedRealtime);
288        public abstract void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtime);
289        public abstract void noteWifiBatchedScanStoppedLocked(long elapsedRealtime);
290        public abstract void noteWifiMulticastEnabledLocked(long elapsedRealtime);
291        public abstract void noteWifiMulticastDisabledLocked(long elapsedRealtime);
292        public abstract void noteAudioTurnedOnLocked(long elapsedRealtime);
293        public abstract void noteAudioTurnedOffLocked(long elapsedRealtime);
294        public abstract void noteVideoTurnedOnLocked(long elapsedRealtime);
295        public abstract void noteVideoTurnedOffLocked(long elapsedRealtime);
296        public abstract void noteActivityResumedLocked(long elapsedRealtime);
297        public abstract void noteActivityPausedLocked(long elapsedRealtime);
298        public abstract long getWifiRunningTime(long batteryRealtime, int which);
299        public abstract long getFullWifiLockTime(long batteryRealtime, int which);
300        public abstract long getWifiScanTime(long batteryRealtime, int which);
301        public abstract long getWifiBatchedScanTime(int csphBin, long batteryRealtime, int which);
302        public abstract long getWifiMulticastTime(long batteryRealtime,
303                                                  int which);
304        public abstract long getAudioTurnedOnTime(long batteryRealtime, int which);
305        public abstract long getVideoTurnedOnTime(long batteryRealtime, int which);
306        public abstract Timer getForegroundActivityTimer();
307        public abstract Timer getVibratorOnTimer();
308
309        public static final int NUM_WIFI_BATCHED_SCAN_BINS = 5;
310
311        /**
312         * Note that these must match the constants in android.os.PowerManager.
313         * Also, if the user activity types change, the BatteryStatsImpl.VERSION must
314         * also be bumped.
315         */
316        static final String[] USER_ACTIVITY_TYPES = {
317            "other", "button", "touch"
318        };
319
320        public static final int NUM_USER_ACTIVITY_TYPES = 3;
321
322        public abstract void noteUserActivityLocked(int type);
323        public abstract boolean hasUserActivity();
324        public abstract int getUserActivityCount(int type, int which);
325
326        public abstract boolean hasNetworkActivity();
327        public abstract long getNetworkActivityBytes(int type, int which);
328        public abstract long getNetworkActivityPackets(int type, int which);
329        public abstract long getMobileRadioActiveTime(int which);
330        public abstract int getMobileRadioActiveCount(int which);
331
332        public static abstract class Sensor {
333            /*
334             * FIXME: it's not correct to use this magic value because it
335             * could clash with a sensor handle (which are defined by
336             * the sensor HAL, and therefore out of our control
337             */
338            // Magic sensor number for the GPS.
339            public static final int GPS = -10000;
340
341            public abstract int getHandle();
342
343            public abstract Timer getSensorTime();
344        }
345
346        public class Pid {
347            public long mWakeSum;
348            public long mWakeStart;
349        }
350
351        /**
352         * The statistics associated with a particular process.
353         */
354        public static abstract class Proc {
355
356            public static class ExcessivePower {
357                public static final int TYPE_WAKE = 1;
358                public static final int TYPE_CPU = 2;
359
360                public int type;
361                public long overTime;
362                public long usedTime;
363            }
364
365            /**
366             * Returns true if this process is still active in the battery stats.
367             */
368            public abstract boolean isActive();
369
370            /**
371             * Returns the total time (in 1/100 sec) spent executing in user code.
372             *
373             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
374             */
375            public abstract long getUserTime(int which);
376
377            /**
378             * Returns the total time (in 1/100 sec) spent executing in system code.
379             *
380             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
381             */
382            public abstract long getSystemTime(int which);
383
384            /**
385             * Returns the number of times the process has been started.
386             *
387             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
388             */
389            public abstract int getStarts(int which);
390
391            /**
392             * Returns the cpu time spent in microseconds while the process was in the foreground.
393             * @param which one of STATS_TOTAL, STATS_LAST, STATS_CURRENT or STATS_UNPLUGGED
394             * @return foreground cpu time in microseconds
395             */
396            public abstract long getForegroundTime(int which);
397
398            /**
399             * Returns the approximate cpu time spent in microseconds, at a certain CPU speed.
400             * @param speedStep the index of the CPU speed. This is not the actual speed of the
401             * CPU.
402             * @param which one of STATS_TOTAL, STATS_LAST, STATS_CURRENT or STATS_UNPLUGGED
403             * @see BatteryStats#getCpuSpeedSteps()
404             */
405            public abstract long getTimeAtCpuSpeedStep(int speedStep, int which);
406
407            public abstract int countExcessivePowers();
408
409            public abstract ExcessivePower getExcessivePower(int i);
410        }
411
412        /**
413         * The statistics associated with a particular package.
414         */
415        public static abstract class Pkg {
416
417            /**
418             * Returns the number of times this package has done something that could wake up the
419             * device from sleep.
420             *
421             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
422             */
423            public abstract int getWakeups(int which);
424
425            /**
426             * Returns a mapping containing service statistics.
427             */
428            public abstract Map<String, ? extends Serv> getServiceStats();
429
430            /**
431             * The statistics associated with a particular service.
432             */
433            public abstract class Serv {
434
435                /**
436                 * Returns the amount of time spent started.
437                 *
438                 * @param batteryUptime elapsed uptime on battery in microseconds.
439                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
440                 * @return
441                 */
442                public abstract long getStartTime(long batteryUptime, int which);
443
444                /**
445                 * Returns the total number of times startService() has been called.
446                 *
447                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
448                 */
449                public abstract int getStarts(int which);
450
451                /**
452                 * Returns the total number times the service has been launched.
453                 *
454                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
455                 */
456                public abstract int getLaunches(int which);
457            }
458        }
459    }
460
461    public final static class HistoryTag {
462        public String string;
463        public int uid;
464
465        public int poolIdx;
466
467        public void setTo(HistoryTag o) {
468            string = o.string;
469            uid = o.uid;
470            poolIdx = o.poolIdx;
471        }
472
473        public void setTo(String _string, int _uid) {
474            string = _string;
475            uid = _uid;
476            poolIdx = -1;
477        }
478
479        public void writeToParcel(Parcel dest, int flags) {
480            dest.writeString(string);
481            dest.writeInt(uid);
482        }
483
484        public void readFromParcel(Parcel src) {
485            string = src.readString();
486            uid = src.readInt();
487            poolIdx = -1;
488        }
489
490        @Override
491        public boolean equals(Object o) {
492            if (this == o) return true;
493            if (o == null || getClass() != o.getClass()) return false;
494
495            HistoryTag that = (HistoryTag) o;
496
497            if (uid != that.uid) return false;
498            if (!string.equals(that.string)) return false;
499
500            return true;
501        }
502
503        @Override
504        public int hashCode() {
505            int result = string.hashCode();
506            result = 31 * result + uid;
507            return result;
508        }
509    }
510
511    public final static class HistoryItem implements Parcelable {
512        public HistoryItem next;
513
514        public long time;
515
516        public static final byte CMD_UPDATE = 0;        // These can be written as deltas
517        public static final byte CMD_NULL = -1;
518        public static final byte CMD_START = 4;
519        public static final byte CMD_OVERFLOW = 5;
520
521        public byte cmd = CMD_NULL;
522
523        /**
524         * Return whether the command code is a delta data update.
525         */
526        public boolean isDeltaData() {
527            return cmd == CMD_UPDATE;
528        }
529
530        public byte batteryLevel;
531        public byte batteryStatus;
532        public byte batteryHealth;
533        public byte batteryPlugType;
534
535        public short batteryTemperature;
536        public char batteryVoltage;
537
538        // Constants from SCREEN_BRIGHTNESS_*
539        public static final int STATE_BRIGHTNESS_SHIFT = 0;
540        public static final int STATE_BRIGHTNESS_MASK = 0x7;
541        // Constants from SIGNAL_STRENGTH_*
542        public static final int STATE_SIGNAL_STRENGTH_SHIFT = 3;
543        public static final int STATE_SIGNAL_STRENGTH_MASK = 0x7 << STATE_SIGNAL_STRENGTH_SHIFT;
544        // Constants from ServiceState.STATE_*
545        public static final int STATE_PHONE_STATE_SHIFT = 6;
546        public static final int STATE_PHONE_STATE_MASK = 0x7 << STATE_PHONE_STATE_SHIFT;
547        // Constants from DATA_CONNECTION_*
548        public static final int STATE_DATA_CONNECTION_SHIFT = 9;
549        public static final int STATE_DATA_CONNECTION_MASK = 0x1f << STATE_DATA_CONNECTION_SHIFT;
550
551        // These states always appear directly in the first int token
552        // of a delta change; they should be ones that change relatively
553        // frequently.
554        public static final int STATE_WAKE_LOCK_FLAG = 1<<31;
555        public static final int STATE_SENSOR_ON_FLAG = 1<<30;
556        public static final int STATE_GPS_ON_FLAG = 1<<29;
557        public static final int STATE_WIFI_FULL_LOCK_FLAG = 1<<28;
558        public static final int STATE_WIFI_SCAN_FLAG = 1<<27;
559        public static final int STATE_WIFI_MULTICAST_ON_FLAG = 1<<26;
560        public static final int STATE_MOBILE_RADIO_ACTIVE_FLAG = 1<<25;
561        public static final int STATE_WIFI_RUNNING_FLAG = 1<<24;
562        // These are on the lower bits used for the command; if they change
563        // we need to write another int of data.
564        public static final int STATE_PHONE_SCANNING_FLAG = 1<<23;
565        public static final int STATE_AUDIO_ON_FLAG = 1<<22;
566        public static final int STATE_VIDEO_ON_FLAG = 1<<21;
567        public static final int STATE_SCREEN_ON_FLAG = 1<<20;
568        public static final int STATE_BATTERY_PLUGGED_FLAG = 1<<19;
569        public static final int STATE_PHONE_IN_CALL_FLAG = 1<<18;
570        public static final int STATE_WIFI_ON_FLAG = 1<<17;
571        public static final int STATE_BLUETOOTH_ON_FLAG = 1<<16;
572
573        public static final int MOST_INTERESTING_STATES =
574            STATE_BATTERY_PLUGGED_FLAG | STATE_SCREEN_ON_FLAG
575            | STATE_GPS_ON_FLAG | STATE_PHONE_IN_CALL_FLAG;
576
577        public int states;
578
579        // The wake lock that was acquired at this point.
580        public HistoryTag wakelockTag;
581
582        public static final int EVENT_FLAG_START = 0x8000;
583        public static final int EVENT_FLAG_FINISH = 0x4000;
584
585        // No event in this item.
586        public static final int EVENT_NONE = 0x0000;
587        // Event is about a process that is running.
588        public static final int EVENT_PROC = 0x0001;
589        // Event is about an application package that is in the foreground.
590        public static final int EVENT_FOREGROUND = 0x0002;
591        // Event is about an application package that is at the top of the screen.
592        public static final int EVENT_TOP = 0x0003;
593        // Event is about an application package that is at the top of the screen.
594        public static final int EVENT_SYNC = 0x0004;
595        // Number of event types.
596        public static final int EVENT_COUNT = 0x0005;
597
598        public static final int EVENT_PROC_START = EVENT_PROC | EVENT_FLAG_START;
599        public static final int EVENT_PROC_FINISH = EVENT_PROC | EVENT_FLAG_FINISH;
600        public static final int EVENT_FOREGROUND_START = EVENT_FOREGROUND | EVENT_FLAG_START;
601        public static final int EVENT_FOREGROUND_FINISH = EVENT_FOREGROUND | EVENT_FLAG_FINISH;
602        public static final int EVENT_TOP_START = EVENT_TOP | EVENT_FLAG_START;
603        public static final int EVENT_TOP_FINISH = EVENT_TOP | EVENT_FLAG_FINISH;
604        public static final int EVENT_SYNC_START = EVENT_SYNC | EVENT_FLAG_START;
605        public static final int EVENT_SYNC_FINISH = EVENT_SYNC | EVENT_FLAG_FINISH;
606
607        // For CMD_EVENT.
608        public int eventCode;
609        public HistoryTag eventTag;
610
611        // Meta-data when reading.
612        public int numReadInts;
613
614        // Pre-allocated objects.
615        public final HistoryTag localWakelockTag = new HistoryTag();
616        public final HistoryTag localEventTag = new HistoryTag();
617
618        public HistoryItem() {
619        }
620
621        public HistoryItem(long time, Parcel src) {
622            this.time = time;
623            numReadInts = 2;
624            readFromParcel(src);
625        }
626
627        public int describeContents() {
628            return 0;
629        }
630
631        public void writeToParcel(Parcel dest, int flags) {
632            dest.writeLong(time);
633            int bat = (((int)cmd)&0xff)
634                    | ((((int)batteryLevel)<<8)&0xff00)
635                    | ((((int)batteryStatus)<<16)&0xf0000)
636                    | ((((int)batteryHealth)<<20)&0xf00000)
637                    | ((((int)batteryPlugType)<<24)&0xf000000);
638            dest.writeInt(bat);
639            bat = (((int)batteryTemperature)&0xffff)
640                    | ((((int)batteryVoltage)<<16)&0xffff0000);
641            dest.writeInt(bat);
642            dest.writeInt(states);
643            if (wakelockTag != null) {
644                dest.writeInt(1);
645                wakelockTag.writeToParcel(dest, flags);
646            } else {
647                dest.writeInt(0);
648            }
649            dest.writeInt(eventCode);
650            if (eventCode != EVENT_NONE) {
651                dest.writeInt(eventCode);
652                eventTag.writeToParcel(dest, flags);
653            }
654        }
655
656        public void readFromParcel(Parcel src) {
657            int start = src.dataPosition();
658            int bat = src.readInt();
659            cmd = (byte)(bat&0xff);
660            batteryLevel = (byte)((bat>>8)&0xff);
661            batteryStatus = (byte)((bat>>16)&0xf);
662            batteryHealth = (byte)((bat>>20)&0xf);
663            batteryPlugType = (byte)((bat>>24)&0xf);
664            bat = src.readInt();
665            batteryTemperature = (short)(bat&0xffff);
666            batteryVoltage = (char)((bat>>16)&0xffff);
667            states = src.readInt();
668            if (src.readInt() != 0) {
669                wakelockTag = localWakelockTag;
670                wakelockTag.readFromParcel(src);
671            } else {
672                wakelockTag = null;
673            }
674            eventCode = src.readInt();
675            if (eventCode != EVENT_NONE) {
676                eventTag = localEventTag;
677                eventTag.readFromParcel(src);
678            }
679            numReadInts += (src.dataPosition()-start)/4;
680        }
681
682        public void clear() {
683            time = 0;
684            cmd = CMD_NULL;
685            batteryLevel = 0;
686            batteryStatus = 0;
687            batteryHealth = 0;
688            batteryPlugType = 0;
689            batteryTemperature = 0;
690            batteryVoltage = 0;
691            states = 0;
692            wakelockTag = null;
693            eventCode = EVENT_NONE;
694            eventTag = null;
695        }
696
697        public void setTo(HistoryItem o) {
698            time = o.time;
699            cmd = o.cmd;
700            setToCommon(o);
701        }
702
703        public void setTo(long time, byte cmd, HistoryItem o) {
704            this.time = time;
705            this.cmd = cmd;
706            setToCommon(o);
707        }
708
709        private void setToCommon(HistoryItem o) {
710            batteryLevel = o.batteryLevel;
711            batteryStatus = o.batteryStatus;
712            batteryHealth = o.batteryHealth;
713            batteryPlugType = o.batteryPlugType;
714            batteryTemperature = o.batteryTemperature;
715            batteryVoltage = o.batteryVoltage;
716            states = o.states;
717            if (o.wakelockTag != null) {
718                wakelockTag = localWakelockTag;
719                wakelockTag.setTo(o.wakelockTag);
720            } else {
721                wakelockTag = null;
722            }
723            eventCode = o.eventCode;
724            if (o.eventTag != null) {
725                eventTag = localEventTag;
726                eventTag.setTo(o.eventTag);
727            } else {
728                eventTag = null;
729            }
730        }
731
732        public boolean sameNonEvent(HistoryItem o) {
733            return batteryLevel == o.batteryLevel
734                    && batteryStatus == o.batteryStatus
735                    && batteryHealth == o.batteryHealth
736                    && batteryPlugType == o.batteryPlugType
737                    && batteryTemperature == o.batteryTemperature
738                    && batteryVoltage == o.batteryVoltage
739                    && states == o.states;
740        }
741
742        public boolean same(HistoryItem o) {
743            if (!sameNonEvent(o) || eventCode != o.eventCode) {
744                return false;
745            }
746            if (wakelockTag != o.wakelockTag) {
747                if (wakelockTag == null || o.wakelockTag == null) {
748                    return false;
749                }
750                if (!wakelockTag.equals(o.wakelockTag)) {
751                    return false;
752                }
753            }
754            if (eventTag != o.eventTag) {
755                if (eventTag == null || o.eventTag == null) {
756                    return false;
757                }
758                if (!eventTag.equals(o.eventTag)) {
759                    return false;
760                }
761            }
762            return true;
763        }
764    }
765
766    public static final class BitDescription {
767        public final int mask;
768        public final int shift;
769        public final String name;
770        public final String shortName;
771        public final String[] values;
772        public final String[] shortValues;
773
774        public BitDescription(int mask, String name, String shortName) {
775            this.mask = mask;
776            this.shift = -1;
777            this.name = name;
778            this.shortName = shortName;
779            this.values = null;
780            this.shortValues = null;
781        }
782
783        public BitDescription(int mask, int shift, String name, String shortName,
784                String[] values, String[] shortValues) {
785            this.mask = mask;
786            this.shift = shift;
787            this.name = name;
788            this.shortName = shortName;
789            this.values = values;
790            this.shortValues = shortValues;
791        }
792    }
793
794    public abstract int getHistoryTotalSize();
795
796    public abstract int getHistoryUsedSize();
797
798    public abstract boolean startIteratingHistoryLocked();
799
800    public abstract int getHistoryStringPoolSize();
801
802    public abstract int getHistoryStringPoolBytes();
803
804    public abstract String getHistoryTagPoolString(int index);
805
806    public abstract int getHistoryTagPoolUid(int index);
807
808    public abstract boolean getNextHistoryLocked(HistoryItem out);
809
810    public abstract void finishIteratingHistoryLocked();
811
812    public abstract boolean startIteratingOldHistoryLocked();
813
814    public abstract boolean getNextOldHistoryLocked(HistoryItem out);
815
816    public abstract void finishIteratingOldHistoryLocked();
817
818    /**
819     * Return the base time offset for the battery history.
820     */
821    public abstract long getHistoryBaseTime();
822
823    /**
824     * Returns the number of times the device has been started.
825     */
826    public abstract int getStartCount();
827
828    /**
829     * Returns the time in microseconds that the screen has been on while the device was
830     * running on battery.
831     *
832     * {@hide}
833     */
834    public abstract long getScreenOnTime(long batteryRealtime, int which);
835
836    /**
837     * Returns the number of times the screen was turned on.
838     *
839     * {@hide}
840     */
841    public abstract int getScreenOnCount(int which);
842
843    public static final int SCREEN_BRIGHTNESS_DARK = 0;
844    public static final int SCREEN_BRIGHTNESS_DIM = 1;
845    public static final int SCREEN_BRIGHTNESS_MEDIUM = 2;
846    public static final int SCREEN_BRIGHTNESS_LIGHT = 3;
847    public static final int SCREEN_BRIGHTNESS_BRIGHT = 4;
848
849    static final String[] SCREEN_BRIGHTNESS_NAMES = {
850        "dark", "dim", "medium", "light", "bright"
851    };
852
853    static final String[] SCREEN_BRIGHTNESS_SHORT_NAMES = {
854        "0", "1", "2", "3", "4"
855    };
856
857    public static final int NUM_SCREEN_BRIGHTNESS_BINS = 5;
858
859    /**
860     * Returns the time in microseconds that the screen has been on with
861     * the given brightness
862     *
863     * {@hide}
864     */
865    public abstract long getScreenBrightnessTime(int brightnessBin,
866            long batteryRealtime, int which);
867
868    public abstract int getInputEventCount(int which);
869
870    /**
871     * Returns the time in microseconds that the phone has been on while the device was
872     * running on battery.
873     *
874     * {@hide}
875     */
876    public abstract long getPhoneOnTime(long batteryRealtime, int which);
877
878    /**
879     * Returns the number of times a phone call was activated.
880     *
881     * {@hide}
882     */
883    public abstract int getPhoneOnCount(int which);
884
885    /**
886     * Returns the time in microseconds that the phone has been running with
887     * the given signal strength.
888     *
889     * {@hide}
890     */
891    public abstract long getPhoneSignalStrengthTime(int strengthBin,
892            long batteryRealtime, int which);
893
894    /**
895     * Returns the time in microseconds that the phone has been trying to
896     * acquire a signal.
897     *
898     * {@hide}
899     */
900    public abstract long getPhoneSignalScanningTime(
901            long batteryRealtime, int which);
902
903    /**
904     * Returns the number of times the phone has entered the given signal strength.
905     *
906     * {@hide}
907     */
908    public abstract int getPhoneSignalStrengthCount(int strengthBin, int which);
909
910    /**
911     * Returns the time in microseconds that the mobile network has been active
912     * (in a high power state).
913     *
914     * {@hide}
915     */
916    public abstract long getMobileRadioActiveTime(long batteryRealtime, int which);
917
918    /**
919     * Returns the number of times that the mobile network has transitioned to the
920     * active state.
921     *
922     * {@hide}
923     */
924    public abstract int getMobileRadioActiveCount(int which);
925
926    /**
927     * Returns the time in microseconds that the mobile network has been active
928     * (in a high power state) but not being able to blame on an app.
929     *
930     * {@hide}
931     */
932    public abstract long getMobileRadioActiveUnknownTime(int which);
933
934    /**
935     * Return count of number of times radio was up that could not be blamed on apps.
936     *
937     * {@hide}
938     */
939    public abstract int getMobileRadioActiveUnknownCount(int which);
940
941    public static final int DATA_CONNECTION_NONE = 0;
942    public static final int DATA_CONNECTION_GPRS = 1;
943    public static final int DATA_CONNECTION_EDGE = 2;
944    public static final int DATA_CONNECTION_UMTS = 3;
945    public static final int DATA_CONNECTION_CDMA = 4;
946    public static final int DATA_CONNECTION_EVDO_0 = 5;
947    public static final int DATA_CONNECTION_EVDO_A = 6;
948    public static final int DATA_CONNECTION_1xRTT = 7;
949    public static final int DATA_CONNECTION_HSDPA = 8;
950    public static final int DATA_CONNECTION_HSUPA = 9;
951    public static final int DATA_CONNECTION_HSPA = 10;
952    public static final int DATA_CONNECTION_IDEN = 11;
953    public static final int DATA_CONNECTION_EVDO_B = 12;
954    public static final int DATA_CONNECTION_LTE = 13;
955    public static final int DATA_CONNECTION_EHRPD = 14;
956    public static final int DATA_CONNECTION_HSPAP = 15;
957    public static final int DATA_CONNECTION_OTHER = 16;
958
959    static final String[] DATA_CONNECTION_NAMES = {
960        "none", "gprs", "edge", "umts", "cdma", "evdo_0", "evdo_A",
961        "1xrtt", "hsdpa", "hsupa", "hspa", "iden", "evdo_b", "lte",
962        "ehrpd", "hspap", "other"
963    };
964
965    public static final int NUM_DATA_CONNECTION_TYPES = DATA_CONNECTION_OTHER+1;
966
967    /**
968     * Returns the time in microseconds that the phone has been running with
969     * the given data connection.
970     *
971     * {@hide}
972     */
973    public abstract long getPhoneDataConnectionTime(int dataType,
974            long batteryRealtime, int which);
975
976    /**
977     * Returns the number of times the phone has entered the given data
978     * connection type.
979     *
980     * {@hide}
981     */
982    public abstract int getPhoneDataConnectionCount(int dataType, int which);
983
984    public static final BitDescription[] HISTORY_STATE_DESCRIPTIONS
985            = new BitDescription[] {
986        new BitDescription(HistoryItem.STATE_WAKE_LOCK_FLAG, "wake_lock", "w"),
987        new BitDescription(HistoryItem.STATE_SENSOR_ON_FLAG, "sensor", "s"),
988        new BitDescription(HistoryItem.STATE_GPS_ON_FLAG, "gps", "g"),
989        new BitDescription(HistoryItem.STATE_WIFI_FULL_LOCK_FLAG, "wifi_full_lock", "Wl"),
990        new BitDescription(HistoryItem.STATE_WIFI_SCAN_FLAG, "wifi_scan", "Ws"),
991        new BitDescription(HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG, "wifi_multicast", "Wm"),
992        new BitDescription(HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG, "mobile_radio", "Pr"),
993        new BitDescription(HistoryItem.STATE_WIFI_RUNNING_FLAG, "wifi_running", "Wr"),
994        new BitDescription(HistoryItem.STATE_PHONE_SCANNING_FLAG, "phone_scanning", "Psc"),
995        new BitDescription(HistoryItem.STATE_AUDIO_ON_FLAG, "audio", "a"),
996        new BitDescription(HistoryItem.STATE_VIDEO_ON_FLAG, "video", "v"),
997        new BitDescription(HistoryItem.STATE_SCREEN_ON_FLAG, "screen", "S"),
998        new BitDescription(HistoryItem.STATE_BATTERY_PLUGGED_FLAG, "plugged", "BP"),
999        new BitDescription(HistoryItem.STATE_PHONE_IN_CALL_FLAG, "phone_in_call", "Pcl"),
1000        new BitDescription(HistoryItem.STATE_WIFI_ON_FLAG, "wifi", "W"),
1001        new BitDescription(HistoryItem.STATE_BLUETOOTH_ON_FLAG, "bluetooth", "b"),
1002        new BitDescription(HistoryItem.STATE_DATA_CONNECTION_MASK,
1003                HistoryItem.STATE_DATA_CONNECTION_SHIFT, "data_conn", "Pcn",
1004                DATA_CONNECTION_NAMES, DATA_CONNECTION_NAMES),
1005        new BitDescription(HistoryItem.STATE_PHONE_STATE_MASK,
1006                HistoryItem.STATE_PHONE_STATE_SHIFT, "phone_state", "Pst",
1007                new String[] {"in", "out", "emergency", "off"},
1008                new String[] {"in", "out", "em", "off"}),
1009        new BitDescription(HistoryItem.STATE_SIGNAL_STRENGTH_MASK,
1010                HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT, "signal_strength", "Pss",
1011                SignalStrength.SIGNAL_STRENGTH_NAMES, new String[] {
1012                    "0", "1", "2", "3", "4"
1013        }),
1014        new BitDescription(HistoryItem.STATE_BRIGHTNESS_MASK,
1015                HistoryItem.STATE_BRIGHTNESS_SHIFT, "brightness", "Sb",
1016                SCREEN_BRIGHTNESS_NAMES, SCREEN_BRIGHTNESS_SHORT_NAMES),
1017    };
1018
1019    public static final String[] HISTORY_EVENT_NAMES = new String[] {
1020            "null", "proc", "fg", "top", "sync"
1021    };
1022
1023    public static final String[] HISTORY_EVENT_CHECKIN_NAMES = new String[] {
1024            "Enl", "Epr", "Efg", "Etp", "Esy"
1025    };
1026
1027    /**
1028     * Returns the time in microseconds that wifi has been on while the device was
1029     * running on battery.
1030     *
1031     * {@hide}
1032     */
1033    public abstract long getWifiOnTime(long batteryRealtime, int which);
1034
1035    /**
1036     * Returns the time in microseconds that wifi has been on and the driver has
1037     * been in the running state while the device was running on battery.
1038     *
1039     * {@hide}
1040     */
1041    public abstract long getGlobalWifiRunningTime(long batteryRealtime, int which);
1042
1043    public static final int WIFI_STATE_OFF = 0;
1044    public static final int WIFI_STATE_OFF_SCANNING = 1;
1045    public static final int WIFI_STATE_ON_NO_NETWORKS = 2;
1046    public static final int WIFI_STATE_ON_DISCONNECTED = 3;
1047    public static final int WIFI_STATE_ON_CONNECTED_STA = 4;
1048    public static final int WIFI_STATE_ON_CONNECTED_P2P = 5;
1049    public static final int WIFI_STATE_ON_CONNECTED_STA_P2P = 6;
1050    public static final int WIFI_STATE_SOFT_AP = 7;
1051
1052    static final String[] WIFI_STATE_NAMES = {
1053        "off", "scanning", "no_net", "disconn",
1054        "sta", "p2p", "sta_p2p", "soft_ap"
1055    };
1056
1057    public static final int NUM_WIFI_STATES = WIFI_STATE_SOFT_AP+1;
1058
1059    /**
1060     * Returns the time in microseconds that WiFi has been running in the given state.
1061     *
1062     * {@hide}
1063     */
1064    public abstract long getWifiStateTime(int wifiState,
1065            long batteryRealtime, int which);
1066
1067    /**
1068     * Returns the number of times that WiFi has entered the given state.
1069     *
1070     * {@hide}
1071     */
1072    public abstract int getWifiStateCount(int wifiState, int which);
1073
1074    /**
1075     * Returns the time in microseconds that bluetooth has been on while the device was
1076     * running on battery.
1077     *
1078     * {@hide}
1079     */
1080    public abstract long getBluetoothOnTime(long batteryRealtime, int which);
1081
1082    public abstract int getBluetoothPingCount();
1083
1084    public static final int BLUETOOTH_STATE_INACTIVE = 0;
1085    public static final int BLUETOOTH_STATE_LOW = 1;
1086    public static final int BLUETOOTH_STATE_MEDIUM = 2;
1087    public static final int BLUETOOTH_STATE_HIGH = 3;
1088
1089    static final String[] BLUETOOTH_STATE_NAMES = {
1090        "inactive", "low", "med", "high"
1091    };
1092
1093    public static final int NUM_BLUETOOTH_STATES = BLUETOOTH_STATE_HIGH +1;
1094
1095    /**
1096     * Returns the time in microseconds that Bluetooth has been running in the
1097     * given active state.
1098     *
1099     * {@hide}
1100     */
1101    public abstract long getBluetoothStateTime(int bluetoothState,
1102            long batteryRealtime, int which);
1103
1104    /**
1105     * Returns the number of times that Bluetooth has entered the given active state.
1106     *
1107     * {@hide}
1108     */
1109    public abstract int getBluetoothStateCount(int bluetoothState, int which);
1110
1111    public static final int NETWORK_MOBILE_RX_DATA = 0;
1112    public static final int NETWORK_MOBILE_TX_DATA = 1;
1113    public static final int NETWORK_WIFI_RX_DATA = 2;
1114    public static final int NETWORK_WIFI_TX_DATA = 3;
1115
1116    public static final int NUM_NETWORK_ACTIVITY_TYPES = NETWORK_WIFI_TX_DATA + 1;
1117
1118    public abstract long getNetworkActivityBytes(int type, int which);
1119    public abstract long getNetworkActivityPackets(int type, int which);
1120
1121    /**
1122     * Return the wall clock time when battery stats data collection started.
1123     */
1124    public abstract long getStartClockTime();
1125
1126    /**
1127     * Return whether we are currently running on battery.
1128     */
1129    public abstract boolean getIsOnBattery();
1130
1131    /**
1132     * Returns a SparseArray containing the statistics for each uid.
1133     */
1134    public abstract SparseArray<? extends Uid> getUidStats();
1135
1136    /**
1137     * Returns the current battery uptime in microseconds.
1138     *
1139     * @param curTime the amount of elapsed realtime in microseconds.
1140     */
1141    public abstract long getBatteryUptime(long curTime);
1142
1143    /**
1144     * Returns the current battery realtime in microseconds.
1145     *
1146     * @param curTime the amount of elapsed realtime in microseconds.
1147     */
1148    public abstract long getBatteryRealtime(long curTime);
1149
1150    /**
1151     * Returns the battery percentage level at the last time the device was unplugged from power, or
1152     * the last time it booted on battery power.
1153     */
1154    public abstract int getDischargeStartLevel();
1155
1156    /**
1157     * Returns the current battery percentage level if we are in a discharge cycle, otherwise
1158     * returns the level at the last plug event.
1159     */
1160    public abstract int getDischargeCurrentLevel();
1161
1162    /**
1163     * Get the amount the battery has discharged since the stats were
1164     * last reset after charging, as a lower-end approximation.
1165     */
1166    public abstract int getLowDischargeAmountSinceCharge();
1167
1168    /**
1169     * Get the amount the battery has discharged since the stats were
1170     * last reset after charging, as an upper-end approximation.
1171     */
1172    public abstract int getHighDischargeAmountSinceCharge();
1173
1174    /**
1175     * Get the amount the battery has discharged while the screen was on,
1176     * since the last time power was unplugged.
1177     */
1178    public abstract int getDischargeAmountScreenOn();
1179
1180    /**
1181     * Get the amount the battery has discharged while the screen was on,
1182     * since the last time the device was charged.
1183     */
1184    public abstract int getDischargeAmountScreenOnSinceCharge();
1185
1186    /**
1187     * Get the amount the battery has discharged while the screen was off,
1188     * since the last time power was unplugged.
1189     */
1190    public abstract int getDischargeAmountScreenOff();
1191
1192    /**
1193     * Get the amount the battery has discharged while the screen was off,
1194     * since the last time the device was charged.
1195     */
1196    public abstract int getDischargeAmountScreenOffSinceCharge();
1197
1198    /**
1199     * Returns the total, last, or current battery uptime in microseconds.
1200     *
1201     * @param curTime the elapsed realtime in microseconds.
1202     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
1203     */
1204    public abstract long computeBatteryUptime(long curTime, int which);
1205
1206    /**
1207     * Returns the total, last, or current battery realtime in microseconds.
1208     *
1209     * @param curTime the current elapsed realtime in microseconds.
1210     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
1211     */
1212    public abstract long computeBatteryRealtime(long curTime, int which);
1213
1214    /**
1215     * Returns the total, last, or current uptime in microseconds.
1216     *
1217     * @param curTime the current elapsed realtime in microseconds.
1218     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
1219     */
1220    public abstract long computeUptime(long curTime, int which);
1221
1222    /**
1223     * Returns the total, last, or current realtime in microseconds.
1224     * *
1225     * @param curTime the current elapsed realtime in microseconds.
1226     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
1227     */
1228    public abstract long computeRealtime(long curTime, int which);
1229
1230    public abstract Map<String, ? extends Timer> getKernelWakelockStats();
1231
1232    /** Returns the number of different speeds that the CPU can run at */
1233    public abstract int getCpuSpeedSteps();
1234
1235    public abstract void writeToParcelWithoutUids(Parcel out, int flags);
1236
1237    private final static void formatTimeRaw(StringBuilder out, long seconds) {
1238        long days = seconds / (60 * 60 * 24);
1239        if (days != 0) {
1240            out.append(days);
1241            out.append("d ");
1242        }
1243        long used = days * 60 * 60 * 24;
1244
1245        long hours = (seconds - used) / (60 * 60);
1246        if (hours != 0 || used != 0) {
1247            out.append(hours);
1248            out.append("h ");
1249        }
1250        used += hours * 60 * 60;
1251
1252        long mins = (seconds-used) / 60;
1253        if (mins != 0 || used != 0) {
1254            out.append(mins);
1255            out.append("m ");
1256        }
1257        used += mins * 60;
1258
1259        if (seconds != 0 || used != 0) {
1260            out.append(seconds-used);
1261            out.append("s ");
1262        }
1263    }
1264
1265    private final static void formatTime(StringBuilder sb, long time) {
1266        long sec = time / 100;
1267        formatTimeRaw(sb, sec);
1268        sb.append((time - (sec * 100)) * 10);
1269        sb.append("ms ");
1270    }
1271
1272    private final static void formatTimeMs(StringBuilder sb, long time) {
1273        long sec = time / 1000;
1274        formatTimeRaw(sb, sec);
1275        sb.append(time - (sec * 1000));
1276        sb.append("ms ");
1277    }
1278
1279    private final static void formatTimeMsNoSpace(StringBuilder sb, long time) {
1280        long sec = time / 1000;
1281        formatTimeRaw(sb, sec);
1282        sb.append(time - (sec * 1000));
1283        sb.append("ms");
1284    }
1285
1286    private final String formatRatioLocked(long num, long den) {
1287        if (den == 0L) {
1288            return "--%";
1289        }
1290        float perc = ((float)num) / ((float)den) * 100;
1291        mFormatBuilder.setLength(0);
1292        mFormatter.format("%.1f%%", perc);
1293        return mFormatBuilder.toString();
1294    }
1295
1296    private final String formatBytesLocked(long bytes) {
1297        mFormatBuilder.setLength(0);
1298
1299        if (bytes < BYTES_PER_KB) {
1300            return bytes + "B";
1301        } else if (bytes < BYTES_PER_MB) {
1302            mFormatter.format("%.2fKB", bytes / (double) BYTES_PER_KB);
1303            return mFormatBuilder.toString();
1304        } else if (bytes < BYTES_PER_GB){
1305            mFormatter.format("%.2fMB", bytes / (double) BYTES_PER_MB);
1306            return mFormatBuilder.toString();
1307        } else {
1308            mFormatter.format("%.2fGB", bytes / (double) BYTES_PER_GB);
1309            return mFormatBuilder.toString();
1310        }
1311    }
1312
1313    private static long computeWakeLock(Timer timer, long batteryRealtime, int which) {
1314        if (timer != null) {
1315            // Convert from microseconds to milliseconds with rounding
1316            long totalTimeMicros = timer.getTotalTimeLocked(batteryRealtime, which);
1317            long totalTimeMillis = (totalTimeMicros + 500) / 1000;
1318            return totalTimeMillis;
1319        }
1320        return 0;
1321    }
1322
1323    /**
1324     *
1325     * @param sb a StringBuilder object.
1326     * @param timer a Timer object contining the wakelock times.
1327     * @param batteryRealtime the current on-battery time in microseconds.
1328     * @param name the name of the wakelock.
1329     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
1330     * @param linePrefix a String to be prepended to each line of output.
1331     * @return the line prefix
1332     */
1333    private static final String printWakeLock(StringBuilder sb, Timer timer,
1334            long batteryRealtime, String name, int which, String linePrefix) {
1335
1336        if (timer != null) {
1337            long totalTimeMillis = computeWakeLock(timer, batteryRealtime, which);
1338
1339            int count = timer.getCountLocked(which);
1340            if (totalTimeMillis != 0) {
1341                sb.append(linePrefix);
1342                formatTimeMs(sb, totalTimeMillis);
1343                if (name != null) {
1344                    sb.append(name);
1345                    sb.append(' ');
1346                }
1347                sb.append('(');
1348                sb.append(count);
1349                sb.append(" times)");
1350                return ", ";
1351            }
1352        }
1353        return linePrefix;
1354    }
1355
1356    /**
1357     * Checkin version of wakelock printer. Prints simple comma-separated list.
1358     *
1359     * @param sb a StringBuilder object.
1360     * @param timer a Timer object contining the wakelock times.
1361     * @param now the current time in microseconds.
1362     * @param name the name of the wakelock.
1363     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
1364     * @param linePrefix a String to be prepended to each line of output.
1365     * @return the line prefix
1366     */
1367    private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, long now,
1368            String name, int which, String linePrefix) {
1369        long totalTimeMicros = 0;
1370        int count = 0;
1371        if (timer != null) {
1372            totalTimeMicros = timer.getTotalTimeLocked(now, which);
1373            count = timer.getCountLocked(which);
1374        }
1375        sb.append(linePrefix);
1376        sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding
1377        sb.append(',');
1378        sb.append(name != null ? name + "," : "");
1379        sb.append(count);
1380        return ",";
1381    }
1382
1383    /**
1384     * Dump a comma-separated line of values for terse checkin mode.
1385     *
1386     * @param pw the PageWriter to dump log to
1387     * @param category category of data (e.g. "total", "last", "unplugged", "current" )
1388     * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" ,  "process", "network")
1389     * @param args type-dependent data arguments
1390     */
1391    private static final void dumpLine(PrintWriter pw, int uid, String category, String type,
1392           Object... args ) {
1393        pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
1394        pw.print(uid); pw.print(',');
1395        pw.print(category); pw.print(',');
1396        pw.print(type);
1397
1398        for (Object arg : args) {
1399            pw.print(',');
1400            pw.print(arg);
1401        }
1402        pw.println();
1403    }
1404
1405    /**
1406     * Checkin server version of dump to produce more compact, computer-readable log.
1407     *
1408     * NOTE: all times are expressed in 'ms'.
1409     */
1410    public final void dumpCheckinLocked(Context context, PrintWriter pw, int which, int reqUid) {
1411        final long rawUptime = SystemClock.uptimeMillis() * 1000;
1412        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
1413        final long batteryUptime = getBatteryUptime(rawUptime);
1414        final long batteryRealtime = getBatteryRealtime(rawRealtime);
1415        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
1416        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
1417        final long totalRealtime = computeRealtime(rawRealtime, which);
1418        final long totalUptime = computeUptime(rawUptime, which);
1419        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1420        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1421        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1422        final long wifiRunningTime = getGlobalWifiRunningTime(batteryRealtime, which);
1423        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1424
1425        StringBuilder sb = new StringBuilder(128);
1426
1427        SparseArray<? extends Uid> uidStats = getUidStats();
1428        final int NU = uidStats.size();
1429
1430        String category = STAT_NAMES[which];
1431
1432        // Dump "battery" stat
1433        dumpLine(pw, 0 /* uid */, category, BATTERY_DATA,
1434                which == STATS_SINCE_CHARGED ? getStartCount() : "N/A",
1435                whichBatteryRealtime / 1000, whichBatteryUptime / 1000,
1436                totalRealtime / 1000, totalUptime / 1000,
1437                getStartClockTime());
1438
1439        // Calculate wakelock times across all uids.
1440        long fullWakeLockTimeTotal = 0;
1441        long partialWakeLockTimeTotal = 0;
1442
1443        for (int iu = 0; iu < NU; iu++) {
1444            Uid u = uidStats.valueAt(iu);
1445
1446            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1447            if (wakelocks.size() > 0) {
1448                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1449                        : wakelocks.entrySet()) {
1450                    Uid.Wakelock wl = ent.getValue();
1451
1452                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1453                    if (fullWakeTimer != null) {
1454                        fullWakeLockTimeTotal += fullWakeTimer.getTotalTimeLocked(batteryRealtime, which);
1455                    }
1456
1457                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1458                    if (partialWakeTimer != null) {
1459                        partialWakeLockTimeTotal += partialWakeTimer.getTotalTimeLocked(
1460                            batteryRealtime, which);
1461                    }
1462                }
1463            }
1464        }
1465
1466        long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
1467        long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
1468        long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
1469        long wifiTxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
1470        long mobileRxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
1471        long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
1472        long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
1473        long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
1474
1475        // Dump network stats
1476        dumpLine(pw, 0 /* uid */, category, GLOBAL_NETWORK_DATA,
1477                mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes,
1478                mobileRxTotalPackets, mobileTxTotalPackets, wifiRxTotalPackets, wifiTxTotalPackets);
1479
1480        // Dump misc stats
1481        dumpLine(pw, 0 /* uid */, category, MISC_DATA,
1482                screenOnTime / 1000, phoneOnTime / 1000, wifiOnTime / 1000,
1483                wifiRunningTime / 1000, bluetoothOnTime / 1000,
1484                mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes,
1485                fullWakeLockTimeTotal, partialWakeLockTimeTotal,
1486                getInputEventCount(which), getMobileRadioActiveTime(batteryRealtime, which));
1487
1488        // Dump screen brightness stats
1489        Object[] args = new Object[NUM_SCREEN_BRIGHTNESS_BINS];
1490        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1491            args[i] = getScreenBrightnessTime(i, batteryRealtime, which) / 1000;
1492        }
1493        dumpLine(pw, 0 /* uid */, category, SCREEN_BRIGHTNESS_DATA, args);
1494
1495        // Dump signal strength stats
1496        args = new Object[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
1497        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
1498            args[i] = getPhoneSignalStrengthTime(i, batteryRealtime, which) / 1000;
1499        }
1500        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_TIME_DATA, args);
1501        dumpLine(pw, 0 /* uid */, category, SIGNAL_SCANNING_TIME_DATA,
1502                getPhoneSignalScanningTime(batteryRealtime, which) / 1000);
1503        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
1504            args[i] = getPhoneSignalStrengthCount(i, which);
1505        }
1506        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_COUNT_DATA, args);
1507
1508        // Dump network type stats
1509        args = new Object[NUM_DATA_CONNECTION_TYPES];
1510        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1511            args[i] = getPhoneDataConnectionTime(i, batteryRealtime, which) / 1000;
1512        }
1513        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_TIME_DATA, args);
1514        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1515            args[i] = getPhoneDataConnectionCount(i, which);
1516        }
1517        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_COUNT_DATA, args);
1518
1519        // Dump wifi state stats
1520        args = new Object[NUM_WIFI_STATES];
1521        for (int i=0; i<NUM_WIFI_STATES; i++) {
1522            args[i] = getWifiStateTime(i, batteryRealtime, which) / 1000;
1523        }
1524        dumpLine(pw, 0 /* uid */, category, WIFI_STATE_TIME_DATA, args);
1525        for (int i=0; i<NUM_WIFI_STATES; i++) {
1526            args[i] = getWifiStateCount(i, which);
1527        }
1528        dumpLine(pw, 0 /* uid */, category, WIFI_STATE_COUNT_DATA, args);
1529
1530        // Dump bluetooth state stats
1531        args = new Object[NUM_BLUETOOTH_STATES];
1532        for (int i=0; i<NUM_BLUETOOTH_STATES; i++) {
1533            args[i] = getBluetoothStateTime(i, batteryRealtime, which) / 1000;
1534        }
1535        dumpLine(pw, 0 /* uid */, category, BLUETOOTH_STATE_TIME_DATA, args);
1536        for (int i=0; i<NUM_BLUETOOTH_STATES; i++) {
1537            args[i] = getBluetoothStateCount(i, which);
1538        }
1539        dumpLine(pw, 0 /* uid */, category, BLUETOOTH_STATE_COUNT_DATA, args);
1540
1541        if (which == STATS_SINCE_UNPLUGGED) {
1542            dumpLine(pw, 0 /* uid */, category, BATTERY_LEVEL_DATA, getDischargeStartLevel(),
1543                    getDischargeCurrentLevel());
1544        }
1545
1546        if (which == STATS_SINCE_UNPLUGGED) {
1547            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
1548                    getDischargeStartLevel()-getDischargeCurrentLevel(),
1549                    getDischargeStartLevel()-getDischargeCurrentLevel(),
1550                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
1551        } else {
1552            dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
1553                    getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(),
1554                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
1555        }
1556
1557        if (reqUid < 0) {
1558            Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1559            if (kernelWakelocks.size() > 0) {
1560                for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1561                    sb.setLength(0);
1562                    printWakeLockCheckin(sb, ent.getValue(), batteryRealtime, null, which, "");
1563
1564                    dumpLine(pw, 0 /* uid */, category, KERNEL_WAKELOCK_DATA, ent.getKey(),
1565                            sb.toString());
1566                }
1567            }
1568        }
1569
1570        BatteryStatsHelper helper = new BatteryStatsHelper(context);
1571        helper.create(this);
1572        helper.refreshStats(which, UserHandle.USER_ALL);
1573        List<BatterySipper> sippers = helper.getUsageList();
1574        if (sippers != null && sippers.size() > 0) {
1575            dumpLine(pw, 0 /* uid */, category, POWER_USE_SUMMARY_DATA,
1576                    BatteryStatsHelper.makemAh(helper.getPowerProfile().getBatteryCapacity()),
1577                    BatteryStatsHelper.makemAh(helper.getComputedPower()),
1578                    BatteryStatsHelper.makemAh(helper.getMinDrainedPower()),
1579                    BatteryStatsHelper.makemAh(helper.getMaxDrainedPower()));
1580            for (int i=0; i<sippers.size(); i++) {
1581                BatterySipper bs = sippers.get(i);
1582                int uid = 0;
1583                String label;
1584                switch (bs.drainType) {
1585                    case IDLE:
1586                        label="idle";
1587                        break;
1588                    case CELL:
1589                        label="cell";
1590                        break;
1591                    case PHONE:
1592                        label="phone";
1593                        break;
1594                    case WIFI:
1595                        label="wifi";
1596                        break;
1597                    case BLUETOOTH:
1598                        label="blue";
1599                        break;
1600                    case SCREEN:
1601                        label="scrn";
1602                        break;
1603                    case APP:
1604                        uid = bs.uidObj.getUid();
1605                        label = "uid";
1606                        break;
1607                    case USER:
1608                        uid = UserHandle.getUid(bs.userId, 0);
1609                        label = "user";
1610                        break;
1611                    case UNACCOUNTED:
1612                        label = "unacc";
1613                        break;
1614                    case OVERCOUNTED:
1615                        label = "over";
1616                        break;
1617                    default:
1618                        label = "???";
1619                }
1620                dumpLine(pw, uid, category, POWER_USE_ITEM_DATA, label,
1621                        BatteryStatsHelper.makemAh(bs.value));
1622            }
1623        }
1624
1625        for (int iu = 0; iu < NU; iu++) {
1626            final int uid = uidStats.keyAt(iu);
1627            if (reqUid >= 0 && uid != reqUid) {
1628                continue;
1629            }
1630            Uid u = uidStats.valueAt(iu);
1631            // Dump Network stats per uid, if any
1632            long mobileBytesRx = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
1633            long mobileBytesTx = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
1634            long wifiBytesRx = u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
1635            long wifiBytesTx = u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
1636            long mobilePacketsRx = u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
1637            long mobilePacketsTx = u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
1638            long mobileActiveTime = u.getMobileRadioActiveTime(which);
1639            int mobileActiveCount = u.getMobileRadioActiveCount(which);
1640            long wifiPacketsRx = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
1641            long wifiPacketsTx = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
1642            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
1643            long wifiScanTime = u.getWifiScanTime(batteryRealtime, which);
1644            long uidWifiRunningTime = u.getWifiRunningTime(batteryRealtime, which);
1645
1646            if (mobileBytesRx > 0 || mobileBytesTx > 0 || wifiBytesRx > 0 || wifiBytesTx > 0
1647                    || mobilePacketsRx > 0 || mobilePacketsTx > 0 || wifiPacketsRx > 0
1648                    || wifiPacketsTx > 0 || mobileActiveTime > 0 || mobileActiveCount > 0) {
1649                dumpLine(pw, uid, category, NETWORK_DATA, mobileBytesRx, mobileBytesTx,
1650                        wifiBytesRx, wifiBytesTx,
1651                        mobilePacketsRx, mobilePacketsTx,
1652                        wifiPacketsRx, wifiPacketsTx,
1653                        mobileActiveTime, mobileActiveCount);
1654            }
1655
1656            if (fullWifiLockOnTime != 0 || wifiScanTime != 0
1657                    || uidWifiRunningTime != 0) {
1658                dumpLine(pw, uid, category, WIFI_DATA,
1659                        fullWifiLockOnTime, wifiScanTime, uidWifiRunningTime);
1660            }
1661
1662            if (u.hasUserActivity()) {
1663                args = new Object[Uid.NUM_USER_ACTIVITY_TYPES];
1664                boolean hasData = false;
1665                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
1666                    int val = u.getUserActivityCount(i, which);
1667                    args[i] = val;
1668                    if (val != 0) hasData = true;
1669                }
1670                if (hasData) {
1671                    dumpLine(pw, 0 /* uid */, category, USER_ACTIVITY_DATA, args);
1672                }
1673            }
1674
1675            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1676            if (wakelocks.size() > 0) {
1677                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1678                        : wakelocks.entrySet()) {
1679                    Uid.Wakelock wl = ent.getValue();
1680                    String linePrefix = "";
1681                    sb.setLength(0);
1682                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL),
1683                            batteryRealtime, "f", which, linePrefix);
1684                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL),
1685                            batteryRealtime, "p", which, linePrefix);
1686                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW),
1687                            batteryRealtime, "w", which, linePrefix);
1688
1689                    // Only log if we had at lease one wakelock...
1690                    if (sb.length() > 0) {
1691                        String name = ent.getKey();
1692                        if (name.indexOf(',') >= 0) {
1693                            name = name.replace(',', '_');
1694                        }
1695                        dumpLine(pw, uid, category, WAKELOCK_DATA, name, sb.toString());
1696                    }
1697                }
1698            }
1699
1700            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
1701            if (sensors.size() > 0)  {
1702                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
1703                        : sensors.entrySet()) {
1704                    Uid.Sensor se = ent.getValue();
1705                    int sensorNumber = ent.getKey();
1706                    Timer timer = se.getSensorTime();
1707                    if (timer != null) {
1708                        // Convert from microseconds to milliseconds with rounding
1709                        long totalTime = (timer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
1710                        int count = timer.getCountLocked(which);
1711                        if (totalTime != 0) {
1712                            dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count);
1713                        }
1714                    }
1715                }
1716            }
1717
1718            Timer vibTimer = u.getVibratorOnTimer();
1719            if (vibTimer != null) {
1720                // Convert from microseconds to milliseconds with rounding
1721                long totalTime = (vibTimer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
1722                int count = vibTimer.getCountLocked(which);
1723                if (totalTime != 0) {
1724                    dumpLine(pw, uid, category, VIBRATOR_DATA, totalTime, count);
1725                }
1726            }
1727
1728            Timer fgTimer = u.getForegroundActivityTimer();
1729            if (fgTimer != null) {
1730                // Convert from microseconds to milliseconds with rounding
1731                long totalTime = (fgTimer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
1732                int count = fgTimer.getCountLocked(which);
1733                if (totalTime != 0) {
1734                    dumpLine(pw, uid, category, FOREGROUND_DATA, totalTime, count);
1735                }
1736            }
1737
1738            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
1739            if (processStats.size() > 0) {
1740                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
1741                        : processStats.entrySet()) {
1742                    Uid.Proc ps = ent.getValue();
1743
1744                    final long userMillis = ps.getUserTime(which) * 10;
1745                    final long systemMillis = ps.getSystemTime(which) * 10;
1746                    final long foregroundMillis = ps.getForegroundTime(which) * 10;
1747                    final long starts = ps.getStarts(which);
1748
1749                    if (userMillis != 0 || systemMillis != 0 || foregroundMillis != 0
1750                            || starts != 0) {
1751                        dumpLine(pw, uid, category, PROCESS_DATA, ent.getKey(), userMillis,
1752                                systemMillis, foregroundMillis, starts);
1753                    }
1754                }
1755            }
1756
1757            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
1758            if (packageStats.size() > 0) {
1759                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
1760                        : packageStats.entrySet()) {
1761
1762                    Uid.Pkg ps = ent.getValue();
1763                    int wakeups = ps.getWakeups(which);
1764                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
1765                    for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
1766                            : serviceStats.entrySet()) {
1767                        BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
1768                        long startTime = ss.getStartTime(batteryUptime, which);
1769                        int starts = ss.getStarts(which);
1770                        int launches = ss.getLaunches(which);
1771                        if (startTime != 0 || starts != 0 || launches != 0) {
1772                            dumpLine(pw, uid, category, APK_DATA,
1773                                    wakeups, // wakeup alarms
1774                                    ent.getKey(), // Apk
1775                                    sent.getKey(), // service
1776                                    startTime / 1000, // time spent started, in ms
1777                                    starts,
1778                                    launches);
1779                        }
1780                    }
1781                }
1782            }
1783        }
1784    }
1785
1786    static final class TimerEntry {
1787        final String mName;
1788        final int mId;
1789        final BatteryStats.Timer mTimer;
1790        final long mTime;
1791        TimerEntry(String name, int id, BatteryStats.Timer timer, long time) {
1792            mName = name;
1793            mId = id;
1794            mTimer = timer;
1795            mTime = time;
1796        }
1797    }
1798
1799    private void printmAh(PrintWriter printer, double power) {
1800        printer.print(BatteryStatsHelper.makemAh(power));
1801    }
1802
1803    @SuppressWarnings("unused")
1804    public final void dumpLocked(Context context, PrintWriter pw, String prefix, final int which,
1805            int reqUid) {
1806        final long rawUptime = SystemClock.uptimeMillis() * 1000;
1807        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
1808        final long batteryUptime = getBatteryUptime(rawUptime);
1809        final long batteryRealtime = getBatteryRealtime(rawRealtime);
1810
1811        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
1812        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
1813        final long totalRealtime = computeRealtime(rawRealtime, which);
1814        final long totalUptime = computeUptime(rawUptime, which);
1815
1816        StringBuilder sb = new StringBuilder(128);
1817
1818        SparseArray<? extends Uid> uidStats = getUidStats();
1819        final int NU = uidStats.size();
1820
1821        sb.setLength(0);
1822        sb.append(prefix);
1823                sb.append("  Time on battery: ");
1824                formatTimeMs(sb, whichBatteryRealtime / 1000); sb.append("(");
1825                sb.append(formatRatioLocked(whichBatteryRealtime, totalRealtime));
1826                sb.append(") realtime, ");
1827                formatTimeMs(sb, whichBatteryUptime / 1000);
1828                sb.append("("); sb.append(formatRatioLocked(whichBatteryUptime, totalRealtime));
1829                sb.append(") uptime");
1830        pw.println(sb.toString());
1831        sb.setLength(0);
1832        sb.append(prefix);
1833                sb.append("  Total run time: ");
1834                formatTimeMs(sb, totalRealtime / 1000);
1835                sb.append("realtime, ");
1836                formatTimeMs(sb, totalUptime / 1000);
1837                sb.append("uptime");
1838        pw.println(sb.toString());
1839        pw.print("  Start clock time: ");
1840        pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss", getStartClockTime()).toString());
1841
1842        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1843        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1844        final long wifiRunningTime = getGlobalWifiRunningTime(batteryRealtime, which);
1845        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1846        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1847        sb.setLength(0);
1848        sb.append(prefix);
1849                sb.append("  Screen on: "); formatTimeMs(sb, screenOnTime / 1000);
1850                sb.append("("); sb.append(formatRatioLocked(screenOnTime, whichBatteryRealtime));
1851                sb.append(") "); sb.append(getScreenOnCount(which));
1852                sb.append("x, Input events: "); sb.append(getInputEventCount(which));
1853        pw.println(sb.toString());
1854        if (phoneOnTime != 0) {
1855            sb.setLength(0);
1856            sb.append(prefix);
1857                    sb.append("  Active phone call: "); formatTimeMs(sb, phoneOnTime / 1000);
1858                    sb.append("("); sb.append(formatRatioLocked(phoneOnTime, whichBatteryRealtime));
1859                    sb.append(") "); sb.append(getPhoneOnCount(which));
1860        }
1861        sb.setLength(0);
1862        sb.append(prefix);
1863        sb.append("  Screen brightnesses:");
1864        boolean didOne = false;
1865        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1866            final long time = getScreenBrightnessTime(i, batteryRealtime, which);
1867            if (time == 0) {
1868                continue;
1869            }
1870            sb.append("\n    ");
1871            sb.append(prefix);
1872            didOne = true;
1873            sb.append(SCREEN_BRIGHTNESS_NAMES[i]);
1874            sb.append(" ");
1875            formatTimeMs(sb, time/1000);
1876            sb.append("(");
1877            sb.append(formatRatioLocked(time, screenOnTime));
1878            sb.append(")");
1879        }
1880        if (!didOne) sb.append(" (no activity)");
1881        pw.println(sb.toString());
1882
1883        // Calculate wakelock times across all uids.
1884        long fullWakeLockTimeTotalMicros = 0;
1885        long partialWakeLockTimeTotalMicros = 0;
1886
1887        final Comparator<TimerEntry> timerComparator = new Comparator<TimerEntry>() {
1888            @Override
1889            public int compare(TimerEntry lhs, TimerEntry rhs) {
1890                long lhsTime = lhs.mTime;
1891                long rhsTime = rhs.mTime;
1892                if (lhsTime < rhsTime) {
1893                    return 1;
1894                }
1895                if (lhsTime > rhsTime) {
1896                    return -1;
1897                }
1898                return 0;
1899            }
1900        };
1901
1902        if (reqUid < 0) {
1903            Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1904            if (kernelWakelocks.size() > 0) {
1905                final ArrayList<TimerEntry> timers = new ArrayList<TimerEntry>();
1906                for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1907                    BatteryStats.Timer timer = ent.getValue();
1908                    long totalTimeMillis = computeWakeLock(timer, batteryRealtime, which);
1909                    if (totalTimeMillis > 0) {
1910                        timers.add(new TimerEntry(ent.getKey(), 0, timer, totalTimeMillis));
1911                    }
1912                }
1913                Collections.sort(timers, timerComparator);
1914                for (int i=0; i<timers.size(); i++) {
1915                    TimerEntry timer = timers.get(i);
1916                    String linePrefix = ": ";
1917                    sb.setLength(0);
1918                    sb.append(prefix);
1919                    sb.append("  Kernel Wake lock ");
1920                    sb.append(timer.mName);
1921                    linePrefix = printWakeLock(sb, timer.mTimer, batteryRealtime, null,
1922                            which, linePrefix);
1923                    if (!linePrefix.equals(": ")) {
1924                        sb.append(" realtime");
1925                        // Only print out wake locks that were held
1926                        pw.println(sb.toString());
1927                    }
1928                }
1929            }
1930        }
1931
1932        final ArrayList<TimerEntry> timers = new ArrayList<TimerEntry>();
1933
1934        for (int iu = 0; iu < NU; iu++) {
1935            Uid u = uidStats.valueAt(iu);
1936
1937            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1938            if (wakelocks.size() > 0) {
1939                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1940                        : wakelocks.entrySet()) {
1941                    Uid.Wakelock wl = ent.getValue();
1942
1943                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1944                    if (fullWakeTimer != null) {
1945                        fullWakeLockTimeTotalMicros += fullWakeTimer.getTotalTimeLocked(
1946                                batteryRealtime, which);
1947                    }
1948
1949                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1950                    if (partialWakeTimer != null) {
1951                        long totalTimeMicros = partialWakeTimer.getTotalTimeLocked(
1952                                batteryRealtime, which);
1953                        if (totalTimeMicros > 0) {
1954                            if (reqUid < 0) {
1955                                // Only show the ordered list of all wake
1956                                // locks if the caller is not asking for data
1957                                // about a specific uid.
1958                                timers.add(new TimerEntry(ent.getKey(), u.getUid(),
1959                                        partialWakeTimer, totalTimeMicros));
1960                            }
1961                            partialWakeLockTimeTotalMicros += totalTimeMicros;
1962                        }
1963                    }
1964                }
1965            }
1966        }
1967
1968        long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
1969        long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
1970        long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
1971        long wifiTxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
1972        long mobileRxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
1973        long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
1974        long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
1975        long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
1976
1977        if (fullWakeLockTimeTotalMicros != 0) {
1978            sb.setLength(0);
1979            sb.append(prefix);
1980                    sb.append("  Total full wakelock time: "); formatTimeMsNoSpace(sb,
1981                            (fullWakeLockTimeTotalMicros + 500) / 1000);
1982            pw.println(sb.toString());
1983        }
1984
1985        if (partialWakeLockTimeTotalMicros != 0) {
1986            sb.setLength(0);
1987            sb.append(prefix);
1988                    sb.append("  Total partial wakelock time: "); formatTimeMsNoSpace(sb,
1989                            (partialWakeLockTimeTotalMicros + 500) / 1000);
1990            pw.println(sb.toString());
1991        }
1992
1993        pw.print(prefix);
1994                pw.print("  Mobile total received: "); pw.print(formatBytesLocked(mobileRxTotalBytes));
1995                pw.print(", sent: "); pw.print(formatBytesLocked(mobileTxTotalBytes));
1996                pw.print(" (packets received "); pw.print(mobileRxTotalPackets);
1997                pw.print(", sent "); pw.print(mobileTxTotalPackets); pw.println(")");
1998        sb.setLength(0);
1999        sb.append(prefix);
2000        sb.append("  Signal levels:");
2001        didOne = false;
2002        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
2003            final long time = getPhoneSignalStrengthTime(i, batteryRealtime, which);
2004            if (time == 0) {
2005                continue;
2006            }
2007            sb.append("\n    ");
2008            sb.append(prefix);
2009            didOne = true;
2010            sb.append(SignalStrength.SIGNAL_STRENGTH_NAMES[i]);
2011            sb.append(" ");
2012            formatTimeMs(sb, time/1000);
2013            sb.append("(");
2014            sb.append(formatRatioLocked(time, whichBatteryRealtime));
2015            sb.append(") ");
2016            sb.append(getPhoneSignalStrengthCount(i, which));
2017            sb.append("x");
2018        }
2019        if (!didOne) sb.append(" (no activity)");
2020        pw.println(sb.toString());
2021
2022        sb.setLength(0);
2023        sb.append(prefix);
2024        sb.append("  Signal scanning time: ");
2025        formatTimeMsNoSpace(sb, getPhoneSignalScanningTime(batteryRealtime, which) / 1000);
2026        pw.println(sb.toString());
2027
2028        sb.setLength(0);
2029        sb.append(prefix);
2030        sb.append("  Radio types:");
2031        didOne = false;
2032        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
2033            final long time = getPhoneDataConnectionTime(i, batteryRealtime, which);
2034            if (time == 0) {
2035                continue;
2036            }
2037            sb.append("\n    ");
2038            sb.append(prefix);
2039            didOne = true;
2040            sb.append(DATA_CONNECTION_NAMES[i]);
2041            sb.append(" ");
2042            formatTimeMs(sb, time/1000);
2043            sb.append("(");
2044            sb.append(formatRatioLocked(time, whichBatteryRealtime));
2045            sb.append(") ");
2046            sb.append(getPhoneDataConnectionCount(i, which));
2047            sb.append("x");
2048        }
2049        if (!didOne) sb.append(" (no activity)");
2050        pw.println(sb.toString());
2051
2052        sb.setLength(0);
2053        sb.append(prefix);
2054        sb.append("  Mobile radio active time: ");
2055        final long mobileActiveTime = getMobileRadioActiveTime(batteryRealtime, which);
2056        formatTimeMs(sb, mobileActiveTime / 1000);
2057        sb.append("("); sb.append(formatRatioLocked(mobileActiveTime, whichBatteryRealtime));
2058        sb.append(") "); sb.append(getMobileRadioActiveCount(which));
2059        sb.append("x");
2060        pw.println(sb.toString());
2061
2062        final long mobileActiveUnknownTime = getMobileRadioActiveUnknownTime(which);
2063        if (mobileActiveUnknownTime != 0) {
2064            sb.setLength(0);
2065            sb.append(prefix);
2066            sb.append("  Mobile radio active unknown time: ");
2067            formatTimeMs(sb, mobileActiveUnknownTime / 1000);
2068            sb.append("(");
2069            sb.append(formatRatioLocked(mobileActiveUnknownTime, whichBatteryRealtime));
2070            sb.append(") "); sb.append(getMobileRadioActiveUnknownCount(which));
2071            sb.append("x");
2072            pw.println(sb.toString());
2073        }
2074
2075        pw.print(prefix);
2076                pw.print("  Wi-Fi total received: "); pw.print(formatBytesLocked(wifiRxTotalBytes));
2077                pw.print(", sent: "); pw.print(formatBytesLocked(wifiTxTotalBytes));
2078                pw.print(" (packets received "); pw.print(wifiRxTotalPackets);
2079                pw.print(", sent "); pw.print(wifiTxTotalPackets); pw.println(")");
2080        sb.setLength(0);
2081        sb.append(prefix);
2082                sb.append("  Wifi on: "); formatTimeMs(sb, wifiOnTime / 1000);
2083                sb.append("("); sb.append(formatRatioLocked(wifiOnTime, whichBatteryRealtime));
2084                sb.append("), Wifi running: "); formatTimeMs(sb, wifiRunningTime / 1000);
2085                sb.append("("); sb.append(formatRatioLocked(wifiRunningTime, whichBatteryRealtime));
2086                sb.append(")");
2087        pw.println(sb.toString());
2088
2089        sb.setLength(0);
2090        sb.append(prefix);
2091        sb.append("  Wifi states:");
2092        didOne = false;
2093        for (int i=0; i<NUM_WIFI_STATES; i++) {
2094            final long time = getWifiStateTime(i, batteryRealtime, which);
2095            if (time == 0) {
2096                continue;
2097            }
2098            sb.append("\n    ");
2099            didOne = true;
2100            sb.append(WIFI_STATE_NAMES[i]);
2101            sb.append(" ");
2102            formatTimeMs(sb, time/1000);
2103            sb.append("(");
2104            sb.append(formatRatioLocked(time, whichBatteryRealtime));
2105            sb.append(") ");
2106            sb.append(getPhoneDataConnectionCount(i, which));
2107            sb.append("x");
2108        }
2109        if (!didOne) sb.append(" (no activity)");
2110        pw.println(sb.toString());
2111
2112        sb.setLength(0);
2113        sb.append(prefix);
2114                sb.append("  Bluetooth on: "); formatTimeMs(sb, bluetoothOnTime / 1000);
2115                sb.append("("); sb.append(formatRatioLocked(bluetoothOnTime, whichBatteryRealtime));
2116                sb.append(")");
2117        pw.println(sb.toString());
2118
2119        sb.setLength(0);
2120        sb.append(prefix);
2121        sb.append("  Bluetooth states:");
2122        didOne = false;
2123        for (int i=0; i<NUM_BLUETOOTH_STATES; i++) {
2124            final long time = getBluetoothStateTime(i, batteryRealtime, which);
2125            if (time == 0) {
2126                continue;
2127            }
2128            sb.append("\n    ");
2129            didOne = true;
2130            sb.append(BLUETOOTH_STATE_NAMES[i]);
2131            sb.append(" ");
2132            formatTimeMs(sb, time/1000);
2133            sb.append("(");
2134            sb.append(formatRatioLocked(time, whichBatteryRealtime));
2135            sb.append(") ");
2136            sb.append(getPhoneDataConnectionCount(i, which));
2137            sb.append("x");
2138        }
2139        if (!didOne) sb.append(" (no activity)");
2140        pw.println(sb.toString());
2141
2142        pw.println();
2143
2144        if (which == STATS_SINCE_UNPLUGGED) {
2145            if (getIsOnBattery()) {
2146                pw.print(prefix); pw.println("  Device is currently unplugged");
2147                pw.print(prefix); pw.print("    Discharge cycle start level: ");
2148                        pw.println(getDischargeStartLevel());
2149                pw.print(prefix); pw.print("    Discharge cycle current level: ");
2150                        pw.println(getDischargeCurrentLevel());
2151            } else {
2152                pw.print(prefix); pw.println("  Device is currently plugged into power");
2153                pw.print(prefix); pw.print("    Last discharge cycle start level: ");
2154                        pw.println(getDischargeStartLevel());
2155                pw.print(prefix); pw.print("    Last discharge cycle end level: ");
2156                        pw.println(getDischargeCurrentLevel());
2157            }
2158            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
2159                    pw.println(getDischargeAmountScreenOn());
2160            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
2161                    pw.println(getDischargeAmountScreenOff());
2162            pw.println(" ");
2163        } else {
2164            pw.print(prefix); pw.println("  Device battery use since last full charge");
2165            pw.print(prefix); pw.print("    Amount discharged (lower bound): ");
2166                    pw.println(getLowDischargeAmountSinceCharge());
2167            pw.print(prefix); pw.print("    Amount discharged (upper bound): ");
2168                    pw.println(getHighDischargeAmountSinceCharge());
2169            pw.print(prefix); pw.print("    Amount discharged while screen on: ");
2170                    pw.println(getDischargeAmountScreenOnSinceCharge());
2171            pw.print(prefix); pw.print("    Amount discharged while screen off: ");
2172                    pw.println(getDischargeAmountScreenOffSinceCharge());
2173            pw.println();
2174        }
2175
2176        BatteryStatsHelper helper = new BatteryStatsHelper(context);
2177        helper.create(this);
2178        helper.refreshStats(which, UserHandle.USER_ALL);
2179        List<BatterySipper> sippers = helper.getUsageList();
2180        if (sippers != null && sippers.size() > 0) {
2181            pw.print(prefix); pw.println("  Estimated power use (mAh):");
2182            pw.print(prefix); pw.print("    Capacity: ");
2183                    printmAh(pw, helper.getPowerProfile().getBatteryCapacity());
2184                    pw.print(", Computed drain: "); printmAh(pw, helper.getComputedPower());
2185                    pw.print(", Min drain: "); printmAh(pw, helper.getMinDrainedPower());
2186                    pw.print(", Max drain: "); printmAh(pw, helper.getMaxDrainedPower());
2187                    pw.println();
2188            for (int i=0; i<sippers.size(); i++) {
2189                BatterySipper bs = sippers.get(i);
2190                switch (bs.drainType) {
2191                    case IDLE:
2192                        pw.print(prefix); pw.print("    Idle: "); printmAh(pw, bs.value);
2193                        pw.println();
2194                        break;
2195                    case CELL:
2196                        pw.print(prefix); pw.print("    Cell standby: "); printmAh(pw, bs.value);
2197                        pw.println();
2198                        break;
2199                    case PHONE:
2200                        pw.print(prefix); pw.print("    Phone calls: "); printmAh(pw, bs.value);
2201                        pw.println();
2202                        break;
2203                    case WIFI:
2204                        pw.print(prefix); pw.print("    Wifi: "); printmAh(pw, bs.value);
2205                        pw.println();
2206                        break;
2207                    case BLUETOOTH:
2208                        pw.print(prefix); pw.print("    Bluetooth: "); printmAh(pw, bs.value);
2209                        pw.println();
2210                        break;
2211                    case SCREEN:
2212                        pw.print(prefix); pw.print("    Screen: "); printmAh(pw, bs.value);
2213                        pw.println();
2214                        break;
2215                    case APP:
2216                        pw.print(prefix); pw.print("    Uid ");
2217                        UserHandle.formatUid(pw, bs.uidObj.getUid());
2218                        pw.print(": "); printmAh(pw, bs.value); pw.println();
2219                        break;
2220                    case USER:
2221                        pw.print(prefix); pw.print("    User "); pw.print(bs.userId);
2222                        pw.print(": "); printmAh(pw, bs.value); pw.println();
2223                        break;
2224                    case UNACCOUNTED:
2225                        pw.print(prefix); pw.print("    Unaccounted: "); printmAh(pw, bs.value);
2226                        pw.println();
2227                        break;
2228                    case OVERCOUNTED:
2229                        pw.print(prefix); pw.print("    Over-counted: "); printmAh(pw, bs.value);
2230                        pw.println();
2231                        break;
2232                }
2233            }
2234            pw.println();
2235        }
2236
2237        sippers = helper.getMobilemsppList();
2238        if (sippers != null && sippers.size() > 0) {
2239            pw.print(prefix); pw.println("  Per-app mobile ms per packet:");
2240            long totalTime = 0;
2241            for (int i=0; i<sippers.size(); i++) {
2242                BatterySipper bs = sippers.get(i);
2243                sb.setLength(0);
2244                sb.append(prefix); sb.append("    Uid ");
2245                UserHandle.formatUid(sb, bs.uidObj.getUid());
2246                sb.append(": "); sb.append(BatteryStatsHelper.makemAh(bs.mobilemspp));
2247                sb.append(" ("); sb.append(bs.mobileRxPackets+bs.mobileTxPackets);
2248                sb.append(" packets over "); formatTimeMsNoSpace(sb, bs.mobileActive);
2249                sb.append(") "); sb.append(bs.mobileActiveCount); sb.append("x");
2250                pw.println(sb.toString());
2251                totalTime += bs.mobileActive;
2252            }
2253            sb.setLength(0);
2254            sb.append(prefix);
2255            sb.append("    TOTAL TIME: ");
2256            formatTimeMs(sb, totalTime);
2257            sb.append("("); sb.append(formatRatioLocked(totalTime, whichBatteryRealtime));
2258            sb.append(")");
2259            pw.println(sb.toString());
2260            pw.println();
2261        }
2262
2263        if (timers.size() > 0) {
2264            Collections.sort(timers, timerComparator);
2265            pw.print(prefix); pw.println("  All partial wake locks:");
2266            for (int i=0; i<timers.size(); i++) {
2267                TimerEntry timer = timers.get(i);
2268                sb.setLength(0);
2269                sb.append("  Wake lock ");
2270                UserHandle.formatUid(sb, timer.mId);
2271                sb.append(" ");
2272                sb.append(timer.mName);
2273                printWakeLock(sb, timer.mTimer, batteryRealtime, null, which, ": ");
2274                sb.append(" realtime");
2275                pw.println(sb.toString());
2276            }
2277            timers.clear();
2278            pw.println();
2279        }
2280
2281        for (int iu=0; iu<NU; iu++) {
2282            final int uid = uidStats.keyAt(iu);
2283            if (reqUid >= 0 && uid != reqUid && uid != Process.SYSTEM_UID) {
2284                continue;
2285            }
2286
2287            Uid u = uidStats.valueAt(iu);
2288
2289            pw.print(prefix);
2290            pw.print("  ");
2291            UserHandle.formatUid(pw, uid);
2292            pw.println(":");
2293            boolean uidActivity = false;
2294
2295            long mobileRxBytes = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
2296            long mobileTxBytes = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
2297            long wifiRxBytes = u.getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
2298            long wifiTxBytes = u.getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which);
2299            long mobileRxPackets = u.getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which);
2300            long mobileTxPackets = u.getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
2301            long uidMobileActiveTime = u.getMobileRadioActiveTime(which);
2302            int uidMobileActiveCount = u.getMobileRadioActiveCount(which);
2303            long wifiRxPackets = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
2304            long wifiTxPackets = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
2305            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
2306            long wifiScanTime = u.getWifiScanTime(batteryRealtime, which);
2307            long uidWifiRunningTime = u.getWifiRunningTime(batteryRealtime, which);
2308
2309            if (mobileRxBytes > 0 || mobileTxBytes > 0
2310                    || mobileRxPackets > 0 || mobileTxPackets > 0) {
2311                pw.print(prefix); pw.print("    Mobile network: ");
2312                        pw.print(formatBytesLocked(mobileRxBytes)); pw.print(" received, ");
2313                        pw.print(formatBytesLocked(mobileTxBytes));
2314                        pw.print(" sent (packets "); pw.print(mobileRxPackets);
2315                        pw.print(" received, "); pw.print(mobileTxPackets); pw.println(" sent)");
2316            }
2317            if (uidMobileActiveTime > 0 || uidMobileActiveCount > 0) {
2318                sb.setLength(0);
2319                sb.append(prefix); sb.append("    Mobile radio active: ");
2320                formatTimeMs(sb, uidMobileActiveTime / 1000);
2321                sb.append("(");
2322                sb.append(formatRatioLocked(uidMobileActiveTime, mobileActiveTime));
2323                sb.append(") "); sb.append(uidMobileActiveCount); sb.append("x");
2324                long packets = mobileRxPackets + mobileTxPackets;
2325                if (packets == 0) {
2326                    packets = 1;
2327                }
2328                sb.append(" @ ");
2329                sb.append(BatteryStatsHelper.makemAh(uidMobileActiveTime / 1000 / (double)packets));
2330                sb.append(" mspp");
2331                pw.println(sb.toString());
2332            }
2333
2334            if (wifiRxBytes > 0 || wifiTxBytes > 0 || wifiRxPackets > 0 || wifiTxPackets > 0) {
2335                pw.print(prefix); pw.print("    Wi-Fi network: ");
2336                        pw.print(formatBytesLocked(wifiRxBytes)); pw.print(" received, ");
2337                        pw.print(formatBytesLocked(wifiTxBytes));
2338                        pw.print(" sent (packets "); pw.print(wifiRxPackets);
2339                        pw.print(" received, "); pw.print(wifiTxPackets); pw.println(" sent)");
2340            }
2341
2342            if (fullWifiLockOnTime != 0 || wifiScanTime != 0
2343                    || uidWifiRunningTime != 0) {
2344                sb.setLength(0);
2345                sb.append(prefix); sb.append("    Wifi Running: ");
2346                        formatTimeMs(sb, uidWifiRunningTime / 1000);
2347                        sb.append("("); sb.append(formatRatioLocked(uidWifiRunningTime,
2348                                whichBatteryRealtime)); sb.append(")\n");
2349                sb.append(prefix); sb.append("    Full Wifi Lock: ");
2350                        formatTimeMs(sb, fullWifiLockOnTime / 1000);
2351                        sb.append("("); sb.append(formatRatioLocked(fullWifiLockOnTime,
2352                                whichBatteryRealtime)); sb.append(")\n");
2353                sb.append(prefix); sb.append("    Wifi Scan: ");
2354                        formatTimeMs(sb, wifiScanTime / 1000);
2355                        sb.append("("); sb.append(formatRatioLocked(wifiScanTime,
2356                                whichBatteryRealtime)); sb.append(")");
2357                pw.println(sb.toString());
2358            }
2359
2360            if (u.hasUserActivity()) {
2361                boolean hasData = false;
2362                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
2363                    int val = u.getUserActivityCount(i, which);
2364                    if (val != 0) {
2365                        if (!hasData) {
2366                            sb.setLength(0);
2367                            sb.append("    User activity: ");
2368                            hasData = true;
2369                        } else {
2370                            sb.append(", ");
2371                        }
2372                        sb.append(val);
2373                        sb.append(" ");
2374                        sb.append(Uid.USER_ACTIVITY_TYPES[i]);
2375                    }
2376                }
2377                if (hasData) {
2378                    pw.println(sb.toString());
2379                }
2380            }
2381
2382            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
2383            if (wakelocks.size() > 0) {
2384                long totalFull = 0, totalPartial = 0, totalWindow = 0;
2385                int count = 0;
2386                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
2387                    : wakelocks.entrySet()) {
2388                    Uid.Wakelock wl = ent.getValue();
2389                    String linePrefix = ": ";
2390                    sb.setLength(0);
2391                    sb.append(prefix);
2392                    sb.append("    Wake lock ");
2393                    sb.append(ent.getKey());
2394                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), batteryRealtime,
2395                            "full", which, linePrefix);
2396                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), batteryRealtime,
2397                            "partial", which, linePrefix);
2398                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), batteryRealtime,
2399                            "window", which, linePrefix);
2400                    if (!linePrefix.equals(": ")) {
2401                        sb.append(" realtime");
2402                        // Only print out wake locks that were held
2403                        pw.println(sb.toString());
2404                        uidActivity = true;
2405                        count++;
2406                    }
2407                    totalFull += computeWakeLock(wl.getWakeTime(WAKE_TYPE_FULL),
2408                            batteryRealtime, which);
2409                    totalPartial += computeWakeLock(wl.getWakeTime(WAKE_TYPE_PARTIAL),
2410                            batteryRealtime, which);
2411                    totalWindow += computeWakeLock(wl.getWakeTime(WAKE_TYPE_WINDOW),
2412                            batteryRealtime, which);
2413                }
2414                if (count > 1) {
2415                    if (totalFull != 0 || totalPartial != 0 || totalWindow != 0) {
2416                        sb.setLength(0);
2417                        sb.append(prefix);
2418                        sb.append("    TOTAL wake: ");
2419                        boolean needComma = false;
2420                        if (totalFull != 0) {
2421                            needComma = true;
2422                            formatTimeMs(sb, totalFull);
2423                            sb.append("full");
2424                        }
2425                        if (totalPartial != 0) {
2426                            if (needComma) {
2427                                sb.append(", ");
2428                            }
2429                            needComma = true;
2430                            formatTimeMs(sb, totalPartial);
2431                            sb.append("partial");
2432                        }
2433                        if (totalWindow != 0) {
2434                            if (needComma) {
2435                                sb.append(", ");
2436                            }
2437                            needComma = true;
2438                            formatTimeMs(sb, totalWindow);
2439                            sb.append("window");
2440                        }
2441                        sb.append(" realtime");
2442                        pw.println(sb.toString());
2443                    }
2444                }
2445            }
2446
2447            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
2448            if (sensors.size() > 0) {
2449                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
2450                    : sensors.entrySet()) {
2451                    Uid.Sensor se = ent.getValue();
2452                    int sensorNumber = ent.getKey();
2453                    sb.setLength(0);
2454                    sb.append(prefix);
2455                    sb.append("    Sensor ");
2456                    int handle = se.getHandle();
2457                    if (handle == Uid.Sensor.GPS) {
2458                        sb.append("GPS");
2459                    } else {
2460                        sb.append(handle);
2461                    }
2462                    sb.append(": ");
2463
2464                    Timer timer = se.getSensorTime();
2465                    if (timer != null) {
2466                        // Convert from microseconds to milliseconds with rounding
2467                        long totalTime = (timer.getTotalTimeLocked(
2468                                batteryRealtime, which) + 500) / 1000;
2469                        int count = timer.getCountLocked(which);
2470                        //timer.logState();
2471                        if (totalTime != 0) {
2472                            formatTimeMs(sb, totalTime);
2473                            sb.append("realtime (");
2474                            sb.append(count);
2475                            sb.append(" times)");
2476                        } else {
2477                            sb.append("(not used)");
2478                        }
2479                    } else {
2480                        sb.append("(not used)");
2481                    }
2482
2483                    pw.println(sb.toString());
2484                    uidActivity = true;
2485                }
2486            }
2487
2488            Timer vibTimer = u.getVibratorOnTimer();
2489            if (vibTimer != null) {
2490                // Convert from microseconds to milliseconds with rounding
2491                long totalTime = (vibTimer.getTotalTimeLocked(
2492                        batteryRealtime, which) + 500) / 1000;
2493                int count = vibTimer.getCountLocked(which);
2494                //timer.logState();
2495                if (totalTime != 0) {
2496                    sb.setLength(0);
2497                    sb.append(prefix);
2498                    sb.append("    Vibrator: ");
2499                    formatTimeMs(sb, totalTime);
2500                    sb.append("realtime (");
2501                    sb.append(count);
2502                    sb.append(" times)");
2503                    pw.println(sb.toString());
2504                    uidActivity = true;
2505                }
2506            }
2507
2508            Timer fgTimer = u.getForegroundActivityTimer();
2509            if (fgTimer != null) {
2510                // Convert from microseconds to milliseconds with rounding
2511                long totalTime = (fgTimer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
2512                int count = fgTimer.getCountLocked(which);
2513                if (totalTime != 0) {
2514                    sb.setLength(0);
2515                    sb.append(prefix);
2516                    sb.append("    Foreground activities: ");
2517                    formatTimeMs(sb, totalTime);
2518                    sb.append("realtime (");
2519                    sb.append(count);
2520                    sb.append(" times)");
2521                    pw.println(sb.toString());
2522                    uidActivity = true;
2523                }
2524            }
2525
2526            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
2527            if (processStats.size() > 0) {
2528                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
2529                    : processStats.entrySet()) {
2530                    Uid.Proc ps = ent.getValue();
2531                    long userTime;
2532                    long systemTime;
2533                    long foregroundTime;
2534                    int starts;
2535                    int numExcessive;
2536
2537                    userTime = ps.getUserTime(which);
2538                    systemTime = ps.getSystemTime(which);
2539                    foregroundTime = ps.getForegroundTime(which);
2540                    starts = ps.getStarts(which);
2541                    numExcessive = which == STATS_SINCE_CHARGED
2542                            ? ps.countExcessivePowers() : 0;
2543
2544                    if (userTime != 0 || systemTime != 0 || foregroundTime != 0 || starts != 0
2545                            || numExcessive != 0) {
2546                        sb.setLength(0);
2547                        sb.append(prefix); sb.append("    Proc ");
2548                                sb.append(ent.getKey()); sb.append(":\n");
2549                        sb.append(prefix); sb.append("      CPU: ");
2550                                formatTime(sb, userTime); sb.append("usr + ");
2551                                formatTime(sb, systemTime); sb.append("krn ; ");
2552                                formatTime(sb, foregroundTime); sb.append("fg");
2553                        if (starts != 0) {
2554                            sb.append("\n"); sb.append(prefix); sb.append("      ");
2555                                    sb.append(starts); sb.append(" proc starts");
2556                        }
2557                        pw.println(sb.toString());
2558                        for (int e=0; e<numExcessive; e++) {
2559                            Uid.Proc.ExcessivePower ew = ps.getExcessivePower(e);
2560                            if (ew != null) {
2561                                pw.print(prefix); pw.print("      * Killed for ");
2562                                        if (ew.type == Uid.Proc.ExcessivePower.TYPE_WAKE) {
2563                                            pw.print("wake lock");
2564                                        } else if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) {
2565                                            pw.print("cpu");
2566                                        } else {
2567                                            pw.print("unknown");
2568                                        }
2569                                        pw.print(" use: ");
2570                                        TimeUtils.formatDuration(ew.usedTime, pw);
2571                                        pw.print(" over ");
2572                                        TimeUtils.formatDuration(ew.overTime, pw);
2573                                        if (ew.overTime != 0) {
2574                                            pw.print(" (");
2575                                            pw.print((ew.usedTime*100)/ew.overTime);
2576                                            pw.println("%)");
2577                                        }
2578                            }
2579                        }
2580                        uidActivity = true;
2581                    }
2582                }
2583            }
2584
2585            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
2586            if (packageStats.size() > 0) {
2587                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
2588                    : packageStats.entrySet()) {
2589                    pw.print(prefix); pw.print("    Apk "); pw.print(ent.getKey()); pw.println(":");
2590                    boolean apkActivity = false;
2591                    Uid.Pkg ps = ent.getValue();
2592                    int wakeups = ps.getWakeups(which);
2593                    if (wakeups != 0) {
2594                        pw.print(prefix); pw.print("      ");
2595                                pw.print(wakeups); pw.println(" wakeup alarms");
2596                        apkActivity = true;
2597                    }
2598                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
2599                    if (serviceStats.size() > 0) {
2600                        for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
2601                                : serviceStats.entrySet()) {
2602                            BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
2603                            long startTime = ss.getStartTime(batteryUptime, which);
2604                            int starts = ss.getStarts(which);
2605                            int launches = ss.getLaunches(which);
2606                            if (startTime != 0 || starts != 0 || launches != 0) {
2607                                sb.setLength(0);
2608                                sb.append(prefix); sb.append("      Service ");
2609                                        sb.append(sent.getKey()); sb.append(":\n");
2610                                sb.append(prefix); sb.append("        Created for: ");
2611                                        formatTimeMs(sb, startTime / 1000);
2612                                        sb.append("uptime\n");
2613                                sb.append(prefix); sb.append("        Starts: ");
2614                                        sb.append(starts);
2615                                        sb.append(", launches: "); sb.append(launches);
2616                                pw.println(sb.toString());
2617                                apkActivity = true;
2618                            }
2619                        }
2620                    }
2621                    if (!apkActivity) {
2622                        pw.print(prefix); pw.println("      (nothing executed)");
2623                    }
2624                    uidActivity = true;
2625                }
2626            }
2627            if (!uidActivity) {
2628                pw.print(prefix); pw.println("    (nothing executed)");
2629            }
2630        }
2631    }
2632
2633    static void printBitDescriptions(PrintWriter pw, int oldval, int newval, HistoryTag wakelockTag,
2634            BitDescription[] descriptions, boolean longNames) {
2635        int diff = oldval ^ newval;
2636        if (diff == 0) return;
2637        boolean didWake = false;
2638        for (int i=0; i<descriptions.length; i++) {
2639            BitDescription bd = descriptions[i];
2640            if ((diff&bd.mask) != 0) {
2641                pw.print(longNames ? " " : ",");
2642                if (bd.shift < 0) {
2643                    pw.print((newval&bd.mask) != 0 ? "+" : "-");
2644                    pw.print(longNames ? bd.name : bd.shortName);
2645                    if (bd.mask == HistoryItem.STATE_WAKE_LOCK_FLAG && wakelockTag != null) {
2646                        didWake = true;
2647                        pw.print("=");
2648                        if (longNames) {
2649                            UserHandle.formatUid(pw, wakelockTag.uid);
2650                            pw.print(":\"");
2651                            pw.print(wakelockTag.string);
2652                            pw.print("\"");
2653                        } else {
2654                            pw.print(wakelockTag.poolIdx);
2655                        }
2656                    }
2657                } else {
2658                    pw.print(longNames ? bd.name : bd.shortName);
2659                    pw.print("=");
2660                    int val = (newval&bd.mask)>>bd.shift;
2661                    if (bd.values != null && val >= 0 && val < bd.values.length) {
2662                        pw.print(longNames? bd.values[val] : bd.shortValues[val]);
2663                    } else {
2664                        pw.print(val);
2665                    }
2666                }
2667            }
2668        }
2669        if (!didWake && wakelockTag != null) {
2670            pw.print(longNames ? "wake_lock=" : "w=");
2671            if (longNames) {
2672                UserHandle.formatUid(pw, wakelockTag.uid);
2673                pw.print(":\"");
2674                pw.print(wakelockTag.string);
2675                pw.print("\"");
2676            } else {
2677                pw.print(wakelockTag.poolIdx);
2678            }
2679        }
2680    }
2681
2682    public void prepareForDumpLocked() {
2683    }
2684
2685    public static class HistoryPrinter {
2686        int oldState = 0;
2687        int oldLevel = -1;
2688        int oldStatus = -1;
2689        int oldHealth = -1;
2690        int oldPlug = -1;
2691        int oldTemp = -1;
2692        int oldVolt = -1;
2693        long lastTime = -1;
2694
2695        public void printNextItem(PrintWriter pw, HistoryItem rec, long now, boolean checkin) {
2696            if (!checkin) {
2697                pw.print("  ");
2698                TimeUtils.formatDuration(rec.time-now, pw, TimeUtils.HUNDRED_DAY_FIELD_LEN);
2699                pw.print(" (");
2700                pw.print(rec.numReadInts);
2701                pw.print(") ");
2702            } else {
2703                if (lastTime < 0) {
2704                    pw.print("@");
2705                    pw.print(rec.time-now);
2706                } else {
2707                    pw.print(rec.time-lastTime);
2708                }
2709                lastTime = rec.time;
2710            }
2711            if (rec.cmd == HistoryItem.CMD_START) {
2712                if (checkin) {
2713                    pw.print(":");
2714                }
2715                pw.println("START");
2716            } else if (rec.cmd == HistoryItem.CMD_OVERFLOW) {
2717                if (checkin) {
2718                    pw.print(":");
2719                }
2720                pw.println("*OVERFLOW*");
2721            } else {
2722                if (!checkin) {
2723                    if (rec.batteryLevel < 10) pw.print("00");
2724                    else if (rec.batteryLevel < 100) pw.print("0");
2725                    pw.print(rec.batteryLevel);
2726                    pw.print(" ");
2727                    if (rec.states < 0) ;
2728                    else if (rec.states < 0x10) pw.print("0000000");
2729                    else if (rec.states < 0x100) pw.print("000000");
2730                    else if (rec.states < 0x1000) pw.print("00000");
2731                    else if (rec.states < 0x10000) pw.print("0000");
2732                    else if (rec.states < 0x100000) pw.print("000");
2733                    else if (rec.states < 0x1000000) pw.print("00");
2734                    else if (rec.states < 0x10000000) pw.print("0");
2735                    pw.print(Integer.toHexString(rec.states));
2736                } else {
2737                    if (oldLevel != rec.batteryLevel) {
2738                        oldLevel = rec.batteryLevel;
2739                        pw.print(",Bl="); pw.print(rec.batteryLevel);
2740                    }
2741                }
2742                if (oldStatus != rec.batteryStatus) {
2743                    oldStatus = rec.batteryStatus;
2744                    pw.print(checkin ? ",Bs=" : " status=");
2745                    switch (oldStatus) {
2746                        case BatteryManager.BATTERY_STATUS_UNKNOWN:
2747                            pw.print(checkin ? "?" : "unknown");
2748                            break;
2749                        case BatteryManager.BATTERY_STATUS_CHARGING:
2750                            pw.print(checkin ? "c" : "charging");
2751                            break;
2752                        case BatteryManager.BATTERY_STATUS_DISCHARGING:
2753                            pw.print(checkin ? "d" : "discharging");
2754                            break;
2755                        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
2756                            pw.print(checkin ? "n" : "not-charging");
2757                            break;
2758                        case BatteryManager.BATTERY_STATUS_FULL:
2759                            pw.print(checkin ? "f" : "full");
2760                            break;
2761                        default:
2762                            pw.print(oldStatus);
2763                            break;
2764                    }
2765                }
2766                if (oldHealth != rec.batteryHealth) {
2767                    oldHealth = rec.batteryHealth;
2768                    pw.print(checkin ? ",Bh=" : " health=");
2769                    switch (oldHealth) {
2770                        case BatteryManager.BATTERY_HEALTH_UNKNOWN:
2771                            pw.print(checkin ? "?" : "unknown");
2772                            break;
2773                        case BatteryManager.BATTERY_HEALTH_GOOD:
2774                            pw.print(checkin ? "g" : "good");
2775                            break;
2776                        case BatteryManager.BATTERY_HEALTH_OVERHEAT:
2777                            pw.print(checkin ? "h" : "overheat");
2778                            break;
2779                        case BatteryManager.BATTERY_HEALTH_DEAD:
2780                            pw.print(checkin ? "d" : "dead");
2781                            break;
2782                        case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
2783                            pw.print(checkin ? "v" : "over-voltage");
2784                            break;
2785                        case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
2786                            pw.print(checkin ? "f" : "failure");
2787                            break;
2788                        case BatteryManager.BATTERY_HEALTH_COLD:
2789                            pw.print(checkin ? "c" : "cold");
2790                            break;
2791                        default:
2792                            pw.print(oldHealth);
2793                            break;
2794                    }
2795                }
2796                if (oldPlug != rec.batteryPlugType) {
2797                    oldPlug = rec.batteryPlugType;
2798                    pw.print(checkin ? ",Bp=" : " plug=");
2799                    switch (oldPlug) {
2800                        case 0:
2801                            pw.print(checkin ? "n" : "none");
2802                            break;
2803                        case BatteryManager.BATTERY_PLUGGED_AC:
2804                            pw.print(checkin ? "a" : "ac");
2805                            break;
2806                        case BatteryManager.BATTERY_PLUGGED_USB:
2807                            pw.print(checkin ? "u" : "usb");
2808                            break;
2809                        case BatteryManager.BATTERY_PLUGGED_WIRELESS:
2810                            pw.print(checkin ? "w" : "wireless");
2811                            break;
2812                        default:
2813                            pw.print(oldPlug);
2814                            break;
2815                    }
2816                }
2817                if (oldTemp != rec.batteryTemperature) {
2818                    oldTemp = rec.batteryTemperature;
2819                    pw.print(checkin ? ",Bt=" : " temp=");
2820                    pw.print(oldTemp);
2821                }
2822                if (oldVolt != rec.batteryVoltage) {
2823                    oldVolt = rec.batteryVoltage;
2824                    pw.print(checkin ? ",Bv=" : " volt=");
2825                    pw.print(oldVolt);
2826                }
2827                printBitDescriptions(pw, oldState, rec.states, rec.wakelockTag,
2828                        HISTORY_STATE_DESCRIPTIONS, !checkin);
2829                if (rec.eventCode != HistoryItem.EVENT_NONE) {
2830                    pw.print(checkin ? "," : " ");
2831                    if ((rec.eventCode&HistoryItem.EVENT_FLAG_START) != 0) {
2832                        pw.print("+");
2833                    } else if ((rec.eventCode&HistoryItem.EVENT_FLAG_FINISH) != 0) {
2834                        pw.print("-");
2835                    }
2836                    String[] eventNames = checkin ? HISTORY_EVENT_CHECKIN_NAMES
2837                            : HISTORY_EVENT_NAMES;
2838                    int idx = rec.eventCode & ~(HistoryItem.EVENT_FLAG_START
2839                            | HistoryItem.EVENT_FLAG_FINISH);
2840                    if (idx >= 0 && idx < eventNames.length) {
2841                        pw.print(eventNames[idx]);
2842                    } else {
2843                        pw.print(checkin ? "Ev" : "event");
2844                        pw.print(idx);
2845                    }
2846                    pw.print("=");
2847                    if (checkin) {
2848                        pw.print(rec.eventTag.poolIdx);
2849                    } else {
2850                        UserHandle.formatUid(pw, rec.eventTag.uid);
2851                        pw.print(":\"");
2852                        pw.print(rec.eventTag.string);
2853                        pw.print("\"");
2854                    }
2855                }
2856                pw.println();
2857            }
2858            oldState = rec.states;
2859        }
2860    }
2861
2862    private void printSizeValue(PrintWriter pw, long size) {
2863        float result = size;
2864        String suffix = "";
2865        if (result >= 10*1024) {
2866            suffix = "KB";
2867            result = result / 1024;
2868        }
2869        if (result >= 10*1024) {
2870            suffix = "MB";
2871            result = result / 1024;
2872        }
2873        if (result >= 10*1024) {
2874            suffix = "GB";
2875            result = result / 1024;
2876        }
2877        if (result >= 10*1024) {
2878            suffix = "TB";
2879            result = result / 1024;
2880        }
2881        if (result >= 10*1024) {
2882            suffix = "PB";
2883            result = result / 1024;
2884        }
2885        pw.print((int)result);
2886        pw.print(suffix);
2887    }
2888
2889    /**
2890     * Dumps a human-readable summary of the battery statistics to the given PrintWriter.
2891     *
2892     * @param pw a Printer to receive the dump output.
2893     */
2894    @SuppressWarnings("unused")
2895    public void dumpLocked(Context context, PrintWriter pw, boolean isUnpluggedOnly, int reqUid,
2896            boolean historyOnly) {
2897        prepareForDumpLocked();
2898
2899        long now = getHistoryBaseTime() + SystemClock.elapsedRealtime();
2900
2901        final HistoryItem rec = new HistoryItem();
2902        final long historyTotalSize = getHistoryTotalSize();
2903        final long historyUsedSize = getHistoryUsedSize();
2904        if (startIteratingHistoryLocked()) {
2905            try {
2906                pw.print("Battery History (");
2907                pw.print((100*historyUsedSize)/historyTotalSize);
2908                pw.print("% used, ");
2909                printSizeValue(pw, historyUsedSize);
2910                pw.print(" used of ");
2911                printSizeValue(pw, historyTotalSize);
2912                pw.print(", ");
2913                pw.print(getHistoryStringPoolSize());
2914                pw.print(" strings using ");
2915                printSizeValue(pw, getHistoryStringPoolBytes());
2916                pw.println("):");
2917                HistoryPrinter hprinter = new HistoryPrinter();
2918                while (getNextHistoryLocked(rec)) {
2919                    hprinter.printNextItem(pw, rec, now, false);
2920                }
2921                pw.println();
2922            } finally {
2923                finishIteratingHistoryLocked();
2924            }
2925        }
2926
2927        if (startIteratingOldHistoryLocked()) {
2928            try {
2929                pw.println("Old battery History:");
2930                HistoryPrinter hprinter = new HistoryPrinter();
2931                while (getNextOldHistoryLocked(rec)) {
2932                    hprinter.printNextItem(pw, rec, now, false);
2933                }
2934                pw.println();
2935            } finally {
2936                finishIteratingOldHistoryLocked();
2937            }
2938        }
2939
2940        if (historyOnly) {
2941            return;
2942        }
2943
2944        SparseArray<? extends Uid> uidStats = getUidStats();
2945        final int NU = uidStats.size();
2946        boolean didPid = false;
2947        long nowRealtime = SystemClock.elapsedRealtime();
2948        for (int i=0; i<NU; i++) {
2949            Uid uid = uidStats.valueAt(i);
2950            SparseArray<? extends Uid.Pid> pids = uid.getPidStats();
2951            if (pids != null) {
2952                for (int j=0; j<pids.size(); j++) {
2953                    Uid.Pid pid = pids.valueAt(j);
2954                    if (!didPid) {
2955                        pw.println("Per-PID Stats:");
2956                        didPid = true;
2957                    }
2958                    long time = pid.mWakeSum + (pid.mWakeStart != 0
2959                            ? (nowRealtime - pid.mWakeStart) : 0);
2960                    pw.print("  PID "); pw.print(pids.keyAt(j));
2961                            pw.print(" wake time: ");
2962                            TimeUtils.formatDuration(time, pw);
2963                            pw.println("");
2964                }
2965            }
2966        }
2967        if (didPid) {
2968            pw.println("");
2969        }
2970
2971        if (!isUnpluggedOnly) {
2972            pw.println("Statistics since last charge:");
2973            pw.println("  System starts: " + getStartCount()
2974                    + ", currently on battery: " + getIsOnBattery());
2975            dumpLocked(context, pw, "", STATS_SINCE_CHARGED, reqUid);
2976            pw.println("");
2977        }
2978        pw.println("Statistics since last unplugged:");
2979        dumpLocked(context, pw, "", STATS_SINCE_UNPLUGGED, reqUid);
2980    }
2981
2982    @SuppressWarnings("unused")
2983    public void dumpCheckinLocked(Context context,
2984            PrintWriter pw, List<ApplicationInfo> apps, boolean isUnpluggedOnly,
2985            boolean includeHistory, boolean historyOnly) {
2986        prepareForDumpLocked();
2987
2988        long now = getHistoryBaseTime() + SystemClock.elapsedRealtime();
2989
2990        if (includeHistory || historyOnly) {
2991            final HistoryItem rec = new HistoryItem();
2992            if (startIteratingHistoryLocked()) {
2993                try {
2994                    for (int i=0; i<getHistoryStringPoolSize(); i++) {
2995                        pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
2996                        pw.print(HISTORY_STRING_POOL); pw.print(',');
2997                        pw.print(i);
2998                        pw.print(',');
2999                        pw.print(getHistoryTagPoolString(i));
3000                        pw.print(',');
3001                        pw.print(getHistoryTagPoolUid(i));
3002                        pw.println();
3003                    }
3004                    HistoryPrinter hprinter = new HistoryPrinter();
3005                    while (getNextHistoryLocked(rec)) {
3006                        pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
3007                        pw.print(HISTORY_DATA); pw.print(',');
3008                        hprinter.printNextItem(pw, rec, now, true);
3009                    }
3010                } finally {
3011                    finishIteratingHistoryLocked();
3012                }
3013            }
3014        }
3015
3016        if (historyOnly) {
3017            return;
3018        }
3019
3020        if (apps != null) {
3021            SparseArray<ArrayList<String>> uids = new SparseArray<ArrayList<String>>();
3022            for (int i=0; i<apps.size(); i++) {
3023                ApplicationInfo ai = apps.get(i);
3024                ArrayList<String> pkgs = uids.get(ai.uid);
3025                if (pkgs == null) {
3026                    pkgs = new ArrayList<String>();
3027                    uids.put(ai.uid, pkgs);
3028                }
3029                pkgs.add(ai.packageName);
3030            }
3031            SparseArray<? extends Uid> uidStats = getUidStats();
3032            final int NU = uidStats.size();
3033            String[] lineArgs = new String[2];
3034            for (int i=0; i<NU; i++) {
3035                int uid = uidStats.keyAt(i);
3036                ArrayList<String> pkgs = uids.get(uid);
3037                if (pkgs != null) {
3038                    for (int j=0; j<pkgs.size(); j++) {
3039                        lineArgs[0] = Integer.toString(uid);
3040                        lineArgs[1] = pkgs.get(j);
3041                        dumpLine(pw, 0 /* uid */, "i" /* category */, UID_DATA,
3042                                (Object[])lineArgs);
3043                    }
3044                }
3045            }
3046        }
3047        if (isUnpluggedOnly) {
3048            dumpCheckinLocked(context, pw, STATS_SINCE_UNPLUGGED, -1);
3049        }
3050        else {
3051            dumpCheckinLocked(context, pw, STATS_SINCE_CHARGED, -1);
3052            dumpCheckinLocked(context, pw, STATS_SINCE_UNPLUGGED, -1);
3053        }
3054    }
3055}
3056