blob: 36fd7fc3ecc29abd5ff179c4abfcfaac14ee499f [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;
Jeff Sharkeyec43a6b2013-04-30 13:33:18 -070091 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "--unplugged" };
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
Jeff Browna4d82042012-10-02 19:11:19 -0700239 private void shutdownIfNoPowerLocked() {
Mike Lockwood07a500f2009-08-12 09:56:44 -0400240 // shut down gracefully if our battery is critically low and we are not powered.
241 // wait until the system has booted before attempting to display the shutdown dialog.
Jeff Brown605ea692012-10-05 16:33:10 -0700242 if (mBatteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
243 mHandler.post(new Runnable() {
244 @Override
245 public void run() {
246 if (ActivityManagerNative.isSystemReady()) {
247 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
248 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
249 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
250 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
251 }
252 }
253 });
Mike Lockwood07a500f2009-08-12 09:56:44 -0400254 }
255 }
256
Jeff Browna4d82042012-10-02 19:11:19 -0700257 private void shutdownIfOverTempLocked() {
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700258 // shut down gracefully if temperature is too high (> 68.0C by default)
259 // wait until the system has booted before attempting to display the
260 // shutdown dialog.
Jeff Brown605ea692012-10-05 16:33:10 -0700261 if (mBatteryTemperature > mShutdownBatteryTemperature) {
262 mHandler.post(new Runnable() {
263 @Override
264 public void run() {
265 if (ActivityManagerNative.isSystemReady()) {
266 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
267 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
268 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
269 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
270 }
271 }
272 });
Eric Olsen6a362a92010-03-26 15:38:41 -0700273 }
274 }
275
Jeff Browna4d82042012-10-02 19:11:19 -0700276 private void updateLocked() {
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700277 if (!mUpdatesStopped) {
278 // Update the values of mAcOnline, et. all.
279 native_update();
Jeff Browna4d82042012-10-02 19:11:19 -0700280
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700281 // Process the new values.
282 processValuesLocked();
283 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285
Jeff Browna4d82042012-10-02 19:11:19 -0700286 private void processValuesLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -0700287 boolean logOutlier = false;
288 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700289
Jeff Browna4d82042012-10-02 19:11:19 -0700290 mBatteryLevelCritical = (mBatteryLevel <= mCriticalBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 if (mAcOnline) {
292 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
293 } else if (mUsbOnline) {
294 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700295 } else if (mWirelessOnline) {
296 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 } else {
298 mPlugType = BATTERY_PLUGGED_NONE;
299 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700300
Jeff Browna4d82042012-10-02 19:11:19 -0700301 if (DEBUG) {
302 Slog.d(TAG, "Processing new values: "
303 + "mAcOnline=" + mAcOnline
304 + ", mUsbOnline=" + mUsbOnline
305 + ", mWirelessOnline=" + mWirelessOnline
306 + ", mBatteryStatus=" + mBatteryStatus
307 + ", mBatteryHealth=" + mBatteryHealth
308 + ", mBatteryPresent=" + mBatteryPresent
309 + ", mBatteryLevel=" + mBatteryLevel
310 + ", mBatteryTechnology=" + mBatteryTechnology
311 + ", mBatteryVoltage=" + mBatteryVoltage
312 + ", mBatteryTemperature=" + mBatteryTemperature
313 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
314 + ", mPlugType=" + mPlugType);
315 }
316
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700317 // Let the battery stats keep track of the current level.
318 try {
319 mBatteryStats.setBatteryState(mBatteryStatus, mBatteryHealth,
320 mPlugType, mBatteryLevel, mBatteryTemperature,
321 mBatteryVoltage);
322 } catch (RemoteException e) {
323 // Should never happen.
324 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700325
Jeff Browna4d82042012-10-02 19:11:19 -0700326 shutdownIfNoPowerLocked();
327 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 if (mBatteryStatus != mLastBatteryStatus ||
330 mBatteryHealth != mLastBatteryHealth ||
331 mBatteryPresent != mLastBatteryPresent ||
332 mBatteryLevel != mLastBatteryLevel ||
333 mPlugType != mLastPlugType ||
334 mBatteryVoltage != mLastBatteryVoltage ||
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400335 mBatteryTemperature != mLastBatteryTemperature ||
336 mInvalidCharger != mLastInvalidCharger) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 if (mPlugType != mLastPlugType) {
339 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
340 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 // There's no value in this data unless we've discharged at least once and the
343 // battery level has changed; so don't log until it does.
344 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700345 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
346 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800347 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 mDischargeStartLevel, mBatteryLevel);
349 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800350 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
352 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
353 // charging -> discharging or we just powered up
354 mDischargeStartTime = SystemClock.elapsedRealtime();
355 mDischargeStartLevel = mBatteryLevel;
356 }
357 }
358 if (mBatteryStatus != mLastBatteryStatus ||
359 mBatteryHealth != mLastBatteryHealth ||
360 mBatteryPresent != mLastBatteryPresent ||
361 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800362 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
364 mPlugType, mBatteryTechnology);
365 }
366 if (mBatteryLevel != mLastBatteryLevel ||
367 mBatteryVoltage != mLastBatteryVoltage ||
368 mBatteryTemperature != mLastBatteryTemperature) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800369 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
371 }
372 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
373 mPlugType == BATTERY_PLUGGED_NONE) {
374 // We want to make sure we log discharge cycle outliers
375 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700376 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
377 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800379
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700380 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
381 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
382
383 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400384 * - is just un-plugged (previously was plugged) and battery level is
385 * less than or equal to WARNING, or
386 * - is not plugged and battery level falls to WARNING boundary
387 * (becomes <= mLowBatteryWarningLevel).
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700388 */
389 final boolean sendBatteryLow = !plugged
Joe Onoratode1b3592010-10-25 20:36:47 -0700390 && mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
391 && mBatteryLevel <= mLowBatteryWarningLevel
392 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800393
Jeff Browna4d82042012-10-02 19:11:19 -0700394 sendIntentLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800395
Christopher Tate06ba5542009-04-09 16:03:56 -0700396 // Separate broadcast is sent for power connected / not connected
397 // since the standard intent will not wake any applications and some
398 // applications may want to have smart behavior based on this.
399 if (mPlugType != 0 && mLastPlugType == 0) {
Jeff Brown605ea692012-10-05 16:33:10 -0700400 mHandler.post(new Runnable() {
401 @Override
402 public void run() {
403 Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
404 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
405 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
406 }
407 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700408 }
409 else if (mPlugType == 0 && mLastPlugType != 0) {
Jeff Brown605ea692012-10-05 16:33:10 -0700410 mHandler.post(new Runnable() {
411 @Override
412 public void run() {
413 Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
414 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
415 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
416 }
417 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700418 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200419
Mihai Predaa82842f2009-04-29 15:05:56 +0200420 if (sendBatteryLow) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700421 mSentLowBatteryBroadcast = true;
Jeff Brown605ea692012-10-05 16:33:10 -0700422 mHandler.post(new Runnable() {
423 @Override
424 public void run() {
425 Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
426 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
427 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
428 }
429 });
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400430 } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700431 mSentLowBatteryBroadcast = false;
Jeff Brown605ea692012-10-05 16:33:10 -0700432 mHandler.post(new Runnable() {
433 @Override
434 public void run() {
435 Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
436 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
437 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
438 }
439 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800441
Joe Onoratode1b3592010-10-25 20:36:47 -0700442 // Update the battery LED
443 mLed.updateLightsLocked();
444
The Android Open Source Project10592532009-03-18 17:39:46 -0700445 // This needs to be done after sendIntent() so that we get the lastest battery stats.
446 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700447 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700448 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800449
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700450 mLastBatteryStatus = mBatteryStatus;
451 mLastBatteryHealth = mBatteryHealth;
452 mLastBatteryPresent = mBatteryPresent;
453 mLastBatteryLevel = mBatteryLevel;
454 mLastPlugType = mPlugType;
455 mLastBatteryVoltage = mBatteryVoltage;
456 mLastBatteryTemperature = mBatteryTemperature;
457 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400458 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 }
460 }
461
Jeff Browna4d82042012-10-02 19:11:19 -0700462 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700464 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800465 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
466 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467
Jeff Browna4d82042012-10-02 19:11:19 -0700468 int icon = getIconLocked(mBatteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469
Dianne Hackbornedd93162009-09-19 14:03:05 -0700470 intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus);
471 intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth);
472 intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent);
473 intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel);
474 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
475 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
476 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
477 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryVoltage);
478 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature);
479 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400480 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481
Jeff Browna4d82042012-10-02 19:11:19 -0700482 if (DEBUG) {
483 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. level:" + mBatteryLevel +
484 ", scale:" + BATTERY_SCALE + ", status:" + mBatteryStatus +
485 ", health:" + mBatteryHealth + ", present:" + mBatteryPresent +
486 ", voltage: " + mBatteryVoltage +
487 ", temperature: " + mBatteryTemperature +
488 ", technology: " + mBatteryTechnology +
489 ", AC powered:" + mAcOnline + ", USB powered:" + mUsbOnline +
490 ", Wireless powered:" + mWirelessOnline +
491 ", icon:" + icon + ", invalid charger:" + mInvalidCharger);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493
Jeff Brown605ea692012-10-05 16:33:10 -0700494 mHandler.post(new Runnable() {
495 @Override
496 public void run() {
497 ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
498 }
499 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
501
Jeff Browna4d82042012-10-02 19:11:19 -0700502 private void logBatteryStatsLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800504 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505
Dan Egnor18e93962010-02-10 19:27:58 -0800506 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
507 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
508
509 File dumpFile = null;
510 FileOutputStream dumpStream = null;
511 try {
512 // dump the service to a file
513 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
514 dumpStream = new FileOutputStream(dumpFile);
515 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700516 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800517
518 // add dump file to drop box
519 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
520 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800521 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800522 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800523 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800524 } finally {
525 // make sure we clean up
526 if (dumpStream != null) {
527 try {
528 dumpStream.close();
529 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800530 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
Dan Egnor18e93962010-02-10 19:27:58 -0800532 }
533 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800534 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800535 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 }
537 }
538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800539
Jeff Browna4d82042012-10-02 19:11:19 -0700540 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700542 String dischargeThresholdString = Settings.Global.getString(cr,
543 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
544 String durationThresholdString = Settings.Global.getString(cr,
545 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 if (dischargeThresholdString != null && durationThresholdString != null) {
548 try {
549 long durationThreshold = Long.parseLong(durationThresholdString);
550 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800551 if (duration <= durationThreshold &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
553 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700554 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 }
Jeff Browna4d82042012-10-02 19:11:19 -0700556 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700558 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 (mDischargeStartLevel - mBatteryLevel));
560 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800561 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 durationThresholdString + " or " + dischargeThresholdString);
563 return;
564 }
565 }
566 }
567
Jeff Browna4d82042012-10-02 19:11:19 -0700568 private int getIconLocked(int level) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
570 return com.android.internal.R.drawable.stat_sys_battery_charge;
Joe Onorato794be402010-11-21 19:22:25 -0800571 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 return com.android.internal.R.drawable.stat_sys_battery;
Joe Onorato794be402010-11-21 19:22:25 -0800573 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
574 || mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700575 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
576 && mBatteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800577 return com.android.internal.R.drawable.stat_sys_battery_charge;
578 } else {
579 return com.android.internal.R.drawable.stat_sys_battery;
580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 } else {
582 return com.android.internal.R.drawable.stat_sys_battery_unknown;
583 }
584 }
585
586 @Override
587 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
588 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
589 != PackageManager.PERMISSION_GRANTED) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 pw.println("Permission Denial: can't dump Battery service from from pid="
592 + Binder.getCallingPid()
593 + ", uid=" + Binder.getCallingUid());
594 return;
595 }
596
Jeff Browna4d82042012-10-02 19:11:19 -0700597 synchronized (mLock) {
598 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700599 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700600 if (mUpdatesStopped) {
601 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
602 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700603 pw.println(" AC powered: " + mAcOnline);
604 pw.println(" USB powered: " + mUsbOnline);
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700605 pw.println(" Wireless powered: " + mWirelessOnline);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700606 pw.println(" status: " + mBatteryStatus);
607 pw.println(" health: " + mBatteryHealth);
608 pw.println(" present: " + mBatteryPresent);
609 pw.println(" level: " + mBatteryLevel);
610 pw.println(" scale: " + BATTERY_SCALE);
611 pw.println(" voltage:" + mBatteryVoltage);
612 pw.println(" temperature: " + mBatteryTemperature);
613 pw.println(" technology: " + mBatteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700614 } else if (args.length == 3 && "set".equals(args[0])) {
615 String key = args[1];
616 String value = args[2];
617 try {
618 boolean update = true;
619 if ("ac".equals(key)) {
620 mAcOnline = Integer.parseInt(value) != 0;
621 } else if ("usb".equals(key)) {
622 mUsbOnline = Integer.parseInt(value) != 0;
623 } else if ("wireless".equals(key)) {
624 mWirelessOnline = Integer.parseInt(value) != 0;
625 } else if ("status".equals(key)) {
626 mBatteryStatus = Integer.parseInt(value);
627 } else if ("level".equals(key)) {
628 mBatteryLevel = Integer.parseInt(value);
629 } else if ("invalid".equals(key)) {
630 mInvalidCharger = Integer.parseInt(value);
631 } else {
632 pw.println("Unknown set option: " + key);
633 update = false;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700634 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700635 if (update) {
636 mUpdatesStopped = true;
637 processValuesLocked();
638 }
639 } catch (NumberFormatException ex) {
640 pw.println("Bad value: " + value);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700641 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700642 } else if (args.length == 1 && "reset".equals(args[0])) {
643 mUpdatesStopped = false;
644 updateLocked();
645 } else {
646 pw.println("Dump current battery state, or:");
647 pw.println(" set ac|usb|wireless|status|level|invalid <value>");
648 pw.println(" reset");
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 }
651 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700652
Jeff Browna4d82042012-10-02 19:11:19 -0700653 private final UEventObserver mPowerSupplyObserver = new UEventObserver() {
654 @Override
655 public void onUEvent(UEventObserver.UEvent event) {
656 synchronized (mLock) {
657 updateLocked();
658 }
659 }
660 };
Joe Onoratode1b3592010-10-25 20:36:47 -0700661
Jeff Browna4d82042012-10-02 19:11:19 -0700662 private final UEventObserver mInvalidChargerObserver = new UEventObserver() {
663 @Override
664 public void onUEvent(UEventObserver.UEvent event) {
665 final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
666 synchronized (mLock) {
667 if (mInvalidCharger != invalidCharger) {
668 mInvalidCharger = invalidCharger;
669 updateLocked();
670 }
671 }
672 }
673 };
Joe Onoratode1b3592010-10-25 20:36:47 -0700674
Jeff Browna4d82042012-10-02 19:11:19 -0700675 private final class Led {
676 private final LightsService.Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700677
Jeff Browna4d82042012-10-02 19:11:19 -0700678 private final int mBatteryLowARGB;
679 private final int mBatteryMediumARGB;
680 private final int mBatteryFullARGB;
681 private final int mBatteryLedOn;
682 private final int mBatteryLedOff;
683
684 public Led(Context context, LightsService lights) {
Joe Onoratode1b3592010-10-25 20:36:47 -0700685 mBatteryLight = lights.getLight(LightsService.LIGHT_ID_BATTERY);
686
Jeff Browna4d82042012-10-02 19:11:19 -0700687 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700688 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700689 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700690 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700691 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700692 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700693 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700694 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700695 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700696 com.android.internal.R.integer.config_notificationsBatteryLedOff);
697 }
698
699 /**
700 * Synchronize on BatteryService.
701 */
Jeff Browna4d82042012-10-02 19:11:19 -0700702 public void updateLightsLocked() {
Joe Onoratode1b3592010-10-25 20:36:47 -0700703 final int level = mBatteryLevel;
704 final int status = mBatteryStatus;
705 if (level < mLowBatteryWarningLevel) {
706 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
707 // Solid red when battery is charging
708 mBatteryLight.setColor(mBatteryLowARGB);
709 } else {
710 // Flash red when battery is low and not charging
711 mBatteryLight.setFlashing(mBatteryLowARGB, LightsService.LIGHT_FLASH_TIMED,
712 mBatteryLedOn, mBatteryLedOff);
713 }
714 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
715 || status == BatteryManager.BATTERY_STATUS_FULL) {
716 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
717 // Solid green when full or charging and nearly full
718 mBatteryLight.setColor(mBatteryFullARGB);
719 } else {
720 // Solid orange when charging and halfway full
721 mBatteryLight.setColor(mBatteryMediumARGB);
722 }
723 } else {
724 // No lights if not charging and not low
725 mBatteryLight.turnOff();
726 }
727 }
728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729}