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