BatteryService.java revision a82842f98d64897e92e1012404863f940bd03d26
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.PackageManager;
27import android.os.BatteryManager;
28import android.os.Binder;
29import android.os.Debug;
30import android.os.IBinder;
31import android.os.RemoteException;
32import android.os.ServiceManager;
33import android.os.SystemClock;
34import android.os.UEventObserver;
35import android.provider.Checkin;
36import android.provider.Settings;
37import android.util.EventLog;
38import android.util.Log;
39
40import java.io.File;
41import java.io.FileDescriptor;
42import java.io.FileInputStream;
43import java.io.FileOutputStream;
44import java.io.IOException;
45import java.io.PrintWriter;
46
47
48
49/**
50 * <p>BatteryService monitors the charging status, and charge level of the device
51 * battery.  When these values change this service broadcasts the new values
52 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
53 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
54 * BATTERY_CHANGED} action.</p>
55 * <p>The new values are stored in the Intent data and can be retrieved by
56 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
57 * following keys:</p>
58 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
59 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
60 * <p>&quot;status&quot; - String, the current charging status.<br />
61 * <p>&quot;health&quot; - String, the current battery health.<br />
62 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
63 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
64 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
65 * into an AC power adapter; 2 if plugged in via USB.</p>
66 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
67 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
68 * a degree Centigrade</p>
69 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
70 */
71class BatteryService extends Binder {
72    private static final String TAG = BatteryService.class.getSimpleName();
73
74    private static final boolean LOCAL_LOGV = false;
75
76    static final int LOG_BATTERY_LEVEL = 2722;
77    static final int LOG_BATTERY_STATUS = 2723;
78    static final int LOG_BATTERY_DISCHARGE_STATUS = 2730;
79
80    static final int BATTERY_SCALE = 100;    // battery capacity is a percentage
81
82    // Used locally for determining when to make a last ditch effort to log
83    // discharge stats before the device dies.
84    private static final int CRITICAL_BATTERY_LEVEL = 4;
85
86    private static final int DUMP_MAX_LENGTH = 24 * 1024;
87    private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" };
88    private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo";
89
90    private static final String DUMPSYS_DATA_PATH = "/data/system/";
91
92    // This should probably be exposed in the API, though it's not critical
93    private static final int BATTERY_PLUGGED_NONE = 0;
94
95    private static final int BATTERY_LEVEL_WARNING = 15;
96
97    private final Context mContext;
98    private final IBatteryStats mBatteryStats;
99
100    private boolean mAcOnline;
101    private boolean mUsbOnline;
102    private int mBatteryStatus;
103    private int mBatteryHealth;
104    private boolean mBatteryPresent;
105    private int mBatteryLevel;
106    private int mBatteryVoltage;
107    private int mBatteryTemperature;
108    private String mBatteryTechnology;
109    private boolean mBatteryLevelCritical;
110
111    private int mLastBatteryStatus;
112    private int mLastBatteryHealth;
113    private boolean mLastBatteryPresent;
114    private int mLastBatteryLevel;
115    private int mLastBatteryVoltage;
116    private int mLastBatteryTemperature;
117    private boolean mLastBatteryLevelCritical;
118
119    private int mPlugType;
120    private int mLastPlugType = -1; // Extra state so we can detect first run
121
122    private long mDischargeStartTime;
123    private int mDischargeStartLevel;
124
125
126    public BatteryService(Context context) {
127        mContext = context;
128        mBatteryStats = BatteryStatsService.getService();
129
130        mUEventObserver.startObserving("SUBSYSTEM=power_supply");
131
132        // set initial status
133        update();
134    }
135
136    final boolean isPowered() {
137        // assume we are powered if battery state is unknown so the "stay on while plugged in" option will work.
138        return (mAcOnline || mUsbOnline || mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN);
139    }
140
141    final boolean isPowered(int plugTypeSet) {
142        // assume we are powered if battery state is unknown so
143        // the "stay on while plugged in" option will work.
144        if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
145            return true;
146        }
147        if (plugTypeSet == 0) {
148            return false;
149        }
150        int plugTypeBit = 0;
151        if (mAcOnline) {
152            plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC;
153        }
154        if (mUsbOnline) {
155            plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB;
156        }
157        return (plugTypeSet & plugTypeBit) != 0;
158    }
159
160    final int getPlugType() {
161        return mPlugType;
162    }
163
164    private UEventObserver mUEventObserver = new UEventObserver() {
165        @Override
166        public void onUEvent(UEventObserver.UEvent event) {
167            update();
168        }
169    };
170
171    // returns battery level as a percentage
172    final int getBatteryLevel() {
173        return mBatteryLevel;
174    }
175
176    private native void native_update();
177
178    private synchronized final void update() {
179        native_update();
180
181        boolean logOutlier = false;
182        long dischargeDuration = 0;
183
184        mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL;
185        if (mAcOnline) {
186            mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
187        } else if (mUsbOnline) {
188            mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
189        } else {
190            mPlugType = BATTERY_PLUGGED_NONE;
191        }
192        if (mBatteryStatus != mLastBatteryStatus ||
193                mBatteryHealth != mLastBatteryHealth ||
194                mBatteryPresent != mLastBatteryPresent ||
195                mBatteryLevel != mLastBatteryLevel ||
196                mPlugType != mLastPlugType ||
197                mBatteryVoltage != mLastBatteryVoltage ||
198                mBatteryTemperature != mLastBatteryTemperature) {
199
200            if (mPlugType != mLastPlugType) {
201                if (mLastPlugType == BATTERY_PLUGGED_NONE) {
202                    // discharging -> charging
203
204                    // There's no value in this data unless we've discharged at least once and the
205                    // battery level has changed; so don't log until it does.
206                    if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
207                        dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
208                        logOutlier = true;
209                        EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration,
210                                mDischargeStartLevel, mBatteryLevel);
211                        // make sure we see a discharge event before logging again
212                        mDischargeStartTime = 0;
213                    }
214                } else if (mPlugType == BATTERY_PLUGGED_NONE) {
215                    // charging -> discharging or we just powered up
216                    mDischargeStartTime = SystemClock.elapsedRealtime();
217                    mDischargeStartLevel = mBatteryLevel;
218                }
219            }
220            if (mBatteryStatus != mLastBatteryStatus ||
221                    mBatteryHealth != mLastBatteryHealth ||
222                    mBatteryPresent != mLastBatteryPresent ||
223                    mPlugType != mLastPlugType) {
224                EventLog.writeEvent(LOG_BATTERY_STATUS,
225                        mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
226                        mPlugType, mBatteryTechnology);
227            }
228            if (mBatteryLevel != mLastBatteryLevel ||
229                    mBatteryVoltage != mLastBatteryVoltage ||
230                    mBatteryTemperature != mLastBatteryTemperature) {
231                EventLog.writeEvent(LOG_BATTERY_LEVEL,
232                        mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
233            }
234            if (mBatteryLevel != mLastBatteryLevel && mPlugType == BATTERY_PLUGGED_NONE) {
235                // If the battery level has changed and we are on battery, update the current level.
236                // This is used for discharge cycle tracking so this shouldn't be updated while the
237                // battery is charging.
238                try {
239                    mBatteryStats.recordCurrentLevel(mBatteryLevel);
240                } catch (RemoteException e) {
241                    // Should never happen.
242                }
243            }
244            if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
245                    mPlugType == BATTERY_PLUGGED_NONE) {
246                // We want to make sure we log discharge cycle outliers
247                // if the battery is about to die.
248                dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
249                logOutlier = true;
250            }
251
252            // Separate broadcast is sent for power connected / not connected
253            // since the standard intent will not wake any applications and some
254            // applications may want to have smart behavior based on this.
255            if (mPlugType != 0 && mLastPlugType == 0) {
256                Intent intent = new Intent(Intent.ACTION_POWER_CONNECTED);
257                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
258                mContext.sendBroadcast(intent);
259            }
260            else if (mPlugType == 0 && mLastPlugType != 0) {
261                Intent intent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
262                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
263                mContext.sendBroadcast(intent);
264            }
265
266            final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
267            final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
268
269            /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
270             * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
271             * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
272             */
273            final boolean sendBatteryLow = !plugged
274                && mBatteryLevel < BATTERY_LEVEL_WARNING
275                && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
276
277            mLastBatteryStatus = mBatteryStatus;
278            mLastBatteryHealth = mBatteryHealth;
279            mLastBatteryPresent = mBatteryPresent;
280            mLastBatteryLevel = mBatteryLevel;
281            mLastPlugType = mPlugType;
282            mLastBatteryVoltage = mBatteryVoltage;
283            mLastBatteryTemperature = mBatteryTemperature;
284            mLastBatteryLevelCritical = mBatteryLevelCritical;
285
286            sendIntent();
287            if (sendBatteryLow) {
288                mContext.sendBroadcast(new Intent(Intent.ACTION_BATTERY_LOW));
289            }
290
291            // This needs to be done after sendIntent() so that we get the lastest battery stats.
292            if (logOutlier && dischargeDuration != 0) {
293                logOutlier(dischargeDuration);
294            }
295        }
296    }
297
298    private final void sendIntent() {
299        //  Pack up the values and broadcast them to everyone
300        Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
301        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
302        try {
303            mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel);
304        } catch (RemoteException e) {
305            // Should never happen.
306        }
307
308        int icon = getIcon(mBatteryLevel);
309
310        intent.putExtra("status", mBatteryStatus);
311        intent.putExtra("health", mBatteryHealth);
312        intent.putExtra("present", mBatteryPresent);
313        intent.putExtra("level", mBatteryLevel);
314        intent.putExtra("scale", BATTERY_SCALE);
315        intent.putExtra("icon-small", icon);
316        intent.putExtra("plugged", mPlugType);
317        intent.putExtra("voltage", mBatteryVoltage);
318        intent.putExtra("temperature", mBatteryTemperature);
319        intent.putExtra("technology", mBatteryTechnology);
320
321        if (false) {
322            Log.d(TAG, "updateBattery level:" + mBatteryLevel +
323                    " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
324                    " health:" + mBatteryHealth +  " present:" + mBatteryPresent +
325                    " voltage: " + mBatteryVoltage +
326                    " temperature: " + mBatteryTemperature +
327                    " technology: " + mBatteryTechnology +
328                    " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
329                    " icon:" + icon );
330        }
331
332        ActivityManagerNative.broadcastStickyIntent(intent, null);
333    }
334
335    private final void logBatteryStats() {
336
337        IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
338        if (batteryInfoService != null) {
339            byte[] buffer = new byte[DUMP_MAX_LENGTH];
340            File dumpFile = null;
341            FileOutputStream dumpStream = null;
342            try {
343                // dump the service to a file
344                dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
345                dumpStream = new FileOutputStream(dumpFile);
346                batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
347                dumpStream.getFD().sync();
348
349                // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
350                // and insert into events table.
351                int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
352                FileInputStream fileInputStream = new FileInputStream(dumpFile);
353                int nread = fileInputStream.read(buffer, 0, length);
354                if (nread > 0) {
355                    Checkin.logEvent(mContext.getContentResolver(),
356                            Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
357                            new String(buffer, 0, nread));
358                    if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
359                            batteryInfoService + "to log");
360                    if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
361                }
362            } catch (RemoteException e) {
363                Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
364                        "':" + e);
365            } catch (IOException e) {
366                Log.e(TAG, "failed to write dumpsys file: " +  e);
367            } finally {
368                // make sure we clean up
369                if (dumpStream != null) {
370                    try {
371                        dumpStream.close();
372                    } catch (IOException e) {
373                        Log.e(TAG, "failed to close dumpsys output stream");
374                    }
375                }
376                if (dumpFile != null && !dumpFile.delete()) {
377                    Log.e(TAG, "failed to delete temporary dumpsys file: "
378                            + dumpFile.getAbsolutePath());
379                }
380            }
381        }
382    }
383
384    private final void logOutlier(long duration) {
385        ContentResolver cr = mContext.getContentResolver();
386        String dischargeThresholdString = Settings.Gservices.getString(cr,
387                Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
388        String durationThresholdString = Settings.Gservices.getString(cr,
389                Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
390
391        if (dischargeThresholdString != null && durationThresholdString != null) {
392            try {
393                long durationThreshold = Long.parseLong(durationThresholdString);
394                int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
395                if (duration <= durationThreshold &&
396                        mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
397                    // If the discharge cycle is bad enough we want to know about it.
398                    logBatteryStats();
399                }
400                if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
401                        " discharge threshold: " + dischargeThreshold);
402                if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
403                        (mDischargeStartLevel - mBatteryLevel));
404            } catch (NumberFormatException e) {
405                Log.e(TAG, "Invalid DischargeThresholds GService string: " +
406                        durationThresholdString + " or " + dischargeThresholdString);
407                return;
408            }
409        }
410    }
411
412    private final int getIcon(int level) {
413        if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
414            return com.android.internal.R.drawable.stat_sys_battery_charge;
415        } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
416                mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
417                mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
418            return com.android.internal.R.drawable.stat_sys_battery;
419        } else {
420            return com.android.internal.R.drawable.stat_sys_battery_unknown;
421        }
422    }
423
424    @Override
425    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
426        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
427                != PackageManager.PERMISSION_GRANTED) {
428
429            pw.println("Permission Denial: can't dump Battery service from from pid="
430                    + Binder.getCallingPid()
431                    + ", uid=" + Binder.getCallingUid());
432            return;
433        }
434
435        synchronized (this) {
436            pw.println("Current Battery Service state:");
437            pw.println("  AC powered: " + mAcOnline);
438            pw.println("  USB powered: " + mUsbOnline);
439            pw.println("  status: " + mBatteryStatus);
440            pw.println("  health: " + mBatteryHealth);
441            pw.println("  present: " + mBatteryPresent);
442            pw.println("  level: " + mBatteryLevel);
443            pw.println("  scale: " + BATTERY_SCALE);
444            pw.println("  voltage:" + mBatteryVoltage);
445            pw.println("  temperature: " + mBatteryTemperature);
446            pw.println("  technology: " + mBatteryTechnology);
447        }
448    }
449}
450