blob: 26fee89aec85d2609d3dacb670b7153b86ef535a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
48/**
49 * <p>BatteryService monitors the charging status, and charge level of the device
50 * battery. When these values change this service broadcasts the new values
51 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
52 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
53 * BATTERY_CHANGED} action.</p>
54 * <p>The new values are stored in the Intent data and can be retrieved by
55 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
56 * following keys:</p>
57 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
58 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
59 * <p>&quot;status&quot; - String, the current charging status.<br />
60 * <p>&quot;health&quot; - String, the current battery health.<br />
61 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
62 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
63 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
64 * into an AC power adapter; 2 if plugged in via USB.</p>
65 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
66 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
67 * a degree Centigrade</p>
68 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
69 */
70class BatteryService extends Binder {
71 private static final String TAG = BatteryService.class.getSimpleName();
72
73 private static final boolean LOCAL_LOGV = false;
74
75 static final int LOG_BATTERY_LEVEL = 2722;
76 static final int LOG_BATTERY_STATUS = 2723;
77 static final int LOG_BATTERY_DISCHARGE_STATUS = 2730;
78
79 static final int BATTERY_SCALE = 100; // battery capacity is a percentage
80
81 // Used locally for determining when to make a last ditch effort to log
82 // discharge stats before the device dies.
83 private static final int CRITICAL_BATTERY_LEVEL = 4;
84
85 private static final int DUMP_MAX_LENGTH = 24 * 1024;
Dianne Hackborn6447ca32009-04-07 19:50:08 -070086 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo";
88
89 private static final String DUMPSYS_DATA_PATH = "/data/system/";
90
91 // This should probably be exposed in the API, though it's not critical
92 private static final int BATTERY_PLUGGED_NONE = 0;
93
Dianne Hackborn8ec5b832009-07-01 21:19:35 -070094 private static final int BATTERY_LEVEL_CLOSE_WARNING = 20;
Mihai Predaa82842f2009-04-29 15:05:56 +020095 private static final int BATTERY_LEVEL_WARNING = 15;
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 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
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700125 private boolean mSentLowBatteryBroadcast = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126
127 public BatteryService(Context context) {
128 mContext = context;
129 mBatteryStats = BatteryStatsService.getService();
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 return (mAcOnline || mUsbOnline || mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN);
140 }
141
142 final boolean isPowered(int plugTypeSet) {
143 // assume we are powered if battery state is unknown so
144 // the "stay on while plugged in" option will work.
145 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
146 return true;
147 }
148 if (plugTypeSet == 0) {
149 return false;
150 }
151 int plugTypeBit = 0;
152 if (mAcOnline) {
153 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC;
154 }
155 if (mUsbOnline) {
156 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB;
157 }
158 return (plugTypeSet & plugTypeBit) != 0;
159 }
160
161 final int getPlugType() {
162 return mPlugType;
163 }
164
165 private UEventObserver mUEventObserver = new UEventObserver() {
166 @Override
167 public void onUEvent(UEventObserver.UEvent event) {
168 update();
169 }
170 };
171
172 // returns battery level as a percentage
173 final int getBatteryLevel() {
174 return mBatteryLevel;
175 }
176
Mike Lockwood07a500f2009-08-12 09:56:44 -0400177 void systemReady() {
178 // check our power situation now that it is safe to display the shutdown dialog.
179 shutdownIfNoPower();
180 }
181
182 private final void shutdownIfNoPower() {
183 // shut down gracefully if our battery is critically low and we are not powered.
184 // wait until the system has booted before attempting to display the shutdown dialog.
185 if (mBatteryLevel == 0 && !isPowered() && ActivityManagerNative.isSystemReady()) {
186 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
187 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
188 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
189 mContext.startActivity(intent);
190 }
191 }
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private native void native_update();
194
195 private synchronized final void update() {
196 native_update();
197
The Android Open Source Project10592532009-03-18 17:39:46 -0700198 boolean logOutlier = false;
199 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700200
Mike Lockwood07a500f2009-08-12 09:56:44 -0400201 shutdownIfNoPower();
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL;
204 if (mAcOnline) {
205 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
206 } else if (mUsbOnline) {
207 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
208 } else {
209 mPlugType = BATTERY_PLUGGED_NONE;
210 }
211 if (mBatteryStatus != mLastBatteryStatus ||
212 mBatteryHealth != mLastBatteryHealth ||
213 mBatteryPresent != mLastBatteryPresent ||
214 mBatteryLevel != mLastBatteryLevel ||
215 mPlugType != mLastPlugType ||
216 mBatteryVoltage != mLastBatteryVoltage ||
217 mBatteryTemperature != mLastBatteryTemperature) {
218
219 if (mPlugType != mLastPlugType) {
220 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
221 // discharging -> charging
222
223 // There's no value in this data unless we've discharged at least once and the
224 // battery level has changed; so don't log until it does.
225 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700226 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
227 logOutlier = true;
228 EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 mDischargeStartLevel, mBatteryLevel);
230 // make sure we see a discharge event before logging again
231 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 }
233 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
234 // charging -> discharging or we just powered up
235 mDischargeStartTime = SystemClock.elapsedRealtime();
236 mDischargeStartLevel = mBatteryLevel;
237 }
238 }
239 if (mBatteryStatus != mLastBatteryStatus ||
240 mBatteryHealth != mLastBatteryHealth ||
241 mBatteryPresent != mLastBatteryPresent ||
242 mPlugType != mLastPlugType) {
243 EventLog.writeEvent(LOG_BATTERY_STATUS,
244 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
245 mPlugType, mBatteryTechnology);
246 }
247 if (mBatteryLevel != mLastBatteryLevel ||
248 mBatteryVoltage != mLastBatteryVoltage ||
249 mBatteryTemperature != mLastBatteryTemperature) {
250 EventLog.writeEvent(LOG_BATTERY_LEVEL,
251 mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
252 }
Evan Millar633a1742009-04-02 16:36:33 -0700253 if (mBatteryLevel != mLastBatteryLevel && mPlugType == BATTERY_PLUGGED_NONE) {
254 // If the battery level has changed and we are on battery, update the current level.
255 // This is used for discharge cycle tracking so this shouldn't be updated while the
256 // battery is charging.
257 try {
258 mBatteryStats.recordCurrentLevel(mBatteryLevel);
259 } catch (RemoteException e) {
260 // Should never happen.
261 }
262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
264 mPlugType == BATTERY_PLUGGED_NONE) {
265 // We want to make sure we log discharge cycle outliers
266 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700267 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
268 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270
Christopher Tate06ba5542009-04-09 16:03:56 -0700271 // Separate broadcast is sent for power connected / not connected
272 // since the standard intent will not wake any applications and some
273 // applications may want to have smart behavior based on this.
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700274 Intent statusIntent = new Intent();
275 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Christopher Tate06ba5542009-04-09 16:03:56 -0700276 if (mPlugType != 0 && mLastPlugType == 0) {
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700277 statusIntent.setAction(Intent.ACTION_POWER_CONNECTED);
278 mContext.sendBroadcast(statusIntent);
Christopher Tate06ba5542009-04-09 16:03:56 -0700279 }
280 else if (mPlugType == 0 && mLastPlugType != 0) {
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700281 statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED);
282 mContext.sendBroadcast(statusIntent);
Christopher Tate06ba5542009-04-09 16:03:56 -0700283 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200284
285 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
286 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
287
288 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
289 * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
290 * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
291 */
292 final boolean sendBatteryLow = !plugged
Rebecca Schultz Zavin47ee3bc2009-05-14 22:34:04 -0700293 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
Mihai Predaa82842f2009-04-29 15:05:56 +0200294 && mBatteryLevel < BATTERY_LEVEL_WARNING
295 && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
Christopher Tate06ba5542009-04-09 16:03:56 -0700296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 mLastBatteryStatus = mBatteryStatus;
298 mLastBatteryHealth = mBatteryHealth;
299 mLastBatteryPresent = mBatteryPresent;
300 mLastBatteryLevel = mBatteryLevel;
301 mLastPlugType = mPlugType;
302 mLastBatteryVoltage = mBatteryVoltage;
303 mLastBatteryTemperature = mBatteryTemperature;
304 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mihai Predaa82842f2009-04-29 15:05:56 +0200305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 sendIntent();
Mihai Predaa82842f2009-04-29 15:05:56 +0200307 if (sendBatteryLow) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700308 mSentLowBatteryBroadcast = true;
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700309 statusIntent.setAction(Intent.ACTION_BATTERY_LOW);
310 mContext.sendBroadcast(statusIntent);
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700311 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= BATTERY_LEVEL_CLOSE_WARNING) {
312 mSentLowBatteryBroadcast = false;
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700313 statusIntent.setAction(Intent.ACTION_BATTERY_OKAY);
314 mContext.sendBroadcast(statusIntent);
Mihai Predaa82842f2009-04-29 15:05:56 +0200315 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700316
317 // This needs to be done after sendIntent() so that we get the lastest battery stats.
318 if (logOutlier && dischargeDuration != 0) {
319 logOutlier(dischargeDuration);
320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322 }
323
324 private final void sendIntent() {
325 // Pack up the values and broadcast them to everyone
326 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
327 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
328 try {
The Android Open Source Project10592532009-03-18 17:39:46 -0700329 mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 } catch (RemoteException e) {
331 // Should never happen.
332 }
333
334 int icon = getIcon(mBatteryLevel);
335
336 intent.putExtra("status", mBatteryStatus);
337 intent.putExtra("health", mBatteryHealth);
338 intent.putExtra("present", mBatteryPresent);
339 intent.putExtra("level", mBatteryLevel);
340 intent.putExtra("scale", BATTERY_SCALE);
341 intent.putExtra("icon-small", icon);
342 intent.putExtra("plugged", mPlugType);
343 intent.putExtra("voltage", mBatteryVoltage);
344 intent.putExtra("temperature", mBatteryTemperature);
345 intent.putExtra("technology", mBatteryTechnology);
346
347 if (false) {
348 Log.d(TAG, "updateBattery level:" + mBatteryLevel +
349 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
350 " health:" + mBatteryHealth + " present:" + mBatteryPresent +
351 " voltage: " + mBatteryVoltage +
352 " temperature: " + mBatteryTemperature +
353 " technology: " + mBatteryTechnology +
354 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
355 " icon:" + icon );
356 }
357
358 ActivityManagerNative.broadcastStickyIntent(intent, null);
359 }
360
361 private final void logBatteryStats() {
362
363 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
364 if (batteryInfoService != null) {
365 byte[] buffer = new byte[DUMP_MAX_LENGTH];
366 File dumpFile = null;
367 FileOutputStream dumpStream = null;
368 try {
369 // dump the service to a file
370 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
371 dumpStream = new FileOutputStream(dumpFile);
372 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
373 dumpStream.getFD().sync();
374
375 // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
376 // and insert into events table.
377 int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
378 FileInputStream fileInputStream = new FileInputStream(dumpFile);
379 int nread = fileInputStream.read(buffer, 0, length);
380 if (nread > 0) {
381 Checkin.logEvent(mContext.getContentResolver(),
382 Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
383 new String(buffer, 0, nread));
384 if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
385 batteryInfoService + "to log");
386 if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
387 }
388 } catch (RemoteException e) {
389 Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
390 "':" + e);
391 } catch (IOException e) {
392 Log.e(TAG, "failed to write dumpsys file: " + e);
393 } finally {
394 // make sure we clean up
395 if (dumpStream != null) {
396 try {
397 dumpStream.close();
398 } catch (IOException e) {
399 Log.e(TAG, "failed to close dumpsys output stream");
400 }
401 }
402 if (dumpFile != null && !dumpFile.delete()) {
403 Log.e(TAG, "failed to delete temporary dumpsys file: "
404 + dumpFile.getAbsolutePath());
405 }
406 }
407 }
408 }
409
410 private final void logOutlier(long duration) {
411 ContentResolver cr = mContext.getContentResolver();
412 String dischargeThresholdString = Settings.Gservices.getString(cr,
413 Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
414 String durationThresholdString = Settings.Gservices.getString(cr,
415 Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
416
417 if (dischargeThresholdString != null && durationThresholdString != null) {
418 try {
419 long durationThreshold = Long.parseLong(durationThresholdString);
420 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
421 if (duration <= durationThreshold &&
422 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
423 // If the discharge cycle is bad enough we want to know about it.
424 logBatteryStats();
425 }
426 if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
427 " discharge threshold: " + dischargeThreshold);
428 if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
429 (mDischargeStartLevel - mBatteryLevel));
430 } catch (NumberFormatException e) {
431 Log.e(TAG, "Invalid DischargeThresholds GService string: " +
432 durationThresholdString + " or " + dischargeThresholdString);
433 return;
434 }
435 }
436 }
437
438 private final int getIcon(int level) {
439 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
440 return com.android.internal.R.drawable.stat_sys_battery_charge;
441 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
442 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
443 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
444 return com.android.internal.R.drawable.stat_sys_battery;
445 } else {
446 return com.android.internal.R.drawable.stat_sys_battery_unknown;
447 }
448 }
449
450 @Override
451 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
452 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
453 != PackageManager.PERMISSION_GRANTED) {
454
455 pw.println("Permission Denial: can't dump Battery service from from pid="
456 + Binder.getCallingPid()
457 + ", uid=" + Binder.getCallingUid());
458 return;
459 }
460
461 synchronized (this) {
462 pw.println("Current Battery Service state:");
463 pw.println(" AC powered: " + mAcOnline);
464 pw.println(" USB powered: " + mUsbOnline);
465 pw.println(" status: " + mBatteryStatus);
466 pw.println(" health: " + mBatteryHealth);
467 pw.println(" present: " + mBatteryPresent);
468 pw.println(" level: " + mBatteryLevel);
469 pw.println(" scale: " + BATTERY_SCALE);
470 pw.println(" voltage:" + mBatteryVoltage);
471 pw.println(" temperature: " + mBatteryTemperature);
472 pw.println(" technology: " + mBatteryTechnology);
473 }
474 }
475}