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