BatteryStats.java revision e43530ab571e901f94361078c7c1f970a0bd27f2
1package android.os;
2
3import java.io.PrintWriter;
4import java.util.Formatter;
5import java.util.Map;
6
7import android.util.Log;
8import android.util.Printer;
9import android.util.SparseArray;
10
11/**
12 * A class providing access to battery usage statistics, including information on
13 * wakelocks, processes, packages, and services.  All times are represented in microseconds
14 * except where indicated otherwise.
15 * @hide
16 */
17public abstract class BatteryStats implements Parcelable {
18
19    private static final boolean LOCAL_LOGV = false;
20
21    /**
22     * A constant indicating a partial wake lock timer.
23     */
24    public static final int WAKE_TYPE_PARTIAL = 0;
25
26    /**
27     * A constant indicating a full wake lock timer.
28     */
29    public static final int WAKE_TYPE_FULL = 1;
30
31    /**
32     * A constant indicating a window wake lock timer.
33     */
34    public static final int WAKE_TYPE_WINDOW = 2;
35
36    /**
37     * A constant indicating a sensor timer.
38     *
39     * {@hide}
40     */
41    public static final int SENSOR = 3;
42
43    /**
44     * A constant indicating a a wifi turn on timer
45     *
46     * {@hide}
47     */
48    public static final int WIFI_TURNED_ON = 4;
49
50    /**
51     * A constant indicating a full wifi lock timer
52     *
53     * {@hide}
54     */
55    public static final int FULL_WIFI_LOCK = 5;
56
57    /**
58     * A constant indicating a scan wifi lock timer
59     *
60     * {@hide}
61     */
62    public static final int SCAN_WIFI_LOCK = 6;
63
64     /**
65      * A constant indicating a wifi multicast timer
66      *
67      * {@hide}
68      */
69     public static final int WIFI_MULTICAST_ENABLED = 7;
70
71    /**
72     * A constant indicating an audio turn on timer
73     *
74     * {@hide}
75     */
76    public static final int AUDIO_TURNED_ON = 7;
77
78    /**
79     * A constant indicating a video turn on timer
80     *
81     * {@hide}
82     */
83    public static final int VIDEO_TURNED_ON = 8;
84
85    /**
86     * Include all of the data in the stats, including previously saved data.
87     */
88    public static final int STATS_TOTAL = 0;
89
90    /**
91     * Include only the last run in the stats.
92     */
93    public static final int STATS_LAST = 1;
94
95    /**
96     * Include only the current run in the stats.
97     */
98    public static final int STATS_CURRENT = 2;
99
100    /**
101     * Include only the run since the last time the device was unplugged in the stats.
102     */
103    public static final int STATS_UNPLUGGED = 3;
104
105    // NOTE: Update this list if you add/change any stats above.
106    // These characters are supposed to represent "total", "last", "current",
107    // and "unplugged". They were shortened for effeciency sake.
108    private static final String[] STAT_NAMES = { "t", "l", "c", "u" };
109
110    /**
111     * Bump the version on this if the checkin format changes.
112     */
113    private static final int BATTERY_STATS_CHECKIN_VERSION = 5;
114
115    private static final long BYTES_PER_KB = 1024;
116    private static final long BYTES_PER_MB = 1048576; // 1024^2
117    private static final long BYTES_PER_GB = 1073741824; //1024^3
118
119
120    private static final String APK_DATA = "apk";
121    private static final String PROCESS_DATA = "pr";
122    private static final String SENSOR_DATA = "sr";
123    private static final String WAKELOCK_DATA = "wl";
124    private static final String KERNEL_WAKELOCK_DATA = "kwl";
125    private static final String NETWORK_DATA = "nt";
126    private static final String USER_ACTIVITY_DATA = "ua";
127    private static final String BATTERY_DATA = "bt";
128    private static final String BATTERY_LEVEL_DATA = "lv";
129    private static final String WIFI_LOCK_DATA = "wfl";
130    private static final String MISC_DATA = "m";
131    private static final String SCREEN_BRIGHTNESS_DATA = "br";
132    private static final String SIGNAL_STRENGTH_TIME_DATA = "sgt";
133    private static final String SIGNAL_STRENGTH_COUNT_DATA = "sgc";
134    private static final String DATA_CONNECTION_TIME_DATA = "dct";
135    private static final String DATA_CONNECTION_COUNT_DATA = "dcc";
136
137    private final StringBuilder mFormatBuilder = new StringBuilder(32);
138    private final Formatter mFormatter = new Formatter(mFormatBuilder);
139
140    /**
141     * State for keeping track of counting information.
142     */
143    public static abstract class Counter {
144
145        /**
146         * Returns the count associated with this Counter for the
147         * selected type of statistics.
148         *
149         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
150         */
151        public abstract int getCountLocked(int which);
152
153        /**
154         * Temporary for debugging.
155         */
156        public abstract void logState(Printer pw, String prefix);
157    }
158
159    /**
160     * State for keeping track of timing information.
161     */
162    public static abstract class Timer {
163
164        /**
165         * Returns the count associated with this Timer for the
166         * selected type of statistics.
167         *
168         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
169         */
170        public abstract int getCountLocked(int which);
171
172        /**
173         * Returns the total time in microseconds associated with this Timer for the
174         * selected type of statistics.
175         *
176         * @param batteryRealtime system realtime on  battery in microseconds
177         * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT
178         * @return a time in microseconds
179         */
180        public abstract long getTotalTimeLocked(long batteryRealtime, int which);
181
182        /**
183         * Temporary for debugging.
184         */
185        public abstract void logState(Printer pw, String prefix);
186    }
187
188    /**
189     * The statistics associated with a particular uid.
190     */
191    public static abstract class Uid {
192
193        /**
194         * Returns a mapping containing wakelock statistics.
195         *
196         * @return a Map from Strings to Uid.Wakelock objects.
197         */
198        public abstract Map<String, ? extends Wakelock> getWakelockStats();
199
200        /**
201         * The statistics associated with a particular wake lock.
202         */
203        public static abstract class Wakelock {
204            public abstract Timer getWakeTime(int type);
205        }
206
207        /**
208         * Returns a mapping containing sensor statistics.
209         *
210         * @return a Map from Integer sensor ids to Uid.Sensor objects.
211         */
212        public abstract Map<Integer, ? extends Sensor> getSensorStats();
213
214        /**
215         * Returns a mapping containing process statistics.
216         *
217         * @return a Map from Strings to Uid.Proc objects.
218         */
219        public abstract Map<String, ? extends Proc> getProcessStats();
220
221        /**
222         * Returns a mapping containing package statistics.
223         *
224         * @return a Map from Strings to Uid.Pkg objects.
225         */
226        public abstract Map<String, ? extends Pkg> getPackageStats();
227
228        /**
229         * {@hide}
230         */
231        public abstract int getUid();
232
233        /**
234         * {@hide}
235         */
236        public abstract long getTcpBytesReceived(int which);
237
238        /**
239         * {@hide}
240         */
241        public abstract long getTcpBytesSent(int which);
242
243        public abstract void noteWifiTurnedOnLocked();
244        public abstract void noteWifiTurnedOffLocked();
245        public abstract void noteFullWifiLockAcquiredLocked();
246        public abstract void noteFullWifiLockReleasedLocked();
247        public abstract void noteScanWifiLockAcquiredLocked();
248        public abstract void noteScanWifiLockReleasedLocked();
249        public abstract void noteWifiMulticastEnabledLocked();
250        public abstract void noteWifiMulticastDisabledLocked();
251        public abstract void noteAudioTurnedOnLocked();
252        public abstract void noteAudioTurnedOffLocked();
253        public abstract void noteVideoTurnedOnLocked();
254        public abstract void noteVideoTurnedOffLocked();
255        public abstract long getWifiTurnedOnTime(long batteryRealtime, int which);
256        public abstract long getFullWifiLockTime(long batteryRealtime, int which);
257        public abstract long getScanWifiLockTime(long batteryRealtime, int which);
258        public abstract long getWifiMulticastTime(long batteryRealtime,
259                                                  int which);
260        public abstract long getAudioTurnedOnTime(long batteryRealtime, int which);
261        public abstract long getVideoTurnedOnTime(long batteryRealtime, int which);
262
263        /**
264         * Note that these must match the constants in android.os.LocalPowerManager.
265         */
266        static final String[] USER_ACTIVITY_TYPES = {
267            "other", "cheek", "touch", "long_touch", "touch_up", "button", "unknown"
268        };
269
270        public static final int NUM_USER_ACTIVITY_TYPES = 7;
271
272        public abstract void noteUserActivityLocked(int type);
273        public abstract boolean hasUserActivity();
274        public abstract int getUserActivityCount(int type, int which);
275
276        public static abstract class Sensor {
277            // Magic sensor number for the GPS.
278            public static final int GPS = -10000;
279
280            public abstract int getHandle();
281
282            public abstract Timer getSensorTime();
283        }
284
285        /**
286         * The statistics associated with a particular process.
287         */
288        public static abstract class Proc {
289
290            /**
291             * Returns the total time (in 1/100 sec) spent executing in user code.
292             *
293             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
294             */
295            public abstract long getUserTime(int which);
296
297            /**
298             * Returns the total time (in 1/100 sec) spent executing in system code.
299             *
300             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
301             */
302            public abstract long getSystemTime(int which);
303
304            /**
305             * Returns the number of times the process has been started.
306             *
307             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
308             */
309            public abstract int getStarts(int which);
310
311            /**
312             * Returns the cpu time spent in microseconds while the process was in the foreground.
313             * @param which one of STATS_TOTAL, STATS_LAST, STATS_CURRENT or STATS_UNPLUGGED
314             * @return foreground cpu time in microseconds
315             */
316            public abstract long getForegroundTime(int which);
317
318            /**
319             * Returns the approximate cpu time spent in microseconds, at a certain CPU speed.
320             * @param speedStep the index of the CPU speed. This is not the actual speed of the
321             * CPU.
322             * @param which one of STATS_TOTAL, STATS_LAST, STATS_CURRENT or STATS_UNPLUGGED
323             * @see BatteryStats#getCpuSpeedSteps()
324             */
325            public abstract long getTimeAtCpuSpeedStep(int speedStep, int which);
326        }
327
328        /**
329         * The statistics associated with a particular package.
330         */
331        public static abstract class Pkg {
332
333            /**
334             * Returns the number of times this package has done something that could wake up the
335             * device from sleep.
336             *
337             * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
338             */
339            public abstract int getWakeups(int which);
340
341            /**
342             * Returns a mapping containing service statistics.
343             */
344            public abstract Map<String, ? extends Serv> getServiceStats();
345
346            /**
347             * The statistics associated with a particular service.
348             */
349            public abstract class Serv {
350
351                /**
352                 * Returns the amount of time spent started.
353                 *
354                 * @param batteryUptime elapsed uptime on battery in microseconds.
355                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
356                 * @return
357                 */
358                public abstract long getStartTime(long batteryUptime, int which);
359
360                /**
361                 * Returns the total number of times startService() has been called.
362                 *
363                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
364                 */
365                public abstract int getStarts(int which);
366
367                /**
368                 * Returns the total number times the service has been launched.
369                 *
370                 * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
371                 */
372                public abstract int getLaunches(int which);
373            }
374        }
375    }
376
377    /**
378     * Returns the number of times the device has been started.
379     */
380    public abstract int getStartCount();
381
382    /**
383     * Returns the time in microseconds that the screen has been on while the device was
384     * running on battery.
385     *
386     * {@hide}
387     */
388    public abstract long getScreenOnTime(long batteryRealtime, int which);
389
390    public static final int SCREEN_BRIGHTNESS_DARK = 0;
391    public static final int SCREEN_BRIGHTNESS_DIM = 1;
392    public static final int SCREEN_BRIGHTNESS_MEDIUM = 2;
393    public static final int SCREEN_BRIGHTNESS_LIGHT = 3;
394    public static final int SCREEN_BRIGHTNESS_BRIGHT = 4;
395
396    static final String[] SCREEN_BRIGHTNESS_NAMES = {
397        "dark", "dim", "medium", "light", "bright"
398    };
399
400    public static final int NUM_SCREEN_BRIGHTNESS_BINS = 5;
401
402    /**
403     * Returns the time in microseconds that the screen has been on with
404     * the given brightness
405     *
406     * {@hide}
407     */
408    public abstract long getScreenBrightnessTime(int brightnessBin,
409            long batteryRealtime, int which);
410
411    public abstract int getInputEventCount(int which);
412
413    /**
414     * Returns the time in microseconds that the phone has been on while the device was
415     * running on battery.
416     *
417     * {@hide}
418     */
419    public abstract long getPhoneOnTime(long batteryRealtime, int which);
420
421    public static final int SIGNAL_STRENGTH_NONE_OR_UNKNOWN = 0;
422    public static final int SIGNAL_STRENGTH_POOR = 1;
423    public static final int SIGNAL_STRENGTH_MODERATE = 2;
424    public static final int SIGNAL_STRENGTH_GOOD = 3;
425    public static final int SIGNAL_STRENGTH_GREAT = 4;
426
427    static final String[] SIGNAL_STRENGTH_NAMES = {
428        "none", "poor", "moderate", "good", "great"
429    };
430
431    public static final int NUM_SIGNAL_STRENGTH_BINS = 5;
432
433    /**
434     * Returns the time in microseconds that the phone has been running with
435     * the given signal strength.
436     *
437     * {@hide}
438     */
439    public abstract long getPhoneSignalStrengthTime(int strengthBin,
440            long batteryRealtime, int which);
441
442    /**
443     * Returns the number of times the phone has entered the given signal strength.
444     *
445     * {@hide}
446     */
447    public abstract int getPhoneSignalStrengthCount(int strengthBin, int which);
448
449    public static final int DATA_CONNECTION_NONE = 0;
450    public static final int DATA_CONNECTION_GPRS = 1;
451    public static final int DATA_CONNECTION_EDGE = 2;
452    public static final int DATA_CONNECTION_UMTS = 3;
453    public static final int DATA_CONNECTION_OTHER = 4;
454
455    static final String[] DATA_CONNECTION_NAMES = {
456        "none", "gprs", "edge", "umts", "other"
457    };
458
459    public static final int NUM_DATA_CONNECTION_TYPES = 5;
460
461    /**
462     * Returns the time in microseconds that the phone has been running with
463     * the given data connection.
464     *
465     * {@hide}
466     */
467    public abstract long getPhoneDataConnectionTime(int dataType,
468            long batteryRealtime, int which);
469
470    /**
471     * Returns the number of times the phone has entered the given data
472     * connection type.
473     *
474     * {@hide}
475     */
476    public abstract int getPhoneDataConnectionCount(int dataType, int which);
477
478    /**
479     * Returns the time in microseconds that wifi has been on while the device was
480     * running on battery.
481     *
482     * {@hide}
483     */
484    public abstract long getWifiOnTime(long batteryRealtime, int which);
485
486    /**
487     * Returns the time in microseconds that wifi has been on and the driver has
488     * been in the running state while the device was running on battery.
489     *
490     * {@hide}
491     */
492    public abstract long getWifiRunningTime(long batteryRealtime, int which);
493
494    /**
495     * Returns the time in microseconds that bluetooth has been on while the device was
496     * running on battery.
497     *
498     * {@hide}
499     */
500    public abstract long getBluetoothOnTime(long batteryRealtime, int which);
501
502    /**
503     * Return whether we are currently running on battery.
504     */
505    public abstract boolean getIsOnBattery();
506
507    /**
508     * Returns a SparseArray containing the statistics for each uid.
509     */
510    public abstract SparseArray<? extends Uid> getUidStats();
511
512    /**
513     * Returns the current battery uptime in microseconds.
514     *
515     * @param curTime the amount of elapsed realtime in microseconds.
516     */
517    public abstract long getBatteryUptime(long curTime);
518
519    /**
520     * @deprecated use getRadioDataUptime
521     */
522    public long getRadioDataUptimeMs() {
523        return getRadioDataUptime() / 1000;
524    }
525
526    /**
527     * Returns the time that the radio was on for data transfers.
528     * @return the uptime in microseconds while unplugged
529     */
530    public abstract long getRadioDataUptime();
531
532    /**
533     * Returns the current battery realtime in microseconds.
534     *
535     * @param curTime the amount of elapsed realtime in microseconds.
536     */
537    public abstract long getBatteryRealtime(long curTime);
538
539    /**
540     * Returns the battery percentage level at the last time the device was unplugged from power, or
541     * the last time it booted on battery power.
542     */
543    public abstract int getDischargeStartLevel();
544
545    /**
546     * Returns the current battery percentage level if we are in a discharge cycle, otherwise
547     * returns the level at the last plug event.
548     */
549    public abstract int getDischargeCurrentLevel();
550
551    /**
552     * Returns the total, last, or current battery uptime in microseconds.
553     *
554     * @param curTime the elapsed realtime in microseconds.
555     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
556     */
557    public abstract long computeBatteryUptime(long curTime, int which);
558
559    /**
560     * Returns the total, last, or current battery realtime in microseconds.
561     *
562     * @param curTime the current elapsed realtime in microseconds.
563     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
564     */
565    public abstract long computeBatteryRealtime(long curTime, int which);
566
567    /**
568     * Returns the total, last, or current uptime in microseconds.
569     *
570     * @param curTime the current elapsed realtime in microseconds.
571     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
572     */
573    public abstract long computeUptime(long curTime, int which);
574
575    /**
576     * Returns the total, last, or current realtime in microseconds.
577     * *
578     * @param curTime the current elapsed realtime in microseconds.
579     * @param which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
580     */
581    public abstract long computeRealtime(long curTime, int which);
582
583    public abstract Map<String, ? extends Timer> getKernelWakelockStats();
584
585    /** Returns the number of different speeds that the CPU can run at */
586    public abstract int getCpuSpeedSteps();
587
588    private final static void formatTimeRaw(StringBuilder out, long seconds) {
589        long days = seconds / (60 * 60 * 24);
590        if (days != 0) {
591            out.append(days);
592            out.append("d ");
593        }
594        long used = days * 60 * 60 * 24;
595
596        long hours = (seconds - used) / (60 * 60);
597        if (hours != 0 || used != 0) {
598            out.append(hours);
599            out.append("h ");
600        }
601        used += hours * 60 * 60;
602
603        long mins = (seconds-used) / 60;
604        if (mins != 0 || used != 0) {
605            out.append(mins);
606            out.append("m ");
607        }
608        used += mins * 60;
609
610        if (seconds != 0 || used != 0) {
611            out.append(seconds-used);
612            out.append("s ");
613        }
614    }
615
616    private final static void formatTime(StringBuilder sb, long time) {
617        long sec = time / 100;
618        formatTimeRaw(sb, sec);
619        sb.append((time - (sec * 100)) * 10);
620        sb.append("ms ");
621    }
622
623    private final static void formatTimeMs(StringBuilder sb, long time) {
624        long sec = time / 1000;
625        formatTimeRaw(sb, sec);
626        sb.append(time - (sec * 1000));
627        sb.append("ms ");
628    }
629
630    private final String formatRatioLocked(long num, long den) {
631        if (den == 0L) {
632            return "---%";
633        }
634        float perc = ((float)num) / ((float)den) * 100;
635        mFormatBuilder.setLength(0);
636        mFormatter.format("%.1f%%", perc);
637        return mFormatBuilder.toString();
638    }
639
640    private final String formatBytesLocked(long bytes) {
641        mFormatBuilder.setLength(0);
642
643        if (bytes < BYTES_PER_KB) {
644            return bytes + "B";
645        } else if (bytes < BYTES_PER_MB) {
646            mFormatter.format("%.2fKB", bytes / (double) BYTES_PER_KB);
647            return mFormatBuilder.toString();
648        } else if (bytes < BYTES_PER_GB){
649            mFormatter.format("%.2fMB", bytes / (double) BYTES_PER_MB);
650            return mFormatBuilder.toString();
651        } else {
652            mFormatter.format("%.2fGB", bytes / (double) BYTES_PER_GB);
653            return mFormatBuilder.toString();
654        }
655    }
656
657    /**
658     *
659     * @param sb a StringBuilder object.
660     * @param timer a Timer object contining the wakelock times.
661     * @param batteryRealtime the current on-battery time in microseconds.
662     * @param name the name of the wakelock.
663     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
664     * @param linePrefix a String to be prepended to each line of output.
665     * @return the line prefix
666     */
667    private static final String printWakeLock(StringBuilder sb, Timer timer,
668            long batteryRealtime, String name, int which, String linePrefix) {
669
670        if (timer != null) {
671            // Convert from microseconds to milliseconds with rounding
672            long totalTimeMicros = timer.getTotalTimeLocked(batteryRealtime, which);
673            long totalTimeMillis = (totalTimeMicros + 500) / 1000;
674
675            int count = timer.getCountLocked(which);
676            if (totalTimeMillis != 0) {
677                sb.append(linePrefix);
678                formatTimeMs(sb, totalTimeMillis);
679                if (name != null) sb.append(name);
680                sb.append(' ');
681                sb.append('(');
682                sb.append(count);
683                sb.append(" times)");
684                return ", ";
685            }
686        }
687        return linePrefix;
688    }
689
690    /**
691     * Checkin version of wakelock printer. Prints simple comma-separated list.
692     *
693     * @param sb a StringBuilder object.
694     * @param timer a Timer object contining the wakelock times.
695     * @param now the current time in microseconds.
696     * @param name the name of the wakelock.
697     * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT.
698     * @param linePrefix a String to be prepended to each line of output.
699     * @return the line prefix
700     */
701    private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, long now,
702            String name, int which, String linePrefix) {
703        long totalTimeMicros = 0;
704        int count = 0;
705        if (timer != null) {
706            totalTimeMicros = timer.getTotalTimeLocked(now, which);
707            count = timer.getCountLocked(which);
708        }
709        sb.append(linePrefix);
710        sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding
711        sb.append(',');
712        sb.append(name != null ? name + "," : "");
713        sb.append(count);
714        return ",";
715    }
716
717    /**
718     * Dump a comma-separated line of values for terse checkin mode.
719     *
720     * @param pw the PageWriter to dump log to
721     * @param category category of data (e.g. "total", "last", "unplugged", "current" )
722     * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" ,  "process", "network")
723     * @param args type-dependent data arguments
724     */
725    private static final void dumpLine(PrintWriter pw, int uid, String category, String type,
726           Object... args ) {
727        pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(',');
728        pw.print(uid); pw.print(',');
729        pw.print(category); pw.print(',');
730        pw.print(type);
731
732        for (Object arg : args) {
733            pw.print(',');
734            pw.print(arg);
735        }
736        pw.print('\n');
737    }
738
739    /**
740     * Checkin server version of dump to produce more compact, computer-readable log.
741     *
742     * NOTE: all times are expressed in 'ms'.
743     * @param fd
744     * @param pw
745     * @param which
746     */
747    private final void dumpCheckinLocked(PrintWriter pw, int which) {
748        final long rawUptime = SystemClock.uptimeMillis() * 1000;
749        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
750        final long batteryUptime = getBatteryUptime(rawUptime);
751        final long batteryRealtime = getBatteryRealtime(rawRealtime);
752        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
753        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
754        final long totalRealtime = computeRealtime(rawRealtime, which);
755        final long totalUptime = computeUptime(rawUptime, which);
756        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
757        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
758        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
759        final long wifiRunningTime = getWifiRunningTime(batteryRealtime, which);
760        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
761
762        StringBuilder sb = new StringBuilder(128);
763
764        SparseArray<? extends Uid> uidStats = getUidStats();
765        final int NU = uidStats.size();
766
767        String category = STAT_NAMES[which];
768
769        // Dump "battery" stat
770        dumpLine(pw, 0 /* uid */, category, BATTERY_DATA,
771                which == STATS_TOTAL ? getStartCount() : "N/A",
772                whichBatteryRealtime / 1000, whichBatteryUptime / 1000,
773                totalRealtime / 1000, totalUptime / 1000);
774
775        // Calculate total network and wakelock times across all uids.
776        long rxTotal = 0;
777        long txTotal = 0;
778        long fullWakeLockTimeTotal = 0;
779        long partialWakeLockTimeTotal = 0;
780
781        for (int iu = 0; iu < NU; iu++) {
782            Uid u = uidStats.valueAt(iu);
783            rxTotal += u.getTcpBytesReceived(which);
784            txTotal += u.getTcpBytesSent(which);
785
786            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
787            if (wakelocks.size() > 0) {
788                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
789                        : wakelocks.entrySet()) {
790                    Uid.Wakelock wl = ent.getValue();
791
792                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
793                    if (fullWakeTimer != null) {
794                        fullWakeLockTimeTotal += fullWakeTimer.getTotalTimeLocked(batteryRealtime, which);
795                    }
796
797                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
798                    if (partialWakeTimer != null) {
799                        partialWakeLockTimeTotal += partialWakeTimer.getTotalTimeLocked(
800                            batteryRealtime, which);
801                    }
802                }
803            }
804        }
805
806        // Dump misc stats
807        dumpLine(pw, 0 /* uid */, category, MISC_DATA,
808                screenOnTime / 1000, phoneOnTime / 1000, wifiOnTime / 1000,
809                wifiRunningTime / 1000, bluetoothOnTime / 1000, rxTotal, txTotal,
810                fullWakeLockTimeTotal, partialWakeLockTimeTotal,
811                getInputEventCount(which));
812
813        // Dump screen brightness stats
814        Object[] args = new Object[NUM_SCREEN_BRIGHTNESS_BINS];
815        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
816            args[i] = getScreenBrightnessTime(i, batteryRealtime, which) / 1000;
817        }
818        dumpLine(pw, 0 /* uid */, category, SCREEN_BRIGHTNESS_DATA, args);
819
820        // Dump signal strength stats
821        args = new Object[NUM_SIGNAL_STRENGTH_BINS];
822        for (int i=0; i<NUM_SIGNAL_STRENGTH_BINS; i++) {
823            args[i] = getPhoneSignalStrengthTime(i, batteryRealtime, which) / 1000;
824        }
825        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_TIME_DATA, args);
826        for (int i=0; i<NUM_SIGNAL_STRENGTH_BINS; i++) {
827            args[i] = getPhoneSignalStrengthCount(i, which);
828        }
829        dumpLine(pw, 0 /* uid */, category, SIGNAL_STRENGTH_COUNT_DATA, args);
830
831        // Dump network type stats
832        args = new Object[NUM_DATA_CONNECTION_TYPES];
833        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
834            args[i] = getPhoneDataConnectionTime(i, batteryRealtime, which) / 1000;
835        }
836        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_TIME_DATA, args);
837        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
838            args[i] = getPhoneDataConnectionCount(i, which);
839        }
840        dumpLine(pw, 0 /* uid */, category, DATA_CONNECTION_COUNT_DATA, args);
841
842        if (which == STATS_UNPLUGGED) {
843            dumpLine(pw, 0 /* uid */, category, BATTERY_LEVEL_DATA, getDischargeStartLevel(),
844                    getDischargeCurrentLevel());
845        }
846
847        Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
848        if (kernelWakelocks.size() > 0) {
849            for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
850                sb.setLength(0);
851                printWakeLockCheckin(sb, ent.getValue(), batteryRealtime, null, which, "");
852
853                dumpLine(pw, 0 /* uid */, category, KERNEL_WAKELOCK_DATA, ent.getKey(),
854                        sb.toString());
855            }
856        }
857
858        for (int iu = 0; iu < NU; iu++) {
859            final int uid = uidStats.keyAt(iu);
860            Uid u = uidStats.valueAt(iu);
861            // Dump Network stats per uid, if any
862            long rx = u.getTcpBytesReceived(which);
863            long tx = u.getTcpBytesSent(which);
864            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
865            long scanWifiLockOnTime = u.getScanWifiLockTime(batteryRealtime, which);
866            long wifiTurnedOnTime = u.getWifiTurnedOnTime(batteryRealtime, which);
867
868            if (rx > 0 || tx > 0) dumpLine(pw, uid, category, NETWORK_DATA, rx, tx);
869
870            if (fullWifiLockOnTime != 0 || scanWifiLockOnTime != 0
871                    || wifiTurnedOnTime != 0) {
872                dumpLine(pw, uid, category, WIFI_LOCK_DATA,
873                        fullWifiLockOnTime, scanWifiLockOnTime, wifiTurnedOnTime);
874            }
875
876            if (u.hasUserActivity()) {
877                args = new Object[Uid.NUM_USER_ACTIVITY_TYPES];
878                boolean hasData = false;
879                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
880                    int val = u.getUserActivityCount(i, which);
881                    args[i] = val;
882                    if (val != 0) hasData = true;
883                }
884                if (hasData) {
885                    dumpLine(pw, 0 /* uid */, category, USER_ACTIVITY_DATA, args);
886                }
887            }
888
889            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
890            if (wakelocks.size() > 0) {
891                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
892                        : wakelocks.entrySet()) {
893                    Uid.Wakelock wl = ent.getValue();
894                    String linePrefix = "";
895                    sb.setLength(0);
896                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL),
897                            batteryRealtime, "f", which, linePrefix);
898                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL),
899                            batteryRealtime, "p", which, linePrefix);
900                    linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW),
901                            batteryRealtime, "w", which, linePrefix);
902
903                    // Only log if we had at lease one wakelock...
904                    if (sb.length() > 0) {
905                       dumpLine(pw, uid, category, WAKELOCK_DATA, ent.getKey(), sb.toString());
906                    }
907                }
908            }
909
910            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
911            if (sensors.size() > 0)  {
912                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
913                        : sensors.entrySet()) {
914                    Uid.Sensor se = ent.getValue();
915                    int sensorNumber = ent.getKey();
916                    Timer timer = se.getSensorTime();
917                    if (timer != null) {
918                        // Convert from microseconds to milliseconds with rounding
919                        long totalTime = (timer.getTotalTimeLocked(batteryRealtime, which) + 500) / 1000;
920                        int count = timer.getCountLocked(which);
921                        if (totalTime != 0) {
922                            dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count);
923                        }
924                    }
925                }
926            }
927
928            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
929            if (processStats.size() > 0) {
930                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
931                        : processStats.entrySet()) {
932                    Uid.Proc ps = ent.getValue();
933
934                    long userTime = ps.getUserTime(which);
935                    long systemTime = ps.getSystemTime(which);
936                    int starts = ps.getStarts(which);
937
938                    if (userTime != 0 || systemTime != 0 || starts != 0) {
939                        dumpLine(pw, uid, category, PROCESS_DATA,
940                                ent.getKey(), // proc
941                                userTime * 10, // cpu time in ms
942                                systemTime * 10, // user time in ms
943                                starts); // process starts
944                    }
945                }
946            }
947
948            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
949            if (packageStats.size() > 0) {
950                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
951                        : packageStats.entrySet()) {
952
953                    Uid.Pkg ps = ent.getValue();
954                    int wakeups = ps.getWakeups(which);
955                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
956                    for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
957                            : serviceStats.entrySet()) {
958                        BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
959                        long startTime = ss.getStartTime(batteryUptime, which);
960                        int starts = ss.getStarts(which);
961                        int launches = ss.getLaunches(which);
962                        if (startTime != 0 || starts != 0 || launches != 0) {
963                            dumpLine(pw, uid, category, APK_DATA,
964                                    wakeups, // wakeup alarms
965                                    ent.getKey(), // Apk
966                                    sent.getKey(), // service
967                                    startTime / 1000, // time spent started, in ms
968                                    starts,
969                                    launches);
970                        }
971                    }
972                }
973            }
974        }
975    }
976
977    @SuppressWarnings("unused")
978    private final void dumpLocked(PrintWriter pw, String prefix, int which) {
979        final long rawUptime = SystemClock.uptimeMillis() * 1000;
980        final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
981        final long batteryUptime = getBatteryUptime(rawUptime);
982        final long batteryRealtime = getBatteryRealtime(rawRealtime);
983
984        final long whichBatteryUptime = computeBatteryUptime(rawUptime, which);
985        final long whichBatteryRealtime = computeBatteryRealtime(rawRealtime, which);
986        final long totalRealtime = computeRealtime(rawRealtime, which);
987        final long totalUptime = computeUptime(rawUptime, which);
988
989        StringBuilder sb = new StringBuilder(128);
990
991        SparseArray<? extends Uid> uidStats = getUidStats();
992        final int NU = uidStats.size();
993
994        sb.setLength(0);
995        sb.append(prefix);
996                sb.append("  Time on battery: ");
997                formatTimeMs(sb, whichBatteryRealtime / 1000); sb.append("(");
998                sb.append(formatRatioLocked(whichBatteryRealtime, totalRealtime));
999                sb.append(") realtime, ");
1000                formatTimeMs(sb, whichBatteryUptime / 1000);
1001                sb.append("("); sb.append(formatRatioLocked(whichBatteryUptime, totalRealtime));
1002                sb.append(") uptime");
1003        pw.println(sb.toString());
1004        sb.setLength(0);
1005        sb.append(prefix);
1006                sb.append("  Total run time: ");
1007                formatTimeMs(sb, totalRealtime / 1000);
1008                sb.append("realtime, ");
1009                formatTimeMs(sb, totalUptime / 1000);
1010                sb.append("uptime, ");
1011        pw.println(sb.toString());
1012
1013        final long screenOnTime = getScreenOnTime(batteryRealtime, which);
1014        final long phoneOnTime = getPhoneOnTime(batteryRealtime, which);
1015        final long wifiRunningTime = getWifiRunningTime(batteryRealtime, which);
1016        final long wifiOnTime = getWifiOnTime(batteryRealtime, which);
1017        final long bluetoothOnTime = getBluetoothOnTime(batteryRealtime, which);
1018        sb.setLength(0);
1019        sb.append(prefix);
1020                sb.append("  Screen on: "); formatTimeMs(sb, screenOnTime / 1000);
1021                sb.append("("); sb.append(formatRatioLocked(screenOnTime, whichBatteryRealtime));
1022                sb.append("), Input events: "); sb.append(getInputEventCount(which));
1023                sb.append(", Active phone call: "); formatTimeMs(sb, phoneOnTime / 1000);
1024                sb.append("("); sb.append(formatRatioLocked(phoneOnTime, whichBatteryRealtime));
1025                sb.append(")");
1026        pw.println(sb.toString());
1027        sb.setLength(0);
1028        sb.append(prefix);
1029        sb.append("  Screen brightnesses: ");
1030        boolean didOne = false;
1031        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1032            final long time = getScreenBrightnessTime(i, batteryRealtime, which);
1033            if (time == 0) {
1034                continue;
1035            }
1036            if (didOne) sb.append(", ");
1037            didOne = true;
1038            sb.append(SCREEN_BRIGHTNESS_NAMES[i]);
1039            sb.append(" ");
1040            formatTimeMs(sb, time/1000);
1041            sb.append("(");
1042            sb.append(formatRatioLocked(time, screenOnTime));
1043            sb.append(")");
1044        }
1045        if (!didOne) sb.append("No activity");
1046        pw.println(sb.toString());
1047
1048        // Calculate total network and wakelock times across all uids.
1049        long rxTotal = 0;
1050        long txTotal = 0;
1051        long fullWakeLockTimeTotalMicros = 0;
1052        long partialWakeLockTimeTotalMicros = 0;
1053
1054        Map<String, ? extends BatteryStats.Timer> kernelWakelocks = getKernelWakelockStats();
1055        if (kernelWakelocks.size() > 0) {
1056            for (Map.Entry<String, ? extends BatteryStats.Timer> ent : kernelWakelocks.entrySet()) {
1057
1058                String linePrefix = ": ";
1059                sb.setLength(0);
1060                sb.append(prefix);
1061                sb.append("  Kernel Wake lock ");
1062                sb.append(ent.getKey());
1063                linePrefix = printWakeLock(sb, ent.getValue(), batteryRealtime, null, which,
1064                        linePrefix);
1065                if (!linePrefix.equals(": ")) {
1066                    sb.append(" realtime");
1067                } else {
1068                    sb.append(": (nothing executed)");
1069                }
1070                pw.println(sb.toString());
1071            }
1072        }
1073
1074        for (int iu = 0; iu < NU; iu++) {
1075            Uid u = uidStats.valueAt(iu);
1076            rxTotal += u.getTcpBytesReceived(which);
1077            txTotal += u.getTcpBytesSent(which);
1078
1079            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1080            if (wakelocks.size() > 0) {
1081                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1082                        : wakelocks.entrySet()) {
1083                    Uid.Wakelock wl = ent.getValue();
1084
1085                    Timer fullWakeTimer = wl.getWakeTime(WAKE_TYPE_FULL);
1086                    if (fullWakeTimer != null) {
1087                        fullWakeLockTimeTotalMicros += fullWakeTimer.getTotalTimeLocked(
1088                                batteryRealtime, which);
1089                    }
1090
1091                    Timer partialWakeTimer = wl.getWakeTime(WAKE_TYPE_PARTIAL);
1092                    if (partialWakeTimer != null) {
1093                        partialWakeLockTimeTotalMicros += partialWakeTimer.getTotalTimeLocked(
1094                                batteryRealtime, which);
1095                    }
1096                }
1097            }
1098        }
1099
1100        pw.print(prefix);
1101                pw.print("  Total received: "); pw.print(formatBytesLocked(rxTotal));
1102                pw.print(", Total sent: "); pw.println(formatBytesLocked(txTotal));
1103        sb.setLength(0);
1104        sb.append(prefix);
1105                sb.append("  Total full wakelock time: "); formatTimeMs(sb,
1106                        (fullWakeLockTimeTotalMicros + 500) / 1000);
1107                sb.append(", Total partial waklock time: "); formatTimeMs(sb,
1108                        (partialWakeLockTimeTotalMicros + 500) / 1000);
1109        pw.println(sb.toString());
1110
1111        sb.setLength(0);
1112        sb.append(prefix);
1113        sb.append("  Signal levels: ");
1114        didOne = false;
1115        for (int i=0; i<NUM_SIGNAL_STRENGTH_BINS; i++) {
1116            final long time = getPhoneSignalStrengthTime(i, batteryRealtime, which);
1117            if (time == 0) {
1118                continue;
1119            }
1120            if (didOne) sb.append(", ");
1121            didOne = true;
1122            sb.append(SIGNAL_STRENGTH_NAMES[i]);
1123            sb.append(" ");
1124            formatTimeMs(sb, time/1000);
1125            sb.append("(");
1126            sb.append(formatRatioLocked(time, whichBatteryRealtime));
1127            sb.append(") ");
1128            sb.append(getPhoneSignalStrengthCount(i, which));
1129            sb.append("x");
1130        }
1131        if (!didOne) sb.append("No activity");
1132        pw.println(sb.toString());
1133
1134        sb.setLength(0);
1135        sb.append(prefix);
1136        sb.append("  Radio types: ");
1137        didOne = false;
1138        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
1139            final long time = getPhoneDataConnectionTime(i, batteryRealtime, which);
1140            if (time == 0) {
1141                continue;
1142            }
1143            if (didOne) sb.append(", ");
1144            didOne = true;
1145            sb.append(DATA_CONNECTION_NAMES[i]);
1146            sb.append(" ");
1147            formatTimeMs(sb, time/1000);
1148            sb.append("(");
1149            sb.append(formatRatioLocked(time, whichBatteryRealtime));
1150            sb.append(") ");
1151            sb.append(getPhoneDataConnectionCount(i, which));
1152            sb.append("x");
1153        }
1154        if (!didOne) sb.append("No activity");
1155        pw.println(sb.toString());
1156
1157        sb.setLength(0);
1158        sb.append(prefix);
1159        sb.append("  Radio data uptime when unplugged: ");
1160        sb.append(getRadioDataUptime() / 1000);
1161        sb.append(" ms");
1162        pw.println(sb.toString());
1163
1164        sb.setLength(0);
1165        sb.append(prefix);
1166                sb.append("  Wifi on: "); formatTimeMs(sb, wifiOnTime / 1000);
1167                sb.append("("); sb.append(formatRatioLocked(wifiOnTime, whichBatteryRealtime));
1168                sb.append("), Wifi running: "); formatTimeMs(sb, wifiRunningTime / 1000);
1169                sb.append("("); sb.append(formatRatioLocked(wifiRunningTime, whichBatteryRealtime));
1170                sb.append("), Bluetooth on: "); formatTimeMs(sb, bluetoothOnTime / 1000);
1171                sb.append("("); sb.append(formatRatioLocked(bluetoothOnTime, whichBatteryRealtime));
1172                sb.append(")");
1173        pw.println(sb.toString());
1174
1175        pw.println(" ");
1176
1177        if (which == STATS_UNPLUGGED) {
1178            if (getIsOnBattery()) {
1179                pw.print(prefix); pw.println("  Device is currently unplugged");
1180                pw.print(prefix); pw.print("    Discharge cycle start level: ");
1181                        pw.println(getDischargeStartLevel());
1182                pw.print(prefix); pw.print("    Discharge cycle current level: ");
1183                        pw.println(getDischargeCurrentLevel());
1184            } else {
1185                pw.print(prefix); pw.println("  Device is currently plugged into power");
1186                pw.print(prefix); pw.print("    Last discharge cycle start level: ");
1187                        pw.println(getDischargeStartLevel());
1188                pw.print(prefix); pw.print("    Last discharge cycle end level: ");
1189                        pw.println(getDischargeCurrentLevel());
1190            }
1191            pw.println(" ");
1192        }
1193
1194
1195        for (int iu=0; iu<NU; iu++) {
1196            final int uid = uidStats.keyAt(iu);
1197            Uid u = uidStats.valueAt(iu);
1198            pw.println(prefix + "  #" + uid + ":");
1199            boolean uidActivity = false;
1200
1201            long tcpReceived = u.getTcpBytesReceived(which);
1202            long tcpSent = u.getTcpBytesSent(which);
1203            long fullWifiLockOnTime = u.getFullWifiLockTime(batteryRealtime, which);
1204            long scanWifiLockOnTime = u.getScanWifiLockTime(batteryRealtime, which);
1205            long wifiTurnedOnTime = u.getWifiTurnedOnTime(batteryRealtime, which);
1206
1207            if (tcpReceived != 0 || tcpSent != 0) {
1208                pw.print(prefix); pw.print("    Network: ");
1209                        pw.print(formatBytesLocked(tcpReceived)); pw.print(" received, ");
1210                        pw.print(formatBytesLocked(tcpSent)); pw.println(" sent");
1211            }
1212
1213            if (u.hasUserActivity()) {
1214                boolean hasData = false;
1215                for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
1216                    int val = u.getUserActivityCount(i, which);
1217                    if (val != 0) {
1218                        if (!hasData) {
1219                            sb.setLength(0);
1220                            sb.append("    User activity: ");
1221                            hasData = true;
1222                        } else {
1223                            sb.append(", ");
1224                        }
1225                        sb.append(val);
1226                        sb.append(" ");
1227                        sb.append(Uid.USER_ACTIVITY_TYPES[i]);
1228                    }
1229                }
1230                if (hasData) {
1231                    pw.println(sb.toString());
1232                }
1233            }
1234
1235            if (fullWifiLockOnTime != 0 || scanWifiLockOnTime != 0
1236                    || wifiTurnedOnTime != 0) {
1237                sb.setLength(0);
1238                sb.append(prefix); sb.append("    Turned Wifi On: ");
1239                        formatTimeMs(sb, wifiTurnedOnTime / 1000);
1240                        sb.append("("); sb.append(formatRatioLocked(wifiTurnedOnTime,
1241                                whichBatteryRealtime)); sb.append(")\n");
1242                sb.append(prefix); sb.append("    Full Wifi Lock: ");
1243                        formatTimeMs(sb, fullWifiLockOnTime / 1000);
1244                        sb.append("("); sb.append(formatRatioLocked(fullWifiLockOnTime,
1245                                whichBatteryRealtime)); sb.append(")\n");
1246                sb.append(prefix); sb.append("    Scan Wifi Lock: ");
1247                        formatTimeMs(sb, scanWifiLockOnTime / 1000);
1248                        sb.append("("); sb.append(formatRatioLocked(scanWifiLockOnTime,
1249                                whichBatteryRealtime)); sb.append(")");
1250                pw.println(sb.toString());
1251            }
1252
1253            Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats();
1254            if (wakelocks.size() > 0) {
1255                for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent
1256                    : wakelocks.entrySet()) {
1257                    Uid.Wakelock wl = ent.getValue();
1258                    String linePrefix = ": ";
1259                    sb.setLength(0);
1260                    sb.append(prefix);
1261                    sb.append("    Wake lock ");
1262                    sb.append(ent.getKey());
1263                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_FULL), batteryRealtime,
1264                            "full", which, linePrefix);
1265                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), batteryRealtime,
1266                            "partial", which, linePrefix);
1267                    linePrefix = printWakeLock(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), batteryRealtime,
1268                            "window", which, linePrefix);
1269                    if (!linePrefix.equals(": ")) {
1270                        sb.append(" realtime");
1271                    } else {
1272                        sb.append(": (nothing executed)");
1273                    }
1274                    pw.println(sb.toString());
1275                    uidActivity = true;
1276                }
1277            }
1278
1279            Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats();
1280            if (sensors.size() > 0) {
1281                for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent
1282                    : sensors.entrySet()) {
1283                    Uid.Sensor se = ent.getValue();
1284                    int sensorNumber = ent.getKey();
1285                    sb.setLength(0);
1286                    sb.append(prefix);
1287                    sb.append("    Sensor ");
1288                    int handle = se.getHandle();
1289                    if (handle == Uid.Sensor.GPS) {
1290                        sb.append("GPS");
1291                    } else {
1292                        sb.append(handle);
1293                    }
1294                    sb.append(": ");
1295
1296                    Timer timer = se.getSensorTime();
1297                    if (timer != null) {
1298                        // Convert from microseconds to milliseconds with rounding
1299                        long totalTime = (timer.getTotalTimeLocked(
1300                                batteryRealtime, which) + 500) / 1000;
1301                        int count = timer.getCountLocked(which);
1302                        //timer.logState();
1303                        if (totalTime != 0) {
1304                            formatTimeMs(sb, totalTime);
1305                            sb.append("realtime (");
1306                            sb.append(count);
1307                            sb.append(" times)");
1308                        } else {
1309                            sb.append("(not used)");
1310                        }
1311                    } else {
1312                        sb.append("(not used)");
1313                    }
1314
1315                    pw.println(sb.toString());
1316                    uidActivity = true;
1317                }
1318            }
1319
1320            Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats();
1321            if (processStats.size() > 0) {
1322                for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent
1323                    : processStats.entrySet()) {
1324                    Uid.Proc ps = ent.getValue();
1325                    long userTime;
1326                    long systemTime;
1327                    int starts;
1328
1329                    userTime = ps.getUserTime(which);
1330                    systemTime = ps.getSystemTime(which);
1331                    starts = ps.getStarts(which);
1332
1333                    if (userTime != 0 || systemTime != 0 || starts != 0) {
1334                        sb.setLength(0);
1335                        sb.append(prefix); sb.append("    Proc ");
1336                                sb.append(ent.getKey()); sb.append(":\n");
1337                        sb.append(prefix); sb.append("      CPU: ");
1338                                formatTime(sb, userTime); sb.append("usr + ");
1339                                formatTime(sb, systemTime); sb.append("krn\n");
1340                        sb.append(prefix); sb.append("      "); sb.append(starts);
1341                                sb.append(" proc starts");
1342                        pw.println(sb.toString());
1343                        uidActivity = true;
1344                    }
1345                }
1346            }
1347
1348            Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats();
1349            if (packageStats.size() > 0) {
1350                for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent
1351                    : packageStats.entrySet()) {
1352                    pw.print(prefix); pw.print("    Apk "); pw.print(ent.getKey()); pw.println(":");
1353                    boolean apkActivity = false;
1354                    Uid.Pkg ps = ent.getValue();
1355                    int wakeups = ps.getWakeups(which);
1356                    if (wakeups != 0) {
1357                        pw.print(prefix); pw.print("      ");
1358                                pw.print(wakeups); pw.println(" wakeup alarms");
1359                        apkActivity = true;
1360                    }
1361                    Map<String, ? extends  Uid.Pkg.Serv> serviceStats = ps.getServiceStats();
1362                    if (serviceStats.size() > 0) {
1363                        for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent
1364                                : serviceStats.entrySet()) {
1365                            BatteryStats.Uid.Pkg.Serv ss = sent.getValue();
1366                            long startTime = ss.getStartTime(batteryUptime, which);
1367                            int starts = ss.getStarts(which);
1368                            int launches = ss.getLaunches(which);
1369                            if (startTime != 0 || starts != 0 || launches != 0) {
1370                                sb.setLength(0);
1371                                sb.append(prefix); sb.append("      Service ");
1372                                        sb.append(sent.getKey()); sb.append(":\n");
1373                                sb.append(prefix); sb.append("        Created for: ");
1374                                        formatTimeMs(sb, startTime / 1000);
1375                                        sb.append(" uptime\n");
1376                                sb.append(prefix); sb.append("        Starts: ");
1377                                        sb.append(starts);
1378                                        sb.append(", launches: "); sb.append(launches);
1379                                pw.println(sb.toString());
1380                                apkActivity = true;
1381                            }
1382                        }
1383                    }
1384                    if (!apkActivity) {
1385                        pw.print(prefix); pw.println("      (nothing executed)");
1386                    }
1387                    uidActivity = true;
1388                }
1389            }
1390            if (!uidActivity) {
1391                pw.print(prefix); pw.println("    (nothing executed)");
1392            }
1393        }
1394    }
1395
1396    /**
1397     * Dumps a human-readable summary of the battery statistics to the given PrintWriter.
1398     *
1399     * @param pw a Printer to receive the dump output.
1400     */
1401    @SuppressWarnings("unused")
1402    public void dumpLocked(PrintWriter pw) {
1403        pw.println("Total Statistics (Current and Historic):");
1404        pw.println("  System starts: " + getStartCount()
1405                + ", currently on battery: " + getIsOnBattery());
1406        dumpLocked(pw, "", STATS_TOTAL);
1407        pw.println("");
1408        pw.println("Last Run Statistics (Previous run of system):");
1409        dumpLocked(pw, "", STATS_LAST);
1410        pw.println("");
1411        pw.println("Current Battery Statistics (Currently running system):");
1412        dumpLocked(pw, "", STATS_CURRENT);
1413        pw.println("");
1414        pw.println("Unplugged Statistics (Since last unplugged from power):");
1415        dumpLocked(pw, "", STATS_UNPLUGGED);
1416    }
1417
1418    @SuppressWarnings("unused")
1419    public void dumpCheckinLocked(PrintWriter pw, String[] args) {
1420        boolean isUnpluggedOnly = false;
1421
1422        for (String arg : args) {
1423            if ("-u".equals(arg)) {
1424                if (LOCAL_LOGV) Log.v("BatteryStats", "Dumping unplugged data");
1425                isUnpluggedOnly = true;
1426            }
1427        }
1428
1429        if (isUnpluggedOnly) {
1430            dumpCheckinLocked(pw, STATS_UNPLUGGED);
1431        }
1432        else {
1433            dumpCheckinLocked(pw, STATS_TOTAL);
1434            dumpCheckinLocked(pw, STATS_LAST);
1435            dumpCheckinLocked(pw, STATS_UNPLUGGED);
1436            dumpCheckinLocked(pw, STATS_CURRENT);
1437        }
1438    }
1439
1440}
1441