blob: 596053d8091d9882e0957fe7bba8ad61b3b7d73d [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
47
48
49/**
50 * <p>BatteryService monitors the charging status, and charge level of the device
51 * battery. When these values change this service broadcasts the new values
52 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
53 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
54 * BATTERY_CHANGED} action.</p>
55 * <p>The new values are stored in the Intent data and can be retrieved by
56 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
57 * following keys:</p>
58 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
59 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
60 * <p>&quot;status&quot; - String, the current charging status.<br />
61 * <p>&quot;health&quot; - String, the current battery health.<br />
62 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
63 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
64 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
65 * into an AC power adapter; 2 if plugged in via USB.</p>
66 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
67 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
68 * a degree Centigrade</p>
69 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
70 */
71class BatteryService extends Binder {
72 private static final String TAG = BatteryService.class.getSimpleName();
73
74 private static final boolean LOCAL_LOGV = false;
75
76 static final int LOG_BATTERY_LEVEL = 2722;
77 static final int LOG_BATTERY_STATUS = 2723;
78 static final int LOG_BATTERY_DISCHARGE_STATUS = 2730;
79
80 static final int BATTERY_SCALE = 100; // battery capacity is a percentage
81
82 // Used locally for determining when to make a last ditch effort to log
83 // discharge stats before the device dies.
84 private static final int CRITICAL_BATTERY_LEVEL = 4;
85
86 private static final int DUMP_MAX_LENGTH = 24 * 1024;
Dianne Hackborn6447ca32009-04-07 19:50:08 -070087 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo";
89
90 private static final String DUMPSYS_DATA_PATH = "/data/system/";
91
92 // This should probably be exposed in the API, though it's not critical
93 private static final int BATTERY_PLUGGED_NONE = 0;
94
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
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 private native void native_update();
177
178 private synchronized final void update() {
179 native_update();
180
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 boolean logOutlier = false;
182 long dischargeDuration = 0;
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL;
185 if (mAcOnline) {
186 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
187 } else if (mUsbOnline) {
188 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
189 } else {
190 mPlugType = BATTERY_PLUGGED_NONE;
191 }
192 if (mBatteryStatus != mLastBatteryStatus ||
193 mBatteryHealth != mLastBatteryHealth ||
194 mBatteryPresent != mLastBatteryPresent ||
195 mBatteryLevel != mLastBatteryLevel ||
196 mPlugType != mLastPlugType ||
197 mBatteryVoltage != mLastBatteryVoltage ||
198 mBatteryTemperature != mLastBatteryTemperature) {
199
200 if (mPlugType != mLastPlugType) {
201 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
202 // discharging -> charging
203
204 // There's no value in this data unless we've discharged at least once and the
205 // battery level has changed; so don't log until it does.
206 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700207 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
208 logOutlier = true;
209 EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 mDischargeStartLevel, mBatteryLevel);
211 // make sure we see a discharge event before logging again
212 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
214 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
215 // charging -> discharging or we just powered up
216 mDischargeStartTime = SystemClock.elapsedRealtime();
217 mDischargeStartLevel = mBatteryLevel;
218 }
219 }
220 if (mBatteryStatus != mLastBatteryStatus ||
221 mBatteryHealth != mLastBatteryHealth ||
222 mBatteryPresent != mLastBatteryPresent ||
223 mPlugType != mLastPlugType) {
224 EventLog.writeEvent(LOG_BATTERY_STATUS,
225 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
226 mPlugType, mBatteryTechnology);
227 }
228 if (mBatteryLevel != mLastBatteryLevel ||
229 mBatteryVoltage != mLastBatteryVoltage ||
230 mBatteryTemperature != mLastBatteryTemperature) {
231 EventLog.writeEvent(LOG_BATTERY_LEVEL,
232 mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
233 }
Evan Millar633a1742009-04-02 16:36:33 -0700234 if (mBatteryLevel != mLastBatteryLevel && mPlugType == BATTERY_PLUGGED_NONE) {
235 // If the battery level has changed and we are on battery, update the current level.
236 // This is used for discharge cycle tracking so this shouldn't be updated while the
237 // battery is charging.
238 try {
239 mBatteryStats.recordCurrentLevel(mBatteryLevel);
240 } catch (RemoteException e) {
241 // Should never happen.
242 }
243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
245 mPlugType == BATTERY_PLUGGED_NONE) {
246 // We want to make sure we log discharge cycle outliers
247 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700248 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
249 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 }
251
Christopher Tate06ba5542009-04-09 16:03:56 -0700252 // Separate broadcast is sent for power connected / not connected
253 // since the standard intent will not wake any applications and some
254 // applications may want to have smart behavior based on this.
255 if (mPlugType != 0 && mLastPlugType == 0) {
256 Intent intent = new Intent(Intent.ACTION_POWER_CONNECTED);
257 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
258 mContext.sendBroadcast(intent);
259 }
260 else if (mPlugType == 0 && mLastPlugType != 0) {
261 Intent intent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
262 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
263 mContext.sendBroadcast(intent);
264 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200265
266 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
267 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
268
269 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
270 * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
271 * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
272 */
273 final boolean sendBatteryLow = !plugged
Rebecca Schultz Zavin47ee3bc2009-05-14 22:34:04 -0700274 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
Mihai Predaa82842f2009-04-29 15:05:56 +0200275 && mBatteryLevel < BATTERY_LEVEL_WARNING
276 && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
Christopher Tate06ba5542009-04-09 16:03:56 -0700277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 mLastBatteryStatus = mBatteryStatus;
279 mLastBatteryHealth = mBatteryHealth;
280 mLastBatteryPresent = mBatteryPresent;
281 mLastBatteryLevel = mBatteryLevel;
282 mLastPlugType = mPlugType;
283 mLastBatteryVoltage = mBatteryVoltage;
284 mLastBatteryTemperature = mBatteryTemperature;
285 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mihai Predaa82842f2009-04-29 15:05:56 +0200286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 sendIntent();
Mihai Predaa82842f2009-04-29 15:05:56 +0200288 if (sendBatteryLow) {
289 mContext.sendBroadcast(new Intent(Intent.ACTION_BATTERY_LOW));
290 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700291
292 // This needs to be done after sendIntent() so that we get the lastest battery stats.
293 if (logOutlier && dischargeDuration != 0) {
294 logOutlier(dischargeDuration);
295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 }
297 }
298
299 private final void sendIntent() {
300 // Pack up the values and broadcast them to everyone
301 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
302 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
303 try {
The Android Open Source Project10592532009-03-18 17:39:46 -0700304 mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 } catch (RemoteException e) {
306 // Should never happen.
307 }
308
309 int icon = getIcon(mBatteryLevel);
310
311 intent.putExtra("status", mBatteryStatus);
312 intent.putExtra("health", mBatteryHealth);
313 intent.putExtra("present", mBatteryPresent);
314 intent.putExtra("level", mBatteryLevel);
315 intent.putExtra("scale", BATTERY_SCALE);
316 intent.putExtra("icon-small", icon);
317 intent.putExtra("plugged", mPlugType);
318 intent.putExtra("voltage", mBatteryVoltage);
319 intent.putExtra("temperature", mBatteryTemperature);
320 intent.putExtra("technology", mBatteryTechnology);
321
322 if (false) {
323 Log.d(TAG, "updateBattery level:" + mBatteryLevel +
324 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
325 " health:" + mBatteryHealth + " present:" + mBatteryPresent +
326 " voltage: " + mBatteryVoltage +
327 " temperature: " + mBatteryTemperature +
328 " technology: " + mBatteryTechnology +
329 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
330 " icon:" + icon );
331 }
332
333 ActivityManagerNative.broadcastStickyIntent(intent, null);
334 }
335
336 private final void logBatteryStats() {
337
338 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
339 if (batteryInfoService != null) {
340 byte[] buffer = new byte[DUMP_MAX_LENGTH];
341 File dumpFile = null;
342 FileOutputStream dumpStream = null;
343 try {
344 // dump the service to a file
345 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
346 dumpStream = new FileOutputStream(dumpFile);
347 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
348 dumpStream.getFD().sync();
349
350 // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
351 // and insert into events table.
352 int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
353 FileInputStream fileInputStream = new FileInputStream(dumpFile);
354 int nread = fileInputStream.read(buffer, 0, length);
355 if (nread > 0) {
356 Checkin.logEvent(mContext.getContentResolver(),
357 Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
358 new String(buffer, 0, nread));
359 if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
360 batteryInfoService + "to log");
361 if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
362 }
363 } catch (RemoteException e) {
364 Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
365 "':" + e);
366 } catch (IOException e) {
367 Log.e(TAG, "failed to write dumpsys file: " + e);
368 } finally {
369 // make sure we clean up
370 if (dumpStream != null) {
371 try {
372 dumpStream.close();
373 } catch (IOException e) {
374 Log.e(TAG, "failed to close dumpsys output stream");
375 }
376 }
377 if (dumpFile != null && !dumpFile.delete()) {
378 Log.e(TAG, "failed to delete temporary dumpsys file: "
379 + dumpFile.getAbsolutePath());
380 }
381 }
382 }
383 }
384
385 private final void logOutlier(long duration) {
386 ContentResolver cr = mContext.getContentResolver();
387 String dischargeThresholdString = Settings.Gservices.getString(cr,
388 Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
389 String durationThresholdString = Settings.Gservices.getString(cr,
390 Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
391
392 if (dischargeThresholdString != null && durationThresholdString != null) {
393 try {
394 long durationThreshold = Long.parseLong(durationThresholdString);
395 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
396 if (duration <= durationThreshold &&
397 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
398 // If the discharge cycle is bad enough we want to know about it.
399 logBatteryStats();
400 }
401 if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
402 " discharge threshold: " + dischargeThreshold);
403 if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
404 (mDischargeStartLevel - mBatteryLevel));
405 } catch (NumberFormatException e) {
406 Log.e(TAG, "Invalid DischargeThresholds GService string: " +
407 durationThresholdString + " or " + dischargeThresholdString);
408 return;
409 }
410 }
411 }
412
413 private final int getIcon(int level) {
414 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
415 return com.android.internal.R.drawable.stat_sys_battery_charge;
416 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
417 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
418 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
419 return com.android.internal.R.drawable.stat_sys_battery;
420 } else {
421 return com.android.internal.R.drawable.stat_sys_battery_unknown;
422 }
423 }
424
425 @Override
426 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
427 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
428 != PackageManager.PERMISSION_GRANTED) {
429
430 pw.println("Permission Denial: can't dump Battery service from from pid="
431 + Binder.getCallingPid()
432 + ", uid=" + Binder.getCallingUid());
433 return;
434 }
435
436 synchronized (this) {
437 pw.println("Current Battery Service state:");
438 pw.println(" AC powered: " + mAcOnline);
439 pw.println(" USB powered: " + mUsbOnline);
440 pw.println(" status: " + mBatteryStatus);
441 pw.println(" health: " + mBatteryHealth);
442 pw.println(" present: " + mBatteryPresent);
443 pw.println(" level: " + mBatteryLevel);
444 pw.println(" scale: " + BATTERY_SCALE);
445 pw.println(" voltage:" + mBatteryVoltage);
446 pw.println(" temperature: " + mBatteryTemperature);
447 pw.println(" technology: " + mBatteryTechnology);
448 }
449 }
450}