BatteryService.java revision edd9316ca9b3b24d54e8a2468927da7e813098fc
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.RemoteException;
31import android.os.ServiceManager;
32import android.os.SystemClock;
33import android.os.UEventObserver;
34import android.provider.Checkin;
35import android.provider.Settings;
36import android.util.EventLog;
37import android.util.Log;
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 LOG_BATTERY_LEVEL = 2722;
75    static final int LOG_BATTERY_STATUS = 2723;
76    static final int LOG_BATTERY_DISCHARGE_STATUS = 2730;
77
78    static final int BATTERY_SCALE = 100;    // battery capacity is a percentage
79
80    // Used locally for determining when to make a last ditch effort to log
81    // discharge stats before the device dies.
82    private static final int CRITICAL_BATTERY_LEVEL = 4;
83
84    private static final int DUMP_MAX_LENGTH = 24 * 1024;
85    private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" };
86    private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo";
87
88    private static final String DUMPSYS_DATA_PATH = "/data/system/";
89
90    // This should probably be exposed in the API, though it's not critical
91    private static final int BATTERY_PLUGGED_NONE = 0;
92
93    private static final int BATTERY_LEVEL_CLOSE_WARNING = 20;
94    private static final int BATTERY_LEVEL_WARNING = 15;
95
96    private final Context mContext;
97    private final IBatteryStats mBatteryStats;
98
99    private boolean mAcOnline;
100    private boolean mUsbOnline;
101    private int mBatteryStatus;
102    private int mBatteryHealth;
103    private boolean mBatteryPresent;
104    private int mBatteryLevel;
105    private int mBatteryVoltage;
106    private int mBatteryTemperature;
107    private String mBatteryTechnology;
108    private boolean mBatteryLevelCritical;
109
110    private int mLastBatteryStatus;
111    private int mLastBatteryHealth;
112    private boolean mLastBatteryPresent;
113    private int mLastBatteryLevel;
114    private int mLastBatteryVoltage;
115    private int mLastBatteryTemperature;
116    private boolean mLastBatteryLevelCritical;
117
118    private int mPlugType;
119    private int mLastPlugType = -1; // Extra state so we can detect first run
120
121    private long mDischargeStartTime;
122    private int mDischargeStartLevel;
123
124    private boolean mSentLowBatteryBroadcast = false;
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    void systemReady() {
177        // check our power situation now that it is safe to display the shutdown dialog.
178        shutdownIfNoPower();
179    }
180
181    private final void shutdownIfNoPower() {
182        // shut down gracefully if our battery is critically low and we are not powered.
183        // wait until the system has booted before attempting to display the shutdown dialog.
184        if (mBatteryLevel == 0 && !isPowered() && ActivityManagerNative.isSystemReady()) {
185            Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
186            intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
187            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
188            mContext.startActivity(intent);
189        }
190    }
191
192    private native void native_update();
193
194    private synchronized final void update() {
195        native_update();
196
197        boolean logOutlier = false;
198        long dischargeDuration = 0;
199
200        shutdownIfNoPower();
201
202        mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL;
203        if (mAcOnline) {
204            mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
205        } else if (mUsbOnline) {
206            mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
207        } else {
208            mPlugType = BATTERY_PLUGGED_NONE;
209        }
210        if (mBatteryStatus != mLastBatteryStatus ||
211                mBatteryHealth != mLastBatteryHealth ||
212                mBatteryPresent != mLastBatteryPresent ||
213                mBatteryLevel != mLastBatteryLevel ||
214                mPlugType != mLastPlugType ||
215                mBatteryVoltage != mLastBatteryVoltage ||
216                mBatteryTemperature != mLastBatteryTemperature) {
217
218            if (mPlugType != mLastPlugType) {
219                if (mLastPlugType == BATTERY_PLUGGED_NONE) {
220                    // discharging -> charging
221
222                    // There's no value in this data unless we've discharged at least once and the
223                    // battery level has changed; so don't log until it does.
224                    if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
225                        dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
226                        logOutlier = true;
227                        EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration,
228                                mDischargeStartLevel, mBatteryLevel);
229                        // make sure we see a discharge event before logging again
230                        mDischargeStartTime = 0;
231                    }
232                } else if (mPlugType == BATTERY_PLUGGED_NONE) {
233                    // charging -> discharging or we just powered up
234                    mDischargeStartTime = SystemClock.elapsedRealtime();
235                    mDischargeStartLevel = mBatteryLevel;
236                }
237            }
238            if (mBatteryStatus != mLastBatteryStatus ||
239                    mBatteryHealth != mLastBatteryHealth ||
240                    mBatteryPresent != mLastBatteryPresent ||
241                    mPlugType != mLastPlugType) {
242                EventLog.writeEvent(LOG_BATTERY_STATUS,
243                        mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
244                        mPlugType, mBatteryTechnology);
245            }
246            if (mBatteryLevel != mLastBatteryLevel ||
247                    mBatteryVoltage != mLastBatteryVoltage ||
248                    mBatteryTemperature != mLastBatteryTemperature) {
249                EventLog.writeEvent(LOG_BATTERY_LEVEL,
250                        mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
251            }
252            if (mBatteryLevel != mLastBatteryLevel && mPlugType == BATTERY_PLUGGED_NONE) {
253                // If the battery level has changed and we are on battery, update the current level.
254                // This is used for discharge cycle tracking so this shouldn't be updated while the
255                // battery is charging.
256                try {
257                    mBatteryStats.recordCurrentLevel(mBatteryLevel);
258                } catch (RemoteException e) {
259                    // Should never happen.
260                }
261            }
262            if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
263                    mPlugType == BATTERY_PLUGGED_NONE) {
264                // We want to make sure we log discharge cycle outliers
265                // if the battery is about to die.
266                dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
267                logOutlier = true;
268            }
269
270            // Separate broadcast is sent for power connected / not connected
271            // since the standard intent will not wake any applications and some
272            // applications may want to have smart behavior based on this.
273            Intent statusIntent = new Intent();
274            statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
275            if (mPlugType != 0 && mLastPlugType == 0) {
276                statusIntent.setAction(Intent.ACTION_POWER_CONNECTED);
277                mContext.sendBroadcast(statusIntent);
278            }
279            else if (mPlugType == 0 && mLastPlugType != 0) {
280                statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED);
281                mContext.sendBroadcast(statusIntent);
282            }
283
284            final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
285            final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
286
287            /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
288             * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
289             * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
290             */
291            final boolean sendBatteryLow = !plugged
292                && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
293                && mBatteryLevel < BATTERY_LEVEL_WARNING
294                && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
295
296            mLastBatteryStatus = mBatteryStatus;
297            mLastBatteryHealth = mBatteryHealth;
298            mLastBatteryPresent = mBatteryPresent;
299            mLastBatteryLevel = mBatteryLevel;
300            mLastPlugType = mPlugType;
301            mLastBatteryVoltage = mBatteryVoltage;
302            mLastBatteryTemperature = mBatteryTemperature;
303            mLastBatteryLevelCritical = mBatteryLevelCritical;
304
305            sendIntent();
306            if (sendBatteryLow) {
307                mSentLowBatteryBroadcast = true;
308                statusIntent.setAction(Intent.ACTION_BATTERY_LOW);
309                mContext.sendBroadcast(statusIntent);
310            } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= BATTERY_LEVEL_CLOSE_WARNING) {
311                mSentLowBatteryBroadcast = false;
312                statusIntent.setAction(Intent.ACTION_BATTERY_OKAY);
313                mContext.sendBroadcast(statusIntent);
314            }
315
316            // This needs to be done after sendIntent() so that we get the lastest battery stats.
317            if (logOutlier && dischargeDuration != 0) {
318                logOutlier(dischargeDuration);
319            }
320        }
321    }
322
323    private final void sendIntent() {
324        //  Pack up the values and broadcast them to everyone
325        Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
326        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
327        try {
328            mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel);
329        } catch (RemoteException e) {
330            // Should never happen.
331        }
332
333        int icon = getIcon(mBatteryLevel);
334
335        intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus);
336        intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth);
337        intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent);
338        intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel);
339        intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
340        intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
341        intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
342        intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryVoltage);
343        intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature);
344        intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology);
345
346        if (false) {
347            Log.d(TAG, "updateBattery level:" + mBatteryLevel +
348                    " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
349                    " health:" + mBatteryHealth +  " present:" + mBatteryPresent +
350                    " voltage: " + mBatteryVoltage +
351                    " temperature: " + mBatteryTemperature +
352                    " technology: " + mBatteryTechnology +
353                    " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
354                    " icon:" + icon );
355        }
356
357        ActivityManagerNative.broadcastStickyIntent(intent, null);
358    }
359
360    private final void logBatteryStats() {
361
362        IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
363        if (batteryInfoService != null) {
364            byte[] buffer = new byte[DUMP_MAX_LENGTH];
365            File dumpFile = null;
366            FileOutputStream dumpStream = null;
367            try {
368                // dump the service to a file
369                dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
370                dumpStream = new FileOutputStream(dumpFile);
371                batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
372                dumpStream.getFD().sync();
373
374                // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
375                // and insert into events table.
376                int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
377                FileInputStream fileInputStream = new FileInputStream(dumpFile);
378                int nread = fileInputStream.read(buffer, 0, length);
379                if (nread > 0) {
380                    Checkin.logEvent(mContext.getContentResolver(),
381                            Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
382                            new String(buffer, 0, nread));
383                    if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
384                            batteryInfoService + "to log");
385                    if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
386                }
387            } catch (RemoteException e) {
388                Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
389                        "':" + e);
390            } catch (IOException e) {
391                Log.e(TAG, "failed to write dumpsys file: " +  e);
392            } finally {
393                // make sure we clean up
394                if (dumpStream != null) {
395                    try {
396                        dumpStream.close();
397                    } catch (IOException e) {
398                        Log.e(TAG, "failed to close dumpsys output stream");
399                    }
400                }
401                if (dumpFile != null && !dumpFile.delete()) {
402                    Log.e(TAG, "failed to delete temporary dumpsys file: "
403                            + dumpFile.getAbsolutePath());
404                }
405            }
406        }
407    }
408
409    private final void logOutlier(long duration) {
410        ContentResolver cr = mContext.getContentResolver();
411        String dischargeThresholdString = Settings.Gservices.getString(cr,
412                Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
413        String durationThresholdString = Settings.Gservices.getString(cr,
414                Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
415
416        if (dischargeThresholdString != null && durationThresholdString != null) {
417            try {
418                long durationThreshold = Long.parseLong(durationThresholdString);
419                int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
420                if (duration <= durationThreshold &&
421                        mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
422                    // If the discharge cycle is bad enough we want to know about it.
423                    logBatteryStats();
424                }
425                if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
426                        " discharge threshold: " + dischargeThreshold);
427                if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
428                        (mDischargeStartLevel - mBatteryLevel));
429            } catch (NumberFormatException e) {
430                Log.e(TAG, "Invalid DischargeThresholds GService string: " +
431                        durationThresholdString + " or " + dischargeThresholdString);
432                return;
433            }
434        }
435    }
436
437    private final int getIcon(int level) {
438        if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
439            return com.android.internal.R.drawable.stat_sys_battery_charge;
440        } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
441                mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
442                mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
443            return com.android.internal.R.drawable.stat_sys_battery;
444        } else {
445            return com.android.internal.R.drawable.stat_sys_battery_unknown;
446        }
447    }
448
449    @Override
450    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
451        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
452                != PackageManager.PERMISSION_GRANTED) {
453
454            pw.println("Permission Denial: can't dump Battery service from from pid="
455                    + Binder.getCallingPid()
456                    + ", uid=" + Binder.getCallingUid());
457            return;
458        }
459
460        synchronized (this) {
461            pw.println("Current Battery Service state:");
462            pw.println("  AC powered: " + mAcOnline);
463            pw.println("  USB powered: " + mUsbOnline);
464            pw.println("  status: " + mBatteryStatus);
465            pw.println("  health: " + mBatteryHealth);
466            pw.println("  present: " + mBatteryPresent);
467            pw.println("  level: " + mBatteryLevel);
468            pw.println("  scale: " + BATTERY_SCALE);
469            pw.println("  voltage:" + mBatteryVoltage);
470            pw.println("  temperature: " + mBatteryTemperature);
471            pw.println("  technology: " + mBatteryTechnology);
472        }
473    }
474}
475