blob: 73ff5016735ff18adb11c52ad73e84730f3d7fdb [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;
87 private static final String[] DUMPSYS_ARGS = new String[] { "-c", "-u" };
88 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 }
232 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
233 mPlugType == BATTERY_PLUGGED_NONE) {
234 // We want to make sure we log discharge cycle outliers
235 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700236 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
237 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 }
239
240 mLastBatteryStatus = mBatteryStatus;
241 mLastBatteryHealth = mBatteryHealth;
242 mLastBatteryPresent = mBatteryPresent;
243 mLastBatteryLevel = mBatteryLevel;
244 mLastPlugType = mPlugType;
245 mLastBatteryVoltage = mBatteryVoltage;
246 mLastBatteryTemperature = mBatteryTemperature;
247 mLastBatteryLevelCritical = mBatteryLevelCritical;
248
249 sendIntent();
The Android Open Source Project10592532009-03-18 17:39:46 -0700250
251 // This needs to be done after sendIntent() so that we get the lastest battery stats.
252 if (logOutlier && dischargeDuration != 0) {
253 logOutlier(dischargeDuration);
254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 }
256 }
257
258 private final void sendIntent() {
259 // Pack up the values and broadcast them to everyone
260 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
261 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
262 try {
The Android Open Source Project10592532009-03-18 17:39:46 -0700263 mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE, mBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 } catch (RemoteException e) {
265 // Should never happen.
266 }
267
268 int icon = getIcon(mBatteryLevel);
269
270 intent.putExtra("status", mBatteryStatus);
271 intent.putExtra("health", mBatteryHealth);
272 intent.putExtra("present", mBatteryPresent);
273 intent.putExtra("level", mBatteryLevel);
274 intent.putExtra("scale", BATTERY_SCALE);
275 intent.putExtra("icon-small", icon);
276 intent.putExtra("plugged", mPlugType);
277 intent.putExtra("voltage", mBatteryVoltage);
278 intent.putExtra("temperature", mBatteryTemperature);
279 intent.putExtra("technology", mBatteryTechnology);
280
281 if (false) {
282 Log.d(TAG, "updateBattery level:" + mBatteryLevel +
283 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
284 " health:" + mBatteryHealth + " present:" + mBatteryPresent +
285 " voltage: " + mBatteryVoltage +
286 " temperature: " + mBatteryTemperature +
287 " technology: " + mBatteryTechnology +
288 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
289 " icon:" + icon );
290 }
291
292 ActivityManagerNative.broadcastStickyIntent(intent, null);
293 }
294
295 private final void logBatteryStats() {
296
297 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
298 if (batteryInfoService != null) {
299 byte[] buffer = new byte[DUMP_MAX_LENGTH];
300 File dumpFile = null;
301 FileOutputStream dumpStream = null;
302 try {
303 // dump the service to a file
304 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
305 dumpStream = new FileOutputStream(dumpFile);
306 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
307 dumpStream.getFD().sync();
308
309 // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
310 // and insert into events table.
311 int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
312 FileInputStream fileInputStream = new FileInputStream(dumpFile);
313 int nread = fileInputStream.read(buffer, 0, length);
314 if (nread > 0) {
315 Checkin.logEvent(mContext.getContentResolver(),
316 Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
317 new String(buffer, 0, nread));
318 if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
319 batteryInfoService + "to log");
320 if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
321 }
322 } catch (RemoteException e) {
323 Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
324 "':" + e);
325 } catch (IOException e) {
326 Log.e(TAG, "failed to write dumpsys file: " + e);
327 } finally {
328 // make sure we clean up
329 if (dumpStream != null) {
330 try {
331 dumpStream.close();
332 } catch (IOException e) {
333 Log.e(TAG, "failed to close dumpsys output stream");
334 }
335 }
336 if (dumpFile != null && !dumpFile.delete()) {
337 Log.e(TAG, "failed to delete temporary dumpsys file: "
338 + dumpFile.getAbsolutePath());
339 }
340 }
341 }
342 }
343
344 private final void logOutlier(long duration) {
345 ContentResolver cr = mContext.getContentResolver();
346 String dischargeThresholdString = Settings.Gservices.getString(cr,
347 Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
348 String durationThresholdString = Settings.Gservices.getString(cr,
349 Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
350
351 if (dischargeThresholdString != null && durationThresholdString != null) {
352 try {
353 long durationThreshold = Long.parseLong(durationThresholdString);
354 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
355 if (duration <= durationThreshold &&
356 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
357 // If the discharge cycle is bad enough we want to know about it.
358 logBatteryStats();
359 }
360 if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
361 " discharge threshold: " + dischargeThreshold);
362 if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
363 (mDischargeStartLevel - mBatteryLevel));
364 } catch (NumberFormatException e) {
365 Log.e(TAG, "Invalid DischargeThresholds GService string: " +
366 durationThresholdString + " or " + dischargeThresholdString);
367 return;
368 }
369 }
370 }
371
372 private final int getIcon(int level) {
373 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
374 return com.android.internal.R.drawable.stat_sys_battery_charge;
375 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
376 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
377 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
378 return com.android.internal.R.drawable.stat_sys_battery;
379 } else {
380 return com.android.internal.R.drawable.stat_sys_battery_unknown;
381 }
382 }
383
384 @Override
385 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
386 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
387 != PackageManager.PERMISSION_GRANTED) {
388
389 pw.println("Permission Denial: can't dump Battery service from from pid="
390 + Binder.getCallingPid()
391 + ", uid=" + Binder.getCallingUid());
392 return;
393 }
394
395 synchronized (this) {
396 pw.println("Current Battery Service state:");
397 pw.println(" AC powered: " + mAcOnline);
398 pw.println(" USB powered: " + mUsbOnline);
399 pw.println(" status: " + mBatteryStatus);
400 pw.println(" health: " + mBatteryHealth);
401 pw.println(" present: " + mBatteryPresent);
402 pw.println(" level: " + mBatteryLevel);
403 pw.println(" scale: " + BATTERY_SCALE);
404 pw.println(" voltage:" + mBatteryVoltage);
405 pw.println(" temperature: " + mBatteryTemperature);
406 pw.println(" technology: " + mBatteryTechnology);
407 }
408 }
409}