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