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