blob: 1f2947db786184cd84a08f5285c9c8864fd30784 [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;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070029import android.os.FileUtils;
Jeff Brown605ea692012-10-05 16:33:10 -070030import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.IBinder;
Dan Egnor18e93962010-02-10 19:27:58 -080032import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.os.RemoteException;
34import android.os.ServiceManager;
35import android.os.SystemClock;
36import android.os.UEventObserver;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070037import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.provider.Settings;
39import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080040import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
42import java.io.File;
43import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.io.FileOutputStream;
45import java.io.IOException;
46import java.io.PrintWriter;
47
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
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>
Jeff Brown605ea692012-10-05 16:33:10 -070070 *
71 * <p>
72 * The battery service may be called by the power manager while holding its locks so
73 * we take care to post all outcalls into the activity manager to a handler.
74 *
75 * FIXME: Ideally the power manager would perform all of its calls into the battery
76 * service asynchronously itself.
77 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 */
Jeff Browna4d82042012-10-02 19:11:19 -070079public final class BatteryService extends Binder {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 private static final String TAG = BatteryService.class.getSimpleName();
Doug Zongkerab5c49c2009-12-04 10:31:43 -080081
Jeff Browna4d82042012-10-02 19:11:19 -070082 private static final boolean DEBUG = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -080083
Jeff Browna4d82042012-10-02 19:11:19 -070084 private static final int BATTERY_SCALE = 100; // battery capacity is a percentage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 // Used locally for determining when to make a last ditch effort to log
87 // discharge stats before the device dies.
Joe Onorato4ca7f1e2010-10-27 15:32:23 -070088 private int mCriticalBatteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
90 private static final int DUMP_MAX_LENGTH = 24 * 1024;
Dianne Hackborn6447ca32009-04-07 19:50:08 -070091 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "-u" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo";
Doug Zongkerab5c49c2009-12-04 10:31:43 -080093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private static final String DUMPSYS_DATA_PATH = "/data/system/";
95
96 // This should probably be exposed in the API, though it's not critical
97 private static final int BATTERY_PLUGGED_NONE = 0;
98
99 private final Context mContext;
100 private final IBatteryStats mBatteryStats;
Jeff Brown605ea692012-10-05 16:33:10 -0700101 private final Handler mHandler;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800102
Jeff Browna4d82042012-10-02 19:11:19 -0700103 private final Object mLock = new Object();
104
105 /* Begin native fields: All of these fields are set by native code. */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private boolean mAcOnline;
107 private boolean mUsbOnline;
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700108 private boolean mWirelessOnline;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private int mBatteryStatus;
110 private int mBatteryHealth;
111 private boolean mBatteryPresent;
112 private int mBatteryLevel;
113 private int mBatteryVoltage;
114 private int mBatteryTemperature;
115 private String mBatteryTechnology;
116 private boolean mBatteryLevelCritical;
Jeff Browna4d82042012-10-02 19:11:19 -0700117 /* End native fields. */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
119 private int mLastBatteryStatus;
120 private int mLastBatteryHealth;
121 private boolean mLastBatteryPresent;
122 private int mLastBatteryLevel;
123 private int mLastBatteryVoltage;
124 private int mLastBatteryTemperature;
125 private boolean mLastBatteryLevelCritical;
Jeff Browna4d82042012-10-02 19:11:19 -0700126
127 private int mInvalidCharger;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700128 private int mLastInvalidCharger;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400129
130 private int mLowBatteryWarningLevel;
131 private int mLowBatteryCloseWarningLevel;
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700132 private int mShutdownBatteryTemperature;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private int mPlugType;
135 private int mLastPlugType = -1; // Extra state so we can detect first run
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private long mDischargeStartTime;
138 private int mDischargeStartLevel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800139
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700140 private boolean mUpdatesStopped;
141
Joe Onoratode1b3592010-10-25 20:36:47 -0700142 private Led mLed;
143
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700144 private boolean mSentLowBatteryBroadcast = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800145
Jeff Browna4d82042012-10-02 19:11:19 -0700146 private native void native_update();
147
Joe Onoratode1b3592010-10-25 20:36:47 -0700148 public BatteryService(Context context, LightsService lights) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 mContext = context;
Jeff Brown605ea692012-10-05 16:33:10 -0700150 mHandler = new Handler(true /*async*/);
Joe Onoratode1b3592010-10-25 20:36:47 -0700151 mLed = new Led(context, lights);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 mBatteryStats = BatteryStatsService.getService();
153
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700154 mCriticalBatteryLevel = mContext.getResources().getInteger(
155 com.android.internal.R.integer.config_criticalBatteryWarningLevel);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400156 mLowBatteryWarningLevel = mContext.getResources().getInteger(
157 com.android.internal.R.integer.config_lowBatteryWarningLevel);
158 mLowBatteryCloseWarningLevel = mContext.getResources().getInteger(
159 com.android.internal.R.integer.config_lowBatteryCloseWarningLevel);
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700160 mShutdownBatteryTemperature = mContext.getResources().getInteger(
161 com.android.internal.R.integer.config_shutdownBatteryTemperature);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400162
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400163 mPowerSupplyObserver.startObserving("SUBSYSTEM=power_supply");
164
165 // watch for invalid charger messages if the invalid_charger switch exists
166 if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
Jeff Browna4d82042012-10-02 19:11:19 -0700167 mInvalidChargerObserver.startObserving(
168 "DEVPATH=/devices/virtual/switch/invalid_charger");
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
171 // set initial status
Jeff Browna4d82042012-10-02 19:11:19 -0700172 synchronized (mLock) {
173 updateLocked();
174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 }
176
Jeff Browna4d82042012-10-02 19:11:19 -0700177 void systemReady() {
178 // check our power situation now that it is safe to display the shutdown dialog.
179 synchronized (mLock) {
180 shutdownIfNoPowerLocked();
181 shutdownIfOverTempLocked();
182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 }
184
Jeff Browna4d82042012-10-02 19:11:19 -0700185 /**
186 * Returns true if the device is plugged into any of the specified plug types.
187 */
188 public boolean isPowered(int plugTypeSet) {
189 synchronized (mLock) {
190 return isPoweredLocked(plugTypeSet);
191 }
192 }
193
194 private boolean isPoweredLocked(int plugTypeSet) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 // assume we are powered if battery state is unknown so
196 // the "stay on while plugged in" option will work.
197 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
198 return true;
199 }
Jeff Browna4d82042012-10-02 19:11:19 -0700200 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_AC) != 0 && mAcOnline) {
201 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 }
Jeff Browna4d82042012-10-02 19:11:19 -0700203 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_USB) != 0 && mUsbOnline) {
204 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 }
Jeff Browna4d82042012-10-02 19:11:19 -0700206 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0 && mWirelessOnline) {
207 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 }
Jeff Browna4d82042012-10-02 19:11:19 -0700209 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 }
211
Jeff Browna4d82042012-10-02 19:11:19 -0700212 /**
Jeff Brownf3fb8952012-10-02 20:57:05 -0700213 * Returns the current plug type.
214 */
215 public int getPlugType() {
216 synchronized (mLock) {
217 return mPlugType;
218 }
219 }
220
221 /**
Jeff Browna4d82042012-10-02 19:11:19 -0700222 * Returns battery level as a percentage.
223 */
224 public int getBatteryLevel() {
225 synchronized (mLock) {
226 return mBatteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 }
Jeff Browna4d82042012-10-02 19:11:19 -0700228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Jeff Browna4d82042012-10-02 19:11:19 -0700230 /**
231 * Returns true if battery level is below the first warning threshold.
232 */
233 public boolean isBatteryLow() {
234 synchronized (mLock) {
235 return mBatteryPresent && mBatteryLevel <= mLowBatteryWarningLevel;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 }
238
Svetoslav6a08a122013-05-03 11:24:26 -0700239 /**
240 * Returns a non-zero value if an unsupported charger is attached.
241 */
242 public int getInvalidCharger() {
243 synchronized (mLock) {
244 return mInvalidCharger;
245 }
246 }
247
Jeff Browna4d82042012-10-02 19:11:19 -0700248 private void shutdownIfNoPowerLocked() {
Mike Lockwood07a500f2009-08-12 09:56:44 -0400249 // shut down gracefully if our battery is critically low and we are not powered.
250 // wait until the system has booted before attempting to display the shutdown dialog.
Jeff Brown605ea692012-10-05 16:33:10 -0700251 if (mBatteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
252 mHandler.post(new Runnable() {
253 @Override
254 public void run() {
255 if (ActivityManagerNative.isSystemReady()) {
256 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
257 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
258 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
259 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
260 }
261 }
262 });
Mike Lockwood07a500f2009-08-12 09:56:44 -0400263 }
264 }
265
Jeff Browna4d82042012-10-02 19:11:19 -0700266 private void shutdownIfOverTempLocked() {
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700267 // shut down gracefully if temperature is too high (> 68.0C by default)
268 // wait until the system has booted before attempting to display the
269 // shutdown dialog.
Jeff Brown605ea692012-10-05 16:33:10 -0700270 if (mBatteryTemperature > mShutdownBatteryTemperature) {
271 mHandler.post(new Runnable() {
272 @Override
273 public void run() {
274 if (ActivityManagerNative.isSystemReady()) {
275 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
276 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
277 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
278 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
279 }
280 }
281 });
Eric Olsen6a362a92010-03-26 15:38:41 -0700282 }
283 }
284
Jeff Browna4d82042012-10-02 19:11:19 -0700285 private void updateLocked() {
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700286 if (!mUpdatesStopped) {
287 // Update the values of mAcOnline, et. all.
288 native_update();
Jeff Browna4d82042012-10-02 19:11:19 -0700289
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700290 // Process the new values.
291 processValuesLocked();
292 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Jeff Browna4d82042012-10-02 19:11:19 -0700295 private void processValuesLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -0700296 boolean logOutlier = false;
297 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700298
Jeff Browna4d82042012-10-02 19:11:19 -0700299 mBatteryLevelCritical = (mBatteryLevel <= mCriticalBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 if (mAcOnline) {
301 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
302 } else if (mUsbOnline) {
303 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700304 } else if (mWirelessOnline) {
305 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 } else {
307 mPlugType = BATTERY_PLUGGED_NONE;
308 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700309
Jeff Browna4d82042012-10-02 19:11:19 -0700310 if (DEBUG) {
311 Slog.d(TAG, "Processing new values: "
312 + "mAcOnline=" + mAcOnline
313 + ", mUsbOnline=" + mUsbOnline
314 + ", mWirelessOnline=" + mWirelessOnline
315 + ", mBatteryStatus=" + mBatteryStatus
316 + ", mBatteryHealth=" + mBatteryHealth
317 + ", mBatteryPresent=" + mBatteryPresent
318 + ", mBatteryLevel=" + mBatteryLevel
319 + ", mBatteryTechnology=" + mBatteryTechnology
320 + ", mBatteryVoltage=" + mBatteryVoltage
321 + ", mBatteryTemperature=" + mBatteryTemperature
322 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
323 + ", mPlugType=" + mPlugType);
324 }
325
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700326 // Let the battery stats keep track of the current level.
327 try {
328 mBatteryStats.setBatteryState(mBatteryStatus, mBatteryHealth,
329 mPlugType, mBatteryLevel, mBatteryTemperature,
330 mBatteryVoltage);
331 } catch (RemoteException e) {
332 // Should never happen.
333 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700334
Jeff Browna4d82042012-10-02 19:11:19 -0700335 shutdownIfNoPowerLocked();
336 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 if (mBatteryStatus != mLastBatteryStatus ||
339 mBatteryHealth != mLastBatteryHealth ||
340 mBatteryPresent != mLastBatteryPresent ||
341 mBatteryLevel != mLastBatteryLevel ||
342 mPlugType != mLastPlugType ||
343 mBatteryVoltage != mLastBatteryVoltage ||
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400344 mBatteryTemperature != mLastBatteryTemperature ||
345 mInvalidCharger != mLastInvalidCharger) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 if (mPlugType != mLastPlugType) {
348 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
349 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 // There's no value in this data unless we've discharged at least once and the
352 // battery level has changed; so don't log until it does.
353 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700354 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
355 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800356 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 mDischargeStartLevel, mBatteryLevel);
358 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800359 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
362 // charging -> discharging or we just powered up
363 mDischargeStartTime = SystemClock.elapsedRealtime();
364 mDischargeStartLevel = mBatteryLevel;
365 }
366 }
367 if (mBatteryStatus != mLastBatteryStatus ||
368 mBatteryHealth != mLastBatteryHealth ||
369 mBatteryPresent != mLastBatteryPresent ||
370 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800371 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
373 mPlugType, mBatteryTechnology);
374 }
375 if (mBatteryLevel != mLastBatteryLevel ||
376 mBatteryVoltage != mLastBatteryVoltage ||
377 mBatteryTemperature != mLastBatteryTemperature) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800378 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
380 }
381 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
382 mPlugType == BATTERY_PLUGGED_NONE) {
383 // We want to make sure we log discharge cycle outliers
384 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700385 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
386 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800388
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700389 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
390 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
391
392 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400393 * - is just un-plugged (previously was plugged) and battery level is
394 * less than or equal to WARNING, or
395 * - is not plugged and battery level falls to WARNING boundary
396 * (becomes <= mLowBatteryWarningLevel).
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700397 */
398 final boolean sendBatteryLow = !plugged
Joe Onoratode1b3592010-10-25 20:36:47 -0700399 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
400 && mBatteryLevel <= mLowBatteryWarningLevel
401 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800402
Jeff Browna4d82042012-10-02 19:11:19 -0700403 sendIntentLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800404
Christopher Tate06ba5542009-04-09 16:03:56 -0700405 // Separate broadcast is sent for power connected / not connected
406 // since the standard intent will not wake any applications and some
407 // applications may want to have smart behavior based on this.
408 if (mPlugType != 0 && mLastPlugType == 0) {
Jeff Brown605ea692012-10-05 16:33:10 -0700409 mHandler.post(new Runnable() {
410 @Override
411 public void run() {
412 Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
413 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
414 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
415 }
416 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700417 }
418 else if (mPlugType == 0 && mLastPlugType != 0) {
Jeff Brown605ea692012-10-05 16:33:10 -0700419 mHandler.post(new Runnable() {
420 @Override
421 public void run() {
422 Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
423 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
424 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
425 }
426 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700427 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200428
Mihai Predaa82842f2009-04-29 15:05:56 +0200429 if (sendBatteryLow) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700430 mSentLowBatteryBroadcast = true;
Jeff Brown605ea692012-10-05 16:33:10 -0700431 mHandler.post(new Runnable() {
432 @Override
433 public void run() {
434 Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
435 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
436 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
437 }
438 });
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400439 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700440 mSentLowBatteryBroadcast = false;
Jeff Brown605ea692012-10-05 16:33:10 -0700441 mHandler.post(new Runnable() {
442 @Override
443 public void run() {
444 Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
445 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
446 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
447 }
448 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800450
Joe Onoratode1b3592010-10-25 20:36:47 -0700451 // Update the battery LED
452 mLed.updateLightsLocked();
453
The Android Open Source Project10592532009-03-18 17:39:46 -0700454 // This needs to be done after sendIntent() so that we get the lastest battery stats.
455 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700456 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800458
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700459 mLastBatteryStatus = mBatteryStatus;
460 mLastBatteryHealth = mBatteryHealth;
461 mLastBatteryPresent = mBatteryPresent;
462 mLastBatteryLevel = mBatteryLevel;
463 mLastPlugType = mPlugType;
464 mLastBatteryVoltage = mBatteryVoltage;
465 mLastBatteryTemperature = mBatteryTemperature;
466 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400467 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 }
469 }
470
Jeff Browna4d82042012-10-02 19:11:19 -0700471 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700473 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
475 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800476
Jeff Browna4d82042012-10-02 19:11:19 -0700477 int icon = getIconLocked(mBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478
Dianne Hackbornedd93162009-09-19 14:03:05 -0700479 intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus);
480 intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth);
481 intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent);
482 intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel);
483 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
484 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
485 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
486 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryVoltage);
487 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature);
488 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400489 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490
Jeff Browna4d82042012-10-02 19:11:19 -0700491 if (DEBUG) {
492 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. level:" + mBatteryLevel +
493 ", scale:" + BATTERY_SCALE + ", status:" + mBatteryStatus +
494 ", health:" + mBatteryHealth + ", present:" + mBatteryPresent +
495 ", voltage: " + mBatteryVoltage +
496 ", temperature: " + mBatteryTemperature +
497 ", technology: " + mBatteryTechnology +
498 ", AC powered:" + mAcOnline + ", USB powered:" + mUsbOnline +
499 ", Wireless powered:" + mWirelessOnline +
500 ", icon:" + icon + ", invalid charger:" + mInvalidCharger);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 }
502
Jeff Brown605ea692012-10-05 16:33:10 -0700503 mHandler.post(new Runnable() {
504 @Override
505 public void run() {
506 ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
507 }
508 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 }
510
Jeff Browna4d82042012-10-02 19:11:19 -0700511 private void logBatteryStatsLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800513 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514
Dan Egnor18e93962010-02-10 19:27:58 -0800515 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
516 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
517
518 File dumpFile = null;
519 FileOutputStream dumpStream = null;
520 try {
521 // dump the service to a file
522 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
523 dumpStream = new FileOutputStream(dumpFile);
524 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700525 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800526
527 // add dump file to drop box
528 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
529 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800530 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800531 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800532 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800533 } finally {
534 // make sure we clean up
535 if (dumpStream != null) {
536 try {
537 dumpStream.close();
538 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800539 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
Dan Egnor18e93962010-02-10 19:27:58 -0800541 }
542 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800543 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800544 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546 }
547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800548
Jeff Browna4d82042012-10-02 19:11:19 -0700549 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700551 String dischargeThresholdString = Settings.Global.getString(cr,
552 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
553 String durationThresholdString = Settings.Global.getString(cr,
554 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 if (dischargeThresholdString != null && durationThresholdString != null) {
557 try {
558 long durationThreshold = Long.parseLong(durationThresholdString);
559 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800560 if (duration <= durationThreshold &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
562 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700563 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 }
Jeff Browna4d82042012-10-02 19:11:19 -0700565 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700567 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 (mDischargeStartLevel - mBatteryLevel));
569 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800570 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 durationThresholdString + " or " + dischargeThresholdString);
572 return;
573 }
574 }
575 }
576
Jeff Browna4d82042012-10-02 19:11:19 -0700577 private int getIconLocked(int level) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
579 return com.android.internal.R.drawable.stat_sys_battery_charge;
Joe Onorato794be402010-11-21 19:22:25 -0800580 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 return com.android.internal.R.drawable.stat_sys_battery;
Joe Onorato794be402010-11-21 19:22:25 -0800582 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
583 || mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700584 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
585 && mBatteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800586 return com.android.internal.R.drawable.stat_sys_battery_charge;
587 } else {
588 return com.android.internal.R.drawable.stat_sys_battery;
589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 } else {
591 return com.android.internal.R.drawable.stat_sys_battery_unknown;
592 }
593 }
594
595 @Override
596 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
597 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
598 != PackageManager.PERMISSION_GRANTED) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 pw.println("Permission Denial: can't dump Battery service from from pid="
601 + Binder.getCallingPid()
602 + ", uid=" + Binder.getCallingUid());
603 return;
604 }
605
Jeff Browna4d82042012-10-02 19:11:19 -0700606 synchronized (mLock) {
607 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700608 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700609 if (mUpdatesStopped) {
610 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
611 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700612 pw.println(" AC powered: " + mAcOnline);
613 pw.println(" USB powered: " + mUsbOnline);
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700614 pw.println(" Wireless powered: " + mWirelessOnline);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700615 pw.println(" status: " + mBatteryStatus);
616 pw.println(" health: " + mBatteryHealth);
617 pw.println(" present: " + mBatteryPresent);
618 pw.println(" level: " + mBatteryLevel);
619 pw.println(" scale: " + BATTERY_SCALE);
620 pw.println(" voltage:" + mBatteryVoltage);
621 pw.println(" temperature: " + mBatteryTemperature);
622 pw.println(" technology: " + mBatteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700623 } else if (args.length == 3 && "set".equals(args[0])) {
624 String key = args[1];
625 String value = args[2];
626 try {
627 boolean update = true;
628 if ("ac".equals(key)) {
629 mAcOnline = Integer.parseInt(value) != 0;
630 } else if ("usb".equals(key)) {
631 mUsbOnline = Integer.parseInt(value) != 0;
632 } else if ("wireless".equals(key)) {
633 mWirelessOnline = Integer.parseInt(value) != 0;
634 } else if ("status".equals(key)) {
635 mBatteryStatus = Integer.parseInt(value);
636 } else if ("level".equals(key)) {
637 mBatteryLevel = Integer.parseInt(value);
638 } else if ("invalid".equals(key)) {
639 mInvalidCharger = Integer.parseInt(value);
640 } else {
641 pw.println("Unknown set option: " + key);
642 update = false;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700643 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700644 if (update) {
645 mUpdatesStopped = true;
646 processValuesLocked();
647 }
648 } catch (NumberFormatException ex) {
649 pw.println("Bad value: " + value);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700650 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700651 } else if (args.length == 1 && "reset".equals(args[0])) {
652 mUpdatesStopped = false;
653 updateLocked();
654 } else {
655 pw.println("Dump current battery state, or:");
656 pw.println(" set ac|usb|wireless|status|level|invalid <value>");
657 pw.println(" reset");
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 }
660 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700661
Jeff Browna4d82042012-10-02 19:11:19 -0700662 private final UEventObserver mPowerSupplyObserver = new UEventObserver() {
663 @Override
664 public void onUEvent(UEventObserver.UEvent event) {
665 synchronized (mLock) {
666 updateLocked();
667 }
668 }
669 };
Joe Onoratode1b3592010-10-25 20:36:47 -0700670
Jeff Browna4d82042012-10-02 19:11:19 -0700671 private final UEventObserver mInvalidChargerObserver = new UEventObserver() {
672 @Override
673 public void onUEvent(UEventObserver.UEvent event) {
674 final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
675 synchronized (mLock) {
676 if (mInvalidCharger != invalidCharger) {
677 mInvalidCharger = invalidCharger;
678 updateLocked();
679 }
680 }
681 }
682 };
Joe Onoratode1b3592010-10-25 20:36:47 -0700683
Jeff Browna4d82042012-10-02 19:11:19 -0700684 private final class Led {
685 private final LightsService.Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700686
Jeff Browna4d82042012-10-02 19:11:19 -0700687 private final int mBatteryLowARGB;
688 private final int mBatteryMediumARGB;
689 private final int mBatteryFullARGB;
690 private final int mBatteryLedOn;
691 private final int mBatteryLedOff;
692
693 public Led(Context context, LightsService lights) {
Joe Onoratode1b3592010-10-25 20:36:47 -0700694 mBatteryLight = lights.getLight(LightsService.LIGHT_ID_BATTERY);
695
Jeff Browna4d82042012-10-02 19:11:19 -0700696 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700697 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700698 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700699 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700700 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700701 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700702 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700703 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700704 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700705 com.android.internal.R.integer.config_notificationsBatteryLedOff);
706 }
707
708 /**
709 * Synchronize on BatteryService.
710 */
Jeff Browna4d82042012-10-02 19:11:19 -0700711 public void updateLightsLocked() {
Joe Onoratode1b3592010-10-25 20:36:47 -0700712 final int level = mBatteryLevel;
713 final int status = mBatteryStatus;
714 if (level < mLowBatteryWarningLevel) {
715 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
716 // Solid red when battery is charging
717 mBatteryLight.setColor(mBatteryLowARGB);
718 } else {
719 // Flash red when battery is low and not charging
720 mBatteryLight.setFlashing(mBatteryLowARGB, LightsService.LIGHT_FLASH_TIMED,
721 mBatteryLedOn, mBatteryLedOff);
722 }
723 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
724 || status == BatteryManager.BATTERY_STATUS_FULL) {
725 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
726 // Solid green when full or charging and nearly full
727 mBatteryLight.setColor(mBatteryFullARGB);
728 } else {
729 // Solid orange when charging and halfway full
730 mBatteryLight.setColor(mBatteryMediumARGB);
731 }
732 } else {
733 // No lights if not charging and not low
734 mBatteryLight.turnOff();
735 }
736 }
737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738}