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