blob: 5cdce5b3b63f48d7811863bc22cdac42973c523e [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
Dianne Hackborn8ec5b832009-07-01 21:19:35 -070095 private static final int BATTERY_LEVEL_CLOSE_WARNING = 20;
Mihai Predaa82842f2009-04-29 15:05:56 +020096 private static final int BATTERY_LEVEL_WARNING = 15;
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private final Context mContext;
99 private final IBatteryStats mBatteryStats;
100
101 private boolean mAcOnline;
102 private boolean mUsbOnline;
103 private int mBatteryStatus;
104 private int mBatteryHealth;
105 private boolean mBatteryPresent;
106 private int mBatteryLevel;
107 private int mBatteryVoltage;
108 private int mBatteryTemperature;
109 private String mBatteryTechnology;
110 private boolean mBatteryLevelCritical;
111
112 private int mLastBatteryStatus;
113 private int mLastBatteryHealth;
114 private boolean mLastBatteryPresent;
115 private int mLastBatteryLevel;
116 private int mLastBatteryVoltage;
117 private int mLastBatteryTemperature;
118 private boolean mLastBatteryLevelCritical;
119
120 private int mPlugType;
121 private int mLastPlugType = -1; // Extra state so we can detect first run
122
123 private long mDischargeStartTime;
124 private int mDischargeStartLevel;
125
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700126 private boolean mSentLowBatteryBroadcast = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
128 public BatteryService(Context context) {
129 mContext = context;
130 mBatteryStats = BatteryStatsService.getService();
131
132 mUEventObserver.startObserving("SUBSYSTEM=power_supply");
133
134 // set initial status
135 update();
136 }
137
138 final boolean isPowered() {
139 // assume we are powered if battery state is unknown so the "stay on while plugged in" option will work.
140 return (mAcOnline || mUsbOnline || mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN);
141 }
142
143 final boolean isPowered(int plugTypeSet) {
144 // assume we are powered if battery state is unknown so
145 // the "stay on while plugged in" option will work.
146 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
147 return true;
148 }
149 if (plugTypeSet == 0) {
150 return false;
151 }
152 int plugTypeBit = 0;
153 if (mAcOnline) {
154 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC;
155 }
156 if (mUsbOnline) {
157 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB;
158 }
159 return (plugTypeSet & plugTypeBit) != 0;
160 }
161
162 final int getPlugType() {
163 return mPlugType;
164 }
165
166 private UEventObserver mUEventObserver = new UEventObserver() {
167 @Override
168 public void onUEvent(UEventObserver.UEvent event) {
169 update();
170 }
171 };
172
173 // returns battery level as a percentage
174 final int getBatteryLevel() {
175 return mBatteryLevel;
176 }
177
178 private native void native_update();
179
180 private synchronized final void update() {
181 native_update();
182
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 boolean logOutlier = false;
184 long dischargeDuration = 0;
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL;
187 if (mAcOnline) {
188 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
189 } else if (mUsbOnline) {
190 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
191 } else {
192 mPlugType = BATTERY_PLUGGED_NONE;
193 }
194 if (mBatteryStatus != mLastBatteryStatus ||
195 mBatteryHealth != mLastBatteryHealth ||
196 mBatteryPresent != mLastBatteryPresent ||
197 mBatteryLevel != mLastBatteryLevel ||
198 mPlugType != mLastPlugType ||
199 mBatteryVoltage != mLastBatteryVoltage ||
200 mBatteryTemperature != mLastBatteryTemperature) {
201
202 if (mPlugType != mLastPlugType) {
203 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
204 // discharging -> charging
205
206 // There's no value in this data unless we've discharged at least once and the
207 // battery level has changed; so don't log until it does.
208 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700209 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
210 logOutlier = true;
211 EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, dischargeDuration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 mDischargeStartLevel, mBatteryLevel);
213 // make sure we see a discharge event before logging again
214 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 }
216 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
217 // charging -> discharging or we just powered up
218 mDischargeStartTime = SystemClock.elapsedRealtime();
219 mDischargeStartLevel = mBatteryLevel;
220 }
221 }
222 if (mBatteryStatus != mLastBatteryStatus ||
223 mBatteryHealth != mLastBatteryHealth ||
224 mBatteryPresent != mLastBatteryPresent ||
225 mPlugType != mLastPlugType) {
226 EventLog.writeEvent(LOG_BATTERY_STATUS,
227 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
228 mPlugType, mBatteryTechnology);
229 }
230 if (mBatteryLevel != mLastBatteryLevel ||
231 mBatteryVoltage != mLastBatteryVoltage ||
232 mBatteryTemperature != mLastBatteryTemperature) {
233 EventLog.writeEvent(LOG_BATTERY_LEVEL,
234 mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
235 }
Evan Millar633a1742009-04-02 16:36:33 -0700236 if (mBatteryLevel != mLastBatteryLevel && mPlugType == BATTERY_PLUGGED_NONE) {
237 // If the battery level has changed and we are on battery, update the current level.
238 // This is used for discharge cycle tracking so this shouldn't be updated while the
239 // battery is charging.
240 try {
241 mBatteryStats.recordCurrentLevel(mBatteryLevel);
242 } catch (RemoteException e) {
243 // Should never happen.
244 }
245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
247 mPlugType == BATTERY_PLUGGED_NONE) {
248 // We want to make sure we log discharge cycle outliers
249 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700250 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
251 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 }
253
Christopher Tate06ba5542009-04-09 16:03:56 -0700254 // Separate broadcast is sent for power connected / not connected
255 // since the standard intent will not wake any applications and some
256 // applications may want to have smart behavior based on this.
257 if (mPlugType != 0 && mLastPlugType == 0) {
258 Intent intent = new Intent(Intent.ACTION_POWER_CONNECTED);
259 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
260 mContext.sendBroadcast(intent);
261 }
262 else if (mPlugType == 0 && mLastPlugType != 0) {
263 Intent intent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
264 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
265 mContext.sendBroadcast(intent);
266 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200267
268 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
269 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
270
271 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
272 * - is just un-plugged (previously was plugged) and battery level is under WARNING, or
273 * - is not plugged and battery level crosses the WARNING boundary (becomes < 15).
274 */
275 final boolean sendBatteryLow = !plugged
Rebecca Schultz Zavin47ee3bc2009-05-14 22:34:04 -0700276 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
Mihai Predaa82842f2009-04-29 15:05:56 +0200277 && mBatteryLevel < BATTERY_LEVEL_WARNING
278 && (oldPlugged || mLastBatteryLevel >= BATTERY_LEVEL_WARNING);
Christopher Tate06ba5542009-04-09 16:03:56 -0700279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 mLastBatteryStatus = mBatteryStatus;
281 mLastBatteryHealth = mBatteryHealth;
282 mLastBatteryPresent = mBatteryPresent;
283 mLastBatteryLevel = mBatteryLevel;
284 mLastPlugType = mPlugType;
285 mLastBatteryVoltage = mBatteryVoltage;
286 mLastBatteryTemperature = mBatteryTemperature;
287 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mihai Predaa82842f2009-04-29 15:05:56 +0200288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 sendIntent();
Mihai Predaa82842f2009-04-29 15:05:56 +0200290 if (sendBatteryLow) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700291 mSentLowBatteryBroadcast = true;
Mihai Predaa82842f2009-04-29 15:05:56 +0200292 mContext.sendBroadcast(new Intent(Intent.ACTION_BATTERY_LOW));
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700293 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= BATTERY_LEVEL_CLOSE_WARNING) {
294 mSentLowBatteryBroadcast = false;
295 mContext.sendBroadcast(new Intent(Intent.ACTION_BATTERY_OKAY));
Mihai Predaa82842f2009-04-29 15:05:56 +0200296 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700297
298 // This needs to be done after sendIntent() so that we get the lastest battery stats.
299 if (logOutlier && dischargeDuration != 0) {
300 logOutlier(dischargeDuration);
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 }
303 }
304
305 private final void sendIntent() {
306 // Pack up the values and broadcast them to everyone
307 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
308 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
309 try {
The Android Open Source Project10592532009-03-18 17:39:46 -0700310 mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 } catch (RemoteException e) {
312 // Should never happen.
313 }
314
315 int icon = getIcon(mBatteryLevel);
316
317 intent.putExtra("status", mBatteryStatus);
318 intent.putExtra("health", mBatteryHealth);
319 intent.putExtra("present", mBatteryPresent);
320 intent.putExtra("level", mBatteryLevel);
321 intent.putExtra("scale", BATTERY_SCALE);
322 intent.putExtra("icon-small", icon);
323 intent.putExtra("plugged", mPlugType);
324 intent.putExtra("voltage", mBatteryVoltage);
325 intent.putExtra("temperature", mBatteryTemperature);
326 intent.putExtra("technology", mBatteryTechnology);
327
328 if (false) {
329 Log.d(TAG, "updateBattery level:" + mBatteryLevel +
330 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
331 " health:" + mBatteryHealth + " present:" + mBatteryPresent +
332 " voltage: " + mBatteryVoltage +
333 " temperature: " + mBatteryTemperature +
334 " technology: " + mBatteryTechnology +
335 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
336 " icon:" + icon );
337 }
338
339 ActivityManagerNative.broadcastStickyIntent(intent, null);
340 }
341
342 private final void logBatteryStats() {
343
344 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
345 if (batteryInfoService != null) {
346 byte[] buffer = new byte[DUMP_MAX_LENGTH];
347 File dumpFile = null;
348 FileOutputStream dumpStream = null;
349 try {
350 // dump the service to a file
351 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
352 dumpStream = new FileOutputStream(dumpFile);
353 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
354 dumpStream.getFD().sync();
355
356 // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
357 // and insert into events table.
358 int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
359 FileInputStream fileInputStream = new FileInputStream(dumpFile);
360 int nread = fileInputStream.read(buffer, 0, length);
361 if (nread > 0) {
362 Checkin.logEvent(mContext.getContentResolver(),
363 Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
364 new String(buffer, 0, nread));
365 if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
366 batteryInfoService + "to log");
367 if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
368 }
369 } catch (RemoteException e) {
370 Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
371 "':" + e);
372 } catch (IOException e) {
373 Log.e(TAG, "failed to write dumpsys file: " + e);
374 } finally {
375 // make sure we clean up
376 if (dumpStream != null) {
377 try {
378 dumpStream.close();
379 } catch (IOException e) {
380 Log.e(TAG, "failed to close dumpsys output stream");
381 }
382 }
383 if (dumpFile != null && !dumpFile.delete()) {
384 Log.e(TAG, "failed to delete temporary dumpsys file: "
385 + dumpFile.getAbsolutePath());
386 }
387 }
388 }
389 }
390
391 private final void logOutlier(long duration) {
392 ContentResolver cr = mContext.getContentResolver();
393 String dischargeThresholdString = Settings.Gservices.getString(cr,
394 Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
395 String durationThresholdString = Settings.Gservices.getString(cr,
396 Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
397
398 if (dischargeThresholdString != null && durationThresholdString != null) {
399 try {
400 long durationThreshold = Long.parseLong(durationThresholdString);
401 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
402 if (duration <= durationThreshold &&
403 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
404 // If the discharge cycle is bad enough we want to know about it.
405 logBatteryStats();
406 }
407 if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
408 " discharge threshold: " + dischargeThreshold);
409 if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
410 (mDischargeStartLevel - mBatteryLevel));
411 } catch (NumberFormatException e) {
412 Log.e(TAG, "Invalid DischargeThresholds GService string: " +
413 durationThresholdString + " or " + dischargeThresholdString);
414 return;
415 }
416 }
417 }
418
419 private final int getIcon(int level) {
420 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
421 return com.android.internal.R.drawable.stat_sys_battery_charge;
422 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
423 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
424 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
425 return com.android.internal.R.drawable.stat_sys_battery;
426 } else {
427 return com.android.internal.R.drawable.stat_sys_battery_unknown;
428 }
429 }
430
431 @Override
432 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
433 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
434 != PackageManager.PERMISSION_GRANTED) {
435
436 pw.println("Permission Denial: can't dump Battery service from from pid="
437 + Binder.getCallingPid()
438 + ", uid=" + Binder.getCallingUid());
439 return;
440 }
441
442 synchronized (this) {
443 pw.println("Current Battery Service state:");
444 pw.println(" AC powered: " + mAcOnline);
445 pw.println(" USB powered: " + mUsbOnline);
446 pw.println(" status: " + mBatteryStatus);
447 pw.println(" health: " + mBatteryHealth);
448 pw.println(" present: " + mBatteryPresent);
449 pw.println(" level: " + mBatteryLevel);
450 pw.println(" scale: " + BATTERY_SCALE);
451 pw.println(" voltage:" + mBatteryVoltage);
452 pw.println(" temperature: " + mBatteryTemperature);
453 pw.println(" technology: " + mBatteryTechnology);
454 }
455 }
456}