blob: 53edf31a20395edca7ac270948f64c165a817f80 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
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;
Dianne Hackborn6447ca32009-04-07 19:50:08 -070085 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 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
Dianne Hackborn8ec5b832009-07-01 21:19:35 -070093 private static final int BATTERY_LEVEL_CLOSE_WARNING = 20;
Mihai Predaa82842f2009-04-29 15:05:56 +020094 private static final int BATTERY_LEVEL_WARNING = 15;
95
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 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
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700124 private boolean mSentLowBatteryBroadcast = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
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
Mike Lockwood07a500f2009-08-12 09:56:44 -0400176 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private native void native_update();
193
194 private synchronized final void update() {
195 native_update();
196
The Android Open Source Project10592532009-03-18 17:39:46 -0700197 boolean logOutlier = false;
198 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700199
Mike Lockwood07a500f2009-08-12 09:56:44 -0400200 shutdownIfNoPower();
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 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) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700225 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
226 logOutlier = true;
227 EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 mDischargeStartLevel, mBatteryLevel);
229 // make sure we see a discharge event before logging again
230 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 }
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 }
Evan Millar633a1742009-04-02 16:36:33 -0700252 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 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 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.
The Android Open Source Project10592532009-03-18 17:39:46 -0700266 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
267 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 }
269
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700270 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
271 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
272
273 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
274 * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
275 * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
276 */
277 final boolean sendBatteryLow = !plugged
278 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
279 && mBatteryLevel < BATTERY_LEVEL_WARNING
280 && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
281
282 sendIntent();
283
Christopher Tate06ba5542009-04-09 16:03:56 -0700284 // Separate broadcast is sent for power connected / not connected
285 // since the standard intent will not wake any applications and some
286 // applications may want to have smart behavior based on this.
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700287 Intent statusIntent = new Intent();
288 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Christopher Tate06ba5542009-04-09 16:03:56 -0700289 if (mPlugType != 0 && mLastPlugType == 0) {
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700290 statusIntent.setAction(Intent.ACTION_POWER_CONNECTED);
291 mContext.sendBroadcast(statusIntent);
Christopher Tate06ba5542009-04-09 16:03:56 -0700292 }
293 else if (mPlugType == 0 && mLastPlugType != 0) {
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700294 statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED);
295 mContext.sendBroadcast(statusIntent);
Christopher Tate06ba5542009-04-09 16:03:56 -0700296 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200297
Mihai Predaa82842f2009-04-29 15:05:56 +0200298 if (sendBatteryLow) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700299 mSentLowBatteryBroadcast = true;
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700300 statusIntent.setAction(Intent.ACTION_BATTERY_LOW);
301 mContext.sendBroadcast(statusIntent);
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700302 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= BATTERY_LEVEL_CLOSE_WARNING) {
303 mSentLowBatteryBroadcast = false;
Christopher Tate93dc9fe2009-07-16 13:25:49 -0700304 statusIntent.setAction(Intent.ACTION_BATTERY_OKAY);
305 mContext.sendBroadcast(statusIntent);
Mihai Predaa82842f2009-04-29 15:05:56 +0200306 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700307
308 // This needs to be done after sendIntent() so that we get the lastest battery stats.
309 if (logOutlier && dischargeDuration != 0) {
310 logOutlier(dischargeDuration);
311 }
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700312
313 mLastBatteryStatus = mBatteryStatus;
314 mLastBatteryHealth = mBatteryHealth;
315 mLastBatteryPresent = mBatteryPresent;
316 mLastBatteryLevel = mBatteryLevel;
317 mLastPlugType = mPlugType;
318 mLastBatteryVoltage = mBatteryVoltage;
319 mLastBatteryTemperature = mBatteryTemperature;
320 mLastBatteryLevelCritical = mBatteryLevelCritical;
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
Dianne Hackbornedd93162009-09-19 14:03:05 -0700336 intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus);
337 intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth);
338 intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent);
339 intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel);
340 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
341 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
342 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
343 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryVoltage);
344 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature);
345 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346
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}