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