blob: 46b671bd1419625b12d3d160db61494664fcba8a [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
Sudheer Shankafc46e9b2016-10-21 17:55:27 -070019import android.app.ActivityManagerInternal;
Dianne Hackborn14272302014-06-10 23:13:02 -070020import android.database.ContentObserver;
Dianne Hackborn8c841092013-06-24 13:46:13 -070021import android.os.BatteryStats;
Jeff Brown21392762014-06-13 19:00:36 -070022
Sudheer Shanka292637f2017-09-25 10:36:23 -070023import android.os.PowerManager;
Dianne Hackborn2e441072015-10-28 18:00:57 -070024import android.os.ResultReceiver;
Dianne Hackborn354736e2016-08-22 17:00:05 -070025import android.os.ShellCallback;
Dianne Hackborn2e441072015-10-28 18:00:57 -070026import android.os.ShellCommand;
Yifan Hong98852792017-10-12 11:35:14 -070027import com.android.internal.annotations.VisibleForTesting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import com.android.internal.app.IBatteryStats;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060029import com.android.internal.util.DumpUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import com.android.server.am.BatteryStatsService;
Adam Lesinskief2ea1f2013-12-05 16:48:06 -080031import com.android.server.lights.Light;
32import com.android.server.lights.LightsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Sudheer Shankadc589ac2016-11-10 15:30:17 -080034import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
38import android.content.pm.PackageManager;
Yifan Hong98852792017-10-12 11:35:14 -070039import android.hidl.manager.V1_0.IServiceManager;
40import android.hidl.manager.V1_0.IServiceNotification;
Yifan Hong932190b2017-10-11 11:00:51 -070041import android.hardware.health.V2_0.HealthInfo;
Yifan Hong89d55c12017-10-11 11:29:01 -070042import android.hardware.health.V2_0.IHealthInfoCallback;
Yifan Hong98852792017-10-12 11:35:14 -070043import android.hardware.health.V2_0.IHealth;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070044import android.hardware.health.V2_0.Result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070046import android.os.BatteryManagerInternal;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070047import android.os.BatteryProperty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Binder;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070049import android.os.FileUtils;
Jeff Brown605ea692012-10-05 16:33:10 -070050import android.os.Handler;
Todd Poynor26faecc2013-05-22 18:54:48 -070051import android.os.IBatteryPropertiesListener;
52import android.os.IBatteryPropertiesRegistrar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.IBinder;
Dan Egnor18e93962010-02-10 19:27:58 -080054import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.RemoteException;
56import android.os.ServiceManager;
57import android.os.SystemClock;
58import android.os.UEventObserver;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070059import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.provider.Settings;
Netta Pe2a3cd82017-01-26 18:03:51 -080061import android.service.battery.BatteryServiceDumpProto;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.util.EventLog;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070063import android.util.MutableInt;
Joe Onorato8a9b2202010-02-26 18:56:32 -080064import android.util.Slog;
Netta Pe2a3cd82017-01-26 18:03:51 -080065import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67import java.io.File;
68import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.io.FileOutputStream;
70import java.io.IOException;
71import java.io.PrintWriter;
72
Yifan Hong98852792017-10-12 11:35:14 -070073import java.util.Arrays;
74import java.util.List;
75import java.util.NoSuchElementException;
Yifan Hong89d55c12017-10-11 11:29:01 -070076import java.util.concurrent.atomic.AtomicReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
78/**
79 * <p>BatteryService monitors the charging status, and charge level of the device
80 * battery. When these values change this service broadcasts the new values
81 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
82 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
83 * BATTERY_CHANGED} action.</p>
84 * <p>The new values are stored in the Intent data and can be retrieved by
85 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
86 * following keys:</p>
87 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
88 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
89 * <p>&quot;status&quot; - String, the current charging status.<br />
90 * <p>&quot;health&quot; - String, the current battery health.<br />
91 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
92 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
93 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
94 * into an AC power adapter; 2 if plugged in via USB.</p>
95 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
96 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
97 * a degree Centigrade</p>
98 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
Jeff Brown605ea692012-10-05 16:33:10 -070099 *
100 * <p>
101 * The battery service may be called by the power manager while holding its locks so
102 * we take care to post all outcalls into the activity manager to a handler.
103 *
104 * FIXME: Ideally the power manager would perform all of its calls into the battery
105 * service asynchronously itself.
106 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 */
Jeff Brown21392762014-06-13 19:00:36 -0700108public final class BatteryService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private static final String TAG = BatteryService.class.getSimpleName();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800110
Jeff Browna4d82042012-10-02 19:11:19 -0700111 private static final boolean DEBUG = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800112
Jeff Browna4d82042012-10-02 19:11:19 -0700113 private static final int BATTERY_SCALE = 100; // battery capacity is a percentage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Yifan Hong89d55c12017-10-11 11:29:01 -0700115 private static final long HEALTH_HAL_WAIT_MS = 1000;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 // Used locally for determining when to make a last ditch effort to log
118 // discharge stats before the device dies.
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700119 private int mCriticalBatteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Jeff Sharkeyec43a6b2013-04-30 13:33:18 -0700121 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "--unplugged" };
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String DUMPSYS_DATA_PATH = "/data/system/";
124
125 // This should probably be exposed in the API, though it's not critical
126 private static final int BATTERY_PLUGGED_NONE = 0;
127
128 private final Context mContext;
129 private final IBatteryStats mBatteryStats;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700130 BinderService mBinderService;
Jeff Brown605ea692012-10-05 16:33:10 -0700131 private final Handler mHandler;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800132
Jeff Browna4d82042012-10-02 19:11:19 -0700133 private final Object mLock = new Object();
134
Yifan Hong932190b2017-10-11 11:00:51 -0700135 private HealthInfo mHealthInfo;
136 private final HealthInfo mLastHealthInfo = new HealthInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private boolean mBatteryLevelCritical;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private int mLastBatteryStatus;
139 private int mLastBatteryHealth;
140 private boolean mLastBatteryPresent;
141 private int mLastBatteryLevel;
142 private int mLastBatteryVoltage;
143 private int mLastBatteryTemperature;
144 private boolean mLastBatteryLevelCritical;
Adrian Roos76dc5a52015-07-21 16:20:36 -0700145 private int mLastMaxChargingCurrent;
Badhri Jagan Sridharanf92fcfe2015-10-27 13:59:34 -0700146 private int mLastMaxChargingVoltage;
Ruchi Kandoi6361e222016-04-07 11:28:30 -0700147 private int mLastChargeCounter;
Jeff Browna4d82042012-10-02 19:11:19 -0700148
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800149 private int mSequence = 1;
150
Jeff Browna4d82042012-10-02 19:11:19 -0700151 private int mInvalidCharger;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700152 private int mLastInvalidCharger;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400153
154 private int mLowBatteryWarningLevel;
155 private int mLowBatteryCloseWarningLevel;
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700156 private int mShutdownBatteryTemperature;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private int mPlugType;
159 private int mLastPlugType = -1; // Extra state so we can detect first run
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800160
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700161 private boolean mBatteryLevelLow;
162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 private long mDischargeStartTime;
164 private int mDischargeStartLevel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800165
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700166 private boolean mUpdatesStopped;
167
Joe Onoratode1b3592010-10-25 20:36:47 -0700168 private Led mLed;
169
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700170 private boolean mSentLowBatteryBroadcast = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800171
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700172 private ActivityManagerInternal mActivityManagerInternal;
173
Yifan Hong89d55c12017-10-11 11:29:01 -0700174 private HealthServiceWrapper mHealthServiceWrapper;
175 private HealthHalCallback mHealthHalCallback;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -0700176 private BatteryPropertiesRegistrar mBatteryPropertiesRegistrar;
Yifan Hong89d55c12017-10-11 11:29:01 -0700177
Jeff Brown21392762014-06-13 19:00:36 -0700178 public BatteryService(Context context) {
179 super(context);
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 mContext = context;
Jeff Brown605ea692012-10-05 16:33:10 -0700182 mHandler = new Handler(true /*async*/);
Jeff Brown21392762014-06-13 19:00:36 -0700183 mLed = new Led(context, getLocalService(LightsManager.class));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 mBatteryStats = BatteryStatsService.getService();
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700185 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700187 mCriticalBatteryLevel = mContext.getResources().getInteger(
188 com.android.internal.R.integer.config_criticalBatteryWarningLevel);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400189 mLowBatteryWarningLevel = mContext.getResources().getInteger(
190 com.android.internal.R.integer.config_lowBatteryWarningLevel);
Dianne Hackborn14272302014-06-10 23:13:02 -0700191 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
192 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700193 mShutdownBatteryTemperature = mContext.getResources().getInteger(
194 com.android.internal.R.integer.config_shutdownBatteryTemperature);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400195
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400196 // watch for invalid charger messages if the invalid_charger switch exists
197 if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700198 UEventObserver invalidChargerObserver = new UEventObserver() {
199 @Override
200 public void onUEvent(UEvent event) {
201 final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
202 synchronized (mLock) {
203 if (mInvalidCharger != invalidCharger) {
204 mInvalidCharger = invalidCharger;
205 }
206 }
207 }
208 };
209 invalidChargerObserver.startObserving(
Jeff Browna4d82042012-10-02 19:11:19 -0700210 "DEVPATH=/devices/virtual/switch/invalid_charger");
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400211 }
Jeff Brown21392762014-06-13 19:00:36 -0700212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Jeff Brown21392762014-06-13 19:00:36 -0700214 @Override
215 public void onStart() {
Yifan Hong89d55c12017-10-11 11:29:01 -0700216 registerHealthCallback();
Jeff Brown21392762014-06-13 19:00:36 -0700217
Dianne Hackborn2e441072015-10-28 18:00:57 -0700218 mBinderService = new BinderService();
219 publishBinderService("battery", mBinderService);
Yifan Hong1fd86f4c2017-10-09 16:50:33 -0700220 mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
221 publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
Jeff Brown21392762014-06-13 19:00:36 -0700222 publishLocalService(BatteryManagerInternal.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 }
224
Jeff Brown21392762014-06-13 19:00:36 -0700225 @Override
226 public void onBootPhase(int phase) {
227 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
228 // check our power situation now that it is safe to display the shutdown dialog.
229 synchronized (mLock) {
230 ContentObserver obs = new ContentObserver(mHandler) {
231 @Override
232 public void onChange(boolean selfChange) {
233 synchronized (mLock) {
234 updateBatteryWarningLevelLocked();
235 }
Dianne Hackborn14272302014-06-10 23:13:02 -0700236 }
Jeff Brown21392762014-06-13 19:00:36 -0700237 };
238 final ContentResolver resolver = mContext.getContentResolver();
239 resolver.registerContentObserver(Settings.Global.getUriFor(
240 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
241 false, obs, UserHandle.USER_ALL);
242 updateBatteryWarningLevelLocked();
243 }
Jeff Browna4d82042012-10-02 19:11:19 -0700244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 }
246
Yifan Hong89d55c12017-10-11 11:29:01 -0700247 private void registerHealthCallback() {
248 mHealthServiceWrapper = new HealthServiceWrapper();
249 mHealthHalCallback = new HealthHalCallback();
250 // IHealth is lazily retrieved.
251 try {
252 mHealthServiceWrapper.init(mHealthHalCallback,
253 new HealthServiceWrapper.IServiceManagerSupplier() {},
254 new HealthServiceWrapper.IHealthSupplier() {});
255 } catch (RemoteException | NoSuchElementException ex) {
256 Slog.w(TAG, "health: cannot register callback. "
257 + "BatteryService will be started with dummy values. Reason: "
258 + ex.getClass().getSimpleName() + ": " + ex.getMessage());
259 update(new HealthInfo());
260 return;
261 }
262
263 // init register for new service notifications, and IServiceManager should return the
264 // existing service in a near future. Wait for this.update() to instantiate
265 // the initial mHealthInfo.
266 long timeWaited = 0;
267 synchronized (mLock) {
268 long beforeWait = SystemClock.uptimeMillis();
269 while (mHealthInfo == null &&
270 (timeWaited = SystemClock.uptimeMillis() - beforeWait) < HEALTH_HAL_WAIT_MS) {
271 try {
272 mLock.wait(HEALTH_HAL_WAIT_MS - timeWaited);
273 } catch (InterruptedException ex) {
274 break;
275 }
276 }
277 if (mHealthInfo == null) {
278 Slog.w(TAG, "health: Waited " + timeWaited + "ms for callbacks but received "
279 + "nothing. BatteryService will be started with dummy values.");
280 update(new HealthInfo());
281 return;
282 }
283 }
284
285 if (DEBUG) {
286 Slog.d(TAG, "health: Waited " + timeWaited + "ms and received the update.");
287 }
288 }
289
Jeff Brown21392762014-06-13 19:00:36 -0700290 private void updateBatteryWarningLevelLocked() {
Dianne Hackborn14272302014-06-10 23:13:02 -0700291 final ContentResolver resolver = mContext.getContentResolver();
292 int defWarnLevel = mContext.getResources().getInteger(
293 com.android.internal.R.integer.config_lowBatteryWarningLevel);
294 mLowBatteryWarningLevel = Settings.Global.getInt(resolver,
295 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, defWarnLevel);
296 if (mLowBatteryWarningLevel == 0) {
297 mLowBatteryWarningLevel = defWarnLevel;
298 }
299 if (mLowBatteryWarningLevel < mCriticalBatteryLevel) {
300 mLowBatteryWarningLevel = mCriticalBatteryLevel;
301 }
302 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
303 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
304 processValuesLocked(true);
305 }
306
Jeff Browna4d82042012-10-02 19:11:19 -0700307 private boolean isPoweredLocked(int plugTypeSet) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 // assume we are powered if battery state is unknown so
309 // the "stay on while plugged in" option will work.
Yifan Hong932190b2017-10-11 11:00:51 -0700310 if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 return true;
312 }
Yifan Hong932190b2017-10-11 11:00:51 -0700313 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_AC) != 0 && mHealthInfo.legacy.chargerAcOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700314 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 }
Yifan Hong932190b2017-10-11 11:00:51 -0700316 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_USB) != 0 && mHealthInfo.legacy.chargerUsbOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700317 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
Yifan Hong932190b2017-10-11 11:00:51 -0700319 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0 && mHealthInfo.legacy.chargerWirelessOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700320 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
Jeff Browna4d82042012-10-02 19:11:19 -0700322 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
324
Jeff Brown21392762014-06-13 19:00:36 -0700325 private boolean shouldSendBatteryLowLocked() {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700326 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
327 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
328
329 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
330 * - is just un-plugged (previously was plugged) and battery level is
331 * less than or equal to WARNING, or
332 * - is not plugged and battery level falls to WARNING boundary
333 * (becomes <= mLowBatteryWarningLevel).
334 */
335 return !plugged
Yifan Hong932190b2017-10-11 11:00:51 -0700336 && mHealthInfo.legacy.batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
337 && mHealthInfo.legacy.batteryLevel <= mLowBatteryWarningLevel
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700338 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
339 }
340
Jeff Browna4d82042012-10-02 19:11:19 -0700341 private void shutdownIfNoPowerLocked() {
Mike Lockwood07a500f2009-08-12 09:56:44 -0400342 // shut down gracefully if our battery is critically low and we are not powered.
343 // wait until the system has booted before attempting to display the shutdown dialog.
Yifan Hong932190b2017-10-11 11:00:51 -0700344 if (mHealthInfo.legacy.batteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
Jeff Brown605ea692012-10-05 16:33:10 -0700345 mHandler.post(new Runnable() {
346 @Override
347 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700348 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700349 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
350 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700351 intent.putExtra(Intent.EXTRA_REASON,
352 PowerManager.SHUTDOWN_LOW_BATTERY);
Jeff Brown605ea692012-10-05 16:33:10 -0700353 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
354 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
355 }
356 }
357 });
Mike Lockwood07a500f2009-08-12 09:56:44 -0400358 }
359 }
360
Jeff Browna4d82042012-10-02 19:11:19 -0700361 private void shutdownIfOverTempLocked() {
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700362 // shut down gracefully if temperature is too high (> 68.0C by default)
363 // wait until the system has booted before attempting to display the
364 // shutdown dialog.
Yifan Hong932190b2017-10-11 11:00:51 -0700365 if (mHealthInfo.legacy.batteryTemperature > mShutdownBatteryTemperature) {
Jeff Brown605ea692012-10-05 16:33:10 -0700366 mHandler.post(new Runnable() {
367 @Override
368 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700369 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700370 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
371 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700372 intent.putExtra(Intent.EXTRA_REASON,
373 PowerManager.SHUTDOWN_BATTERY_THERMAL_STATE);
Jeff Brown605ea692012-10-05 16:33:10 -0700374 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
375 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
376 }
377 }
378 });
Eric Olsen6a362a92010-03-26 15:38:41 -0700379 }
380 }
381
Yifan Hong89d55c12017-10-11 11:29:01 -0700382 private void update(HealthInfo info) {
Todd Poynor26faecc2013-05-22 18:54:48 -0700383 synchronized (mLock) {
384 if (!mUpdatesStopped) {
Yifan Hong89d55c12017-10-11 11:29:01 -0700385 mHealthInfo = info;
Todd Poynor26faecc2013-05-22 18:54:48 -0700386 // Process the new values.
Dianne Hackborn14272302014-06-10 23:13:02 -0700387 processValuesLocked(false);
Yifan Hong89d55c12017-10-11 11:29:01 -0700388 mLock.notifyAll(); // for any waiters on new info
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800389 } else {
Yifan Hong89d55c12017-10-11 11:29:01 -0700390 copy(mLastHealthInfo, info);
Todd Poynor26faecc2013-05-22 18:54:48 -0700391 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700392 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394
Yifan Hong932190b2017-10-11 11:00:51 -0700395 private static void copy(HealthInfo dst, HealthInfo src) {
396 dst.legacy.chargerAcOnline = src.legacy.chargerAcOnline;
397 dst.legacy.chargerUsbOnline = src.legacy.chargerUsbOnline;
398 dst.legacy.chargerWirelessOnline = src.legacy.chargerWirelessOnline;
399 dst.legacy.maxChargingCurrent = src.legacy.maxChargingCurrent;
400 dst.legacy.maxChargingVoltage = src.legacy.maxChargingVoltage;
401 dst.legacy.batteryStatus = src.legacy.batteryStatus;
402 dst.legacy.batteryHealth = src.legacy.batteryHealth;
403 dst.legacy.batteryPresent = src.legacy.batteryPresent;
404 dst.legacy.batteryLevel = src.legacy.batteryLevel;
405 dst.legacy.batteryVoltage = src.legacy.batteryVoltage;
406 dst.legacy.batteryTemperature = src.legacy.batteryTemperature;
407 dst.legacy.batteryCurrent = src.legacy.batteryCurrent;
408 dst.legacy.batteryCycleCount = src.legacy.batteryCycleCount;
409 dst.legacy.batteryFullCharge = src.legacy.batteryFullCharge;
410 dst.legacy.batteryChargeCounter = src.legacy.batteryChargeCounter;
411 dst.legacy.batteryTechnology = src.legacy.batteryTechnology;
412 dst.batteryCurrentAverage = src.batteryCurrentAverage;
413 dst.batteryCapacity = src.batteryCapacity;
414 dst.energyCounter = src.energyCounter;
415 }
416
Dianne Hackborn14272302014-06-10 23:13:02 -0700417 private void processValuesLocked(boolean force) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700418 boolean logOutlier = false;
419 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700420
Yifan Hong932190b2017-10-11 11:00:51 -0700421 mBatteryLevelCritical = (mHealthInfo.legacy.batteryLevel <= mCriticalBatteryLevel);
422 if (mHealthInfo.legacy.chargerAcOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
Yifan Hong932190b2017-10-11 11:00:51 -0700424 } else if (mHealthInfo.legacy.chargerUsbOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Yifan Hong932190b2017-10-11 11:00:51 -0700426 } else if (mHealthInfo.legacy.chargerWirelessOnline) {
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700427 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 } else {
429 mPlugType = BATTERY_PLUGGED_NONE;
430 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700431
Jeff Browna4d82042012-10-02 19:11:19 -0700432 if (DEBUG) {
433 Slog.d(TAG, "Processing new values: "
Yifan Hong932190b2017-10-11 11:00:51 -0700434 + "info=" + mHealthInfo
Jeff Browna4d82042012-10-02 19:11:19 -0700435 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
436 + ", mPlugType=" + mPlugType);
437 }
438
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700439 // Let the battery stats keep track of the current level.
440 try {
Yifan Hong932190b2017-10-11 11:00:51 -0700441 mBatteryStats.setBatteryState(mHealthInfo.legacy.batteryStatus, mHealthInfo.legacy.batteryHealth,
442 mPlugType, mHealthInfo.legacy.batteryLevel, mHealthInfo.legacy.batteryTemperature,
443 mHealthInfo.legacy.batteryVoltage, mHealthInfo.legacy.batteryChargeCounter,
444 mHealthInfo.legacy.batteryFullCharge);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700445 } catch (RemoteException e) {
446 // Should never happen.
447 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700448
Jeff Browna4d82042012-10-02 19:11:19 -0700449 shutdownIfNoPowerLocked();
450 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700451
Yifan Hong932190b2017-10-11 11:00:51 -0700452 if (force || (mHealthInfo.legacy.batteryStatus != mLastBatteryStatus ||
453 mHealthInfo.legacy.batteryHealth != mLastBatteryHealth ||
454 mHealthInfo.legacy.batteryPresent != mLastBatteryPresent ||
455 mHealthInfo.legacy.batteryLevel != mLastBatteryLevel ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 mPlugType != mLastPlugType ||
Yifan Hong932190b2017-10-11 11:00:51 -0700457 mHealthInfo.legacy.batteryVoltage != mLastBatteryVoltage ||
458 mHealthInfo.legacy.batteryTemperature != mLastBatteryTemperature ||
459 mHealthInfo.legacy.maxChargingCurrent != mLastMaxChargingCurrent ||
460 mHealthInfo.legacy.maxChargingVoltage != mLastMaxChargingVoltage ||
461 mHealthInfo.legacy.batteryChargeCounter != mLastChargeCounter ||
Dianne Hackborn14272302014-06-10 23:13:02 -0700462 mInvalidCharger != mLastInvalidCharger)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 if (mPlugType != mLastPlugType) {
465 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
466 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 // There's no value in this data unless we've discharged at least once and the
469 // battery level has changed; so don't log until it does.
Yifan Hong932190b2017-10-11 11:00:51 -0700470 if (mDischargeStartTime != 0 && mDischargeStartLevel != mHealthInfo.legacy.batteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700471 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
472 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800473 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
Yifan Hong932190b2017-10-11 11:00:51 -0700474 mDischargeStartLevel, mHealthInfo.legacy.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800476 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
479 // charging -> discharging or we just powered up
480 mDischargeStartTime = SystemClock.elapsedRealtime();
Yifan Hong932190b2017-10-11 11:00:51 -0700481 mDischargeStartLevel = mHealthInfo.legacy.batteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 }
483 }
Yifan Hong932190b2017-10-11 11:00:51 -0700484 if (mHealthInfo.legacy.batteryStatus != mLastBatteryStatus ||
485 mHealthInfo.legacy.batteryHealth != mLastBatteryHealth ||
486 mHealthInfo.legacy.batteryPresent != mLastBatteryPresent ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800488 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
Yifan Hong932190b2017-10-11 11:00:51 -0700489 mHealthInfo.legacy.batteryStatus, mHealthInfo.legacy.batteryHealth, mHealthInfo.legacy.batteryPresent ? 1 : 0,
490 mPlugType, mHealthInfo.legacy.batteryTechnology);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 }
Yifan Hong932190b2017-10-11 11:00:51 -0700492 if (mHealthInfo.legacy.batteryLevel != mLastBatteryLevel) {
Dianne Hackborncf1171642013-07-12 17:26:02 -0700493 // Don't do this just from voltage or temperature changes, that is
494 // too noisy.
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800495 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
Yifan Hong932190b2017-10-11 11:00:51 -0700496 mHealthInfo.legacy.batteryLevel, mHealthInfo.legacy.batteryVoltage, mHealthInfo.legacy.batteryTemperature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
498 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
499 mPlugType == BATTERY_PLUGGED_NONE) {
500 // We want to make sure we log discharge cycle outliers
501 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700502 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
503 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800505
Dianne Hackborn14272302014-06-10 23:13:02 -0700506 if (!mBatteryLevelLow) {
507 // Should we now switch in to low battery mode?
508 if (mPlugType == BATTERY_PLUGGED_NONE
Yifan Hong932190b2017-10-11 11:00:51 -0700509 && mHealthInfo.legacy.batteryLevel <= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700510 mBatteryLevelLow = true;
511 }
512 } else {
513 // Should we now switch out of low battery mode?
514 if (mPlugType != BATTERY_PLUGGED_NONE) {
515 mBatteryLevelLow = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700516 } else if (mHealthInfo.legacy.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700517 mBatteryLevelLow = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700518 } else if (force && mHealthInfo.legacy.batteryLevel >= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700519 // If being forced, the previous state doesn't matter, we will just
520 // absolutely check to see if we are now above the warning level.
521 mBatteryLevelLow = false;
522 }
523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800524
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800525 mSequence++;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800526
Christopher Tate06ba5542009-04-09 16:03:56 -0700527 // Separate broadcast is sent for power connected / not connected
528 // since the standard intent will not wake any applications and some
529 // applications may want to have smart behavior based on this.
530 if (mPlugType != 0 && mLastPlugType == 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800531 final Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
532 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
533 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700534 mHandler.post(new Runnable() {
535 @Override
536 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700537 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
538 }
539 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700540 }
541 else if (mPlugType == 0 && mLastPlugType != 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800542 final Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
543 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
544 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700545 mHandler.post(new Runnable() {
546 @Override
547 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700548 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
549 }
550 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700551 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200552
Dianne Hackborn14272302014-06-10 23:13:02 -0700553 if (shouldSendBatteryLowLocked()) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700554 mSentLowBatteryBroadcast = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800555 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
556 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
557 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700558 mHandler.post(new Runnable() {
559 @Override
560 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700561 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
562 }
563 });
Dianne Hackborn532ea262017-03-17 17:50:55 -0700564 } else if (mSentLowBatteryBroadcast &&
Yifan Hong932190b2017-10-11 11:00:51 -0700565 mHealthInfo.legacy.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700566 mSentLowBatteryBroadcast = false;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800567 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
568 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
569 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700570 mHandler.post(new Runnable() {
571 @Override
572 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700573 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
574 }
575 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800577
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800578 // We are doing this after sending the above broadcasts, so anything processing
579 // them will get the new sequence number at that point. (See for example how testing
580 // of JobScheduler's BatteryController works.)
581 sendIntentLocked();
582
Joe Onoratode1b3592010-10-25 20:36:47 -0700583 // Update the battery LED
584 mLed.updateLightsLocked();
585
The Android Open Source Project10592532009-03-18 17:39:46 -0700586 // This needs to be done after sendIntent() so that we get the lastest battery stats.
587 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700588 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700589 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800590
Yifan Hong932190b2017-10-11 11:00:51 -0700591 mLastBatteryStatus = mHealthInfo.legacy.batteryStatus;
592 mLastBatteryHealth = mHealthInfo.legacy.batteryHealth;
593 mLastBatteryPresent = mHealthInfo.legacy.batteryPresent;
594 mLastBatteryLevel = mHealthInfo.legacy.batteryLevel;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700595 mLastPlugType = mPlugType;
Yifan Hong932190b2017-10-11 11:00:51 -0700596 mLastBatteryVoltage = mHealthInfo.legacy.batteryVoltage;
597 mLastBatteryTemperature = mHealthInfo.legacy.batteryTemperature;
598 mLastMaxChargingCurrent = mHealthInfo.legacy.maxChargingCurrent;
599 mLastMaxChargingVoltage = mHealthInfo.legacy.maxChargingVoltage;
600 mLastChargeCounter = mHealthInfo.legacy.batteryChargeCounter;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700601 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400602 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
604 }
605
Jeff Browna4d82042012-10-02 19:11:19 -0700606 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700608 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800609 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
610 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800611
Yifan Hong932190b2017-10-11 11:00:51 -0700612 int icon = getIconLocked(mHealthInfo.legacy.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800614 intent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Yifan Hong932190b2017-10-11 11:00:51 -0700615 intent.putExtra(BatteryManager.EXTRA_STATUS, mHealthInfo.legacy.batteryStatus);
616 intent.putExtra(BatteryManager.EXTRA_HEALTH, mHealthInfo.legacy.batteryHealth);
617 intent.putExtra(BatteryManager.EXTRA_PRESENT, mHealthInfo.legacy.batteryPresent);
618 intent.putExtra(BatteryManager.EXTRA_LEVEL, mHealthInfo.legacy.batteryLevel);
Dianne Hackbornedd93162009-09-19 14:03:05 -0700619 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
620 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
621 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
Yifan Hong932190b2017-10-11 11:00:51 -0700622 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mHealthInfo.legacy.batteryVoltage);
623 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mHealthInfo.legacy.batteryTemperature);
624 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mHealthInfo.legacy.batteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400625 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
Yifan Hong932190b2017-10-11 11:00:51 -0700626 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mHealthInfo.legacy.maxChargingCurrent);
627 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE, mHealthInfo.legacy.maxChargingVoltage);
628 intent.putExtra(BatteryManager.EXTRA_CHARGE_COUNTER, mHealthInfo.legacy.batteryChargeCounter);
Jeff Browna4d82042012-10-02 19:11:19 -0700629 if (DEBUG) {
Yifan Hong932190b2017-10-11 11:00:51 -0700630 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. scale:" + BATTERY_SCALE
631 + ", info:" + mHealthInfo.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633
Jeff Brown605ea692012-10-05 16:33:10 -0700634 mHandler.post(new Runnable() {
635 @Override
636 public void run() {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800637 ActivityManager.broadcastStickyIntent(intent, UserHandle.USER_ALL);
Jeff Brown605ea692012-10-05 16:33:10 -0700638 }
639 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 }
641
Jeff Browna4d82042012-10-02 19:11:19 -0700642 private void logBatteryStatsLocked() {
Dianne Hackborn8c841092013-06-24 13:46:13 -0700643 IBinder batteryInfoService = ServiceManager.getService(BatteryStats.SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800644 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645
Dan Egnor18e93962010-02-10 19:27:58 -0800646 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
647 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
648
649 File dumpFile = null;
650 FileOutputStream dumpStream = null;
651 try {
652 // dump the service to a file
Dianne Hackborn8c841092013-06-24 13:46:13 -0700653 dumpFile = new File(DUMPSYS_DATA_PATH + BatteryStats.SERVICE_NAME + ".dump");
Dan Egnor18e93962010-02-10 19:27:58 -0800654 dumpStream = new FileOutputStream(dumpFile);
655 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700656 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800657
658 // add dump file to drop box
659 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
660 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800661 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800662 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800663 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800664 } finally {
665 // make sure we clean up
666 if (dumpStream != null) {
667 try {
668 dumpStream.close();
669 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800670 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
Dan Egnor18e93962010-02-10 19:27:58 -0800672 }
673 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800675 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
677 }
678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800679
Jeff Browna4d82042012-10-02 19:11:19 -0700680 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700682 String dischargeThresholdString = Settings.Global.getString(cr,
683 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
684 String durationThresholdString = Settings.Global.getString(cr,
685 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 if (dischargeThresholdString != null && durationThresholdString != null) {
688 try {
689 long durationThreshold = Long.parseLong(durationThresholdString);
690 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800691 if (duration <= durationThreshold &&
Yifan Hong932190b2017-10-11 11:00:51 -0700692 mDischargeStartLevel - mHealthInfo.legacy.batteryLevel >= dischargeThreshold) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700694 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 }
Jeff Browna4d82042012-10-02 19:11:19 -0700696 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700698 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
Yifan Hong932190b2017-10-11 11:00:51 -0700699 (mDischargeStartLevel - mHealthInfo.legacy.batteryLevel));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800701 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 durationThresholdString + " or " + dischargeThresholdString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704 }
705 }
706
Jeff Browna4d82042012-10-02 19:11:19 -0700707 private int getIconLocked(int level) {
Yifan Hong932190b2017-10-11 11:00:51 -0700708 if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 return com.android.internal.R.drawable.stat_sys_battery_charge;
Yifan Hong932190b2017-10-11 11:00:51 -0700710 } else if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 return com.android.internal.R.drawable.stat_sys_battery;
Yifan Hong932190b2017-10-11 11:00:51 -0700712 } else if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
713 || mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700714 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
Yifan Hong932190b2017-10-11 11:00:51 -0700715 && mHealthInfo.legacy.batteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800716 return com.android.internal.R.drawable.stat_sys_battery_charge;
717 } else {
718 return com.android.internal.R.drawable.stat_sys_battery;
719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 } else {
721 return com.android.internal.R.drawable.stat_sys_battery_unknown;
722 }
723 }
724
Dianne Hackborn2e441072015-10-28 18:00:57 -0700725 class Shell extends ShellCommand {
726 @Override
727 public int onCommand(String cmd) {
728 return onShellCommand(this, cmd);
729 }
730
731 @Override
732 public void onHelp() {
733 PrintWriter pw = getOutPrintWriter();
734 dumpHelp(pw);
735 }
736 }
737
738 static void dumpHelp(PrintWriter pw) {
739 pw.println("Battery service (battery) commands:");
740 pw.println(" help");
741 pw.println(" Print this help text.");
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700742 pw.println(" set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700743 pw.println(" Force a battery property value, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800744 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
745 pw.println(" unplug [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700746 pw.println(" Force battery unplugged, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800747 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
748 pw.println(" reset [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700749 pw.println(" Unfreeze battery state, returning to current hardware values.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800750 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
751 }
752
753 static final int OPTION_FORCE_UPDATE = 1<<0;
754
755 int parseOptions(Shell shell) {
756 String opt;
757 int opts = 0;
758 while ((opt = shell.getNextOption()) != null) {
759 if ("-f".equals(opt)) {
760 opts |= OPTION_FORCE_UPDATE;
761 }
762 }
763 return opts;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700764 }
765
766 int onShellCommand(Shell shell, String cmd) {
767 if (cmd == null) {
768 return shell.handleDefaultCommands(cmd);
769 }
770 PrintWriter pw = shell.getOutPrintWriter();
771 switch (cmd) {
772 case "unplug": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800773 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700774 getContext().enforceCallingOrSelfPermission(
775 android.Manifest.permission.DEVICE_POWER, null);
776 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700777 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700778 }
Yifan Hong932190b2017-10-11 11:00:51 -0700779 mHealthInfo.legacy.chargerAcOnline = false;
780 mHealthInfo.legacy.chargerUsbOnline = false;
781 mHealthInfo.legacy.chargerWirelessOnline = false;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700782 long ident = Binder.clearCallingIdentity();
783 try {
784 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800785 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700786 } finally {
787 Binder.restoreCallingIdentity(ident);
788 }
789 } break;
790 case "set": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800791 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700792 getContext().enforceCallingOrSelfPermission(
793 android.Manifest.permission.DEVICE_POWER, null);
794 final String key = shell.getNextArg();
795 if (key == null) {
796 pw.println("No property specified");
797 return -1;
798
799 }
800 final String value = shell.getNextArg();
801 if (value == null) {
802 pw.println("No value specified");
803 return -1;
804
805 }
806 try {
807 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700808 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700809 }
810 boolean update = true;
811 switch (key) {
Christopher Tate630d98b2017-03-07 14:12:26 -0800812 case "present":
Yifan Hong932190b2017-10-11 11:00:51 -0700813 mHealthInfo.legacy.batteryPresent = Integer.parseInt(value) != 0;
Christopher Tate630d98b2017-03-07 14:12:26 -0800814 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700815 case "ac":
Yifan Hong932190b2017-10-11 11:00:51 -0700816 mHealthInfo.legacy.chargerAcOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700817 break;
818 case "usb":
Yifan Hong932190b2017-10-11 11:00:51 -0700819 mHealthInfo.legacy.chargerUsbOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700820 break;
821 case "wireless":
Yifan Hong932190b2017-10-11 11:00:51 -0700822 mHealthInfo.legacy.chargerWirelessOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700823 break;
824 case "status":
Yifan Hong932190b2017-10-11 11:00:51 -0700825 mHealthInfo.legacy.batteryStatus = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700826 break;
827 case "level":
Yifan Hong932190b2017-10-11 11:00:51 -0700828 mHealthInfo.legacy.batteryLevel = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700829 break;
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700830 case "temp":
Yifan Hong932190b2017-10-11 11:00:51 -0700831 mHealthInfo.legacy.batteryTemperature = Integer.parseInt(value);
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700832 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700833 case "invalid":
834 mInvalidCharger = Integer.parseInt(value);
835 break;
836 default:
837 pw.println("Unknown set option: " + key);
838 update = false;
839 break;
840 }
841 if (update) {
842 long ident = Binder.clearCallingIdentity();
843 try {
844 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800845 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700846 } finally {
847 Binder.restoreCallingIdentity(ident);
848 }
849 }
850 } catch (NumberFormatException ex) {
851 pw.println("Bad value: " + value);
852 return -1;
853 }
854 } break;
855 case "reset": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800856 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700857 getContext().enforceCallingOrSelfPermission(
858 android.Manifest.permission.DEVICE_POWER, null);
859 long ident = Binder.clearCallingIdentity();
860 try {
861 if (mUpdatesStopped) {
862 mUpdatesStopped = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700863 copy(mHealthInfo, mLastHealthInfo);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800864 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700865 }
866 } finally {
867 Binder.restoreCallingIdentity(ident);
868 }
869 } break;
870 default:
871 return shell.handleDefaultCommands(cmd);
872 }
873 return 0;
874 }
875
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800876 private void processValuesFromShellLocked(PrintWriter pw, int opts) {
877 processValuesLocked((opts & OPTION_FORCE_UPDATE) != 0);
878 if ((opts & OPTION_FORCE_UPDATE) != 0) {
879 pw.println(mSequence);
880 }
881 }
882
Dianne Hackborn2e441072015-10-28 18:00:57 -0700883 private void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna4d82042012-10-02 19:11:19 -0700884 synchronized (mLock) {
885 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700886 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700887 if (mUpdatesStopped) {
888 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
889 }
Yifan Hong932190b2017-10-11 11:00:51 -0700890 pw.println(" AC powered: " + mHealthInfo.legacy.chargerAcOnline);
891 pw.println(" USB powered: " + mHealthInfo.legacy.chargerUsbOnline);
892 pw.println(" Wireless powered: " + mHealthInfo.legacy.chargerWirelessOnline);
893 pw.println(" Max charging current: " + mHealthInfo.legacy.maxChargingCurrent);
894 pw.println(" Max charging voltage: " + mHealthInfo.legacy.maxChargingVoltage);
895 pw.println(" Charge counter: " + mHealthInfo.legacy.batteryChargeCounter);
896 pw.println(" status: " + mHealthInfo.legacy.batteryStatus);
897 pw.println(" health: " + mHealthInfo.legacy.batteryHealth);
898 pw.println(" present: " + mHealthInfo.legacy.batteryPresent);
899 pw.println(" level: " + mHealthInfo.legacy.batteryLevel);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700900 pw.println(" scale: " + BATTERY_SCALE);
Yifan Hong932190b2017-10-11 11:00:51 -0700901 pw.println(" voltage: " + mHealthInfo.legacy.batteryVoltage);
902 pw.println(" temperature: " + mHealthInfo.legacy.batteryTemperature);
903 pw.println(" technology: " + mHealthInfo.legacy.batteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700904 } else {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700905 Shell shell = new Shell();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700906 shell.exec(mBinderService, null, fd, null, args, null, new ResultReceiver(null));
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700910
Netta Pe2a3cd82017-01-26 18:03:51 -0800911 private void dumpProto(FileDescriptor fd) {
912 final ProtoOutputStream proto = new ProtoOutputStream(fd);
913
914 synchronized (mLock) {
915 proto.write(BatteryServiceDumpProto.ARE_UPDATES_STOPPED, mUpdatesStopped);
916 int batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_NONE;
Yifan Hong932190b2017-10-11 11:00:51 -0700917 if (mHealthInfo.legacy.chargerAcOnline) {
Netta Pe2a3cd82017-01-26 18:03:51 -0800918 batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_AC;
Yifan Hong932190b2017-10-11 11:00:51 -0700919 } else if (mHealthInfo.legacy.chargerUsbOnline) {
Netta Pe2a3cd82017-01-26 18:03:51 -0800920 batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_USB;
Yifan Hong932190b2017-10-11 11:00:51 -0700921 } else if (mHealthInfo.legacy.chargerWirelessOnline) {
Netta Pe2a3cd82017-01-26 18:03:51 -0800922 batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_WIRELESS;
923 }
924 proto.write(BatteryServiceDumpProto.PLUGGED, batteryPluggedValue);
Yifan Hong932190b2017-10-11 11:00:51 -0700925 proto.write(BatteryServiceDumpProto.MAX_CHARGING_CURRENT, mHealthInfo.legacy.maxChargingCurrent);
926 proto.write(BatteryServiceDumpProto.MAX_CHARGING_VOLTAGE, mHealthInfo.legacy.maxChargingVoltage);
927 proto.write(BatteryServiceDumpProto.CHARGE_COUNTER, mHealthInfo.legacy.batteryChargeCounter);
928 proto.write(BatteryServiceDumpProto.STATUS, mHealthInfo.legacy.batteryStatus);
929 proto.write(BatteryServiceDumpProto.HEALTH, mHealthInfo.legacy.batteryHealth);
930 proto.write(BatteryServiceDumpProto.IS_PRESENT, mHealthInfo.legacy.batteryPresent);
931 proto.write(BatteryServiceDumpProto.LEVEL, mHealthInfo.legacy.batteryLevel);
Netta Pe2a3cd82017-01-26 18:03:51 -0800932 proto.write(BatteryServiceDumpProto.SCALE, BATTERY_SCALE);
Yifan Hong932190b2017-10-11 11:00:51 -0700933 proto.write(BatteryServiceDumpProto.VOLTAGE, mHealthInfo.legacy.batteryVoltage);
934 proto.write(BatteryServiceDumpProto.TEMPERATURE, mHealthInfo.legacy.batteryTemperature);
935 proto.write(BatteryServiceDumpProto.TECHNOLOGY, mHealthInfo.legacy.batteryTechnology);
Netta Pe2a3cd82017-01-26 18:03:51 -0800936 }
937 proto.flush();
938 }
939
Jeff Browna4d82042012-10-02 19:11:19 -0700940 private final class Led {
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800941 private final Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700942
Jeff Browna4d82042012-10-02 19:11:19 -0700943 private final int mBatteryLowARGB;
944 private final int mBatteryMediumARGB;
945 private final int mBatteryFullARGB;
946 private final int mBatteryLedOn;
947 private final int mBatteryLedOff;
948
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800949 public Led(Context context, LightsManager lights) {
950 mBatteryLight = lights.getLight(LightsManager.LIGHT_ID_BATTERY);
Joe Onoratode1b3592010-10-25 20:36:47 -0700951
Jeff Browna4d82042012-10-02 19:11:19 -0700952 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700953 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700954 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700955 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700956 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700957 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700958 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700959 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700960 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700961 com.android.internal.R.integer.config_notificationsBatteryLedOff);
962 }
963
964 /**
965 * Synchronize on BatteryService.
966 */
Jeff Browna4d82042012-10-02 19:11:19 -0700967 public void updateLightsLocked() {
Yifan Hong932190b2017-10-11 11:00:51 -0700968 final int level = mHealthInfo.legacy.batteryLevel;
969 final int status = mHealthInfo.legacy.batteryStatus;
Joe Onoratode1b3592010-10-25 20:36:47 -0700970 if (level < mLowBatteryWarningLevel) {
971 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
972 // Solid red when battery is charging
973 mBatteryLight.setColor(mBatteryLowARGB);
974 } else {
975 // Flash red when battery is low and not charging
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800976 mBatteryLight.setFlashing(mBatteryLowARGB, Light.LIGHT_FLASH_TIMED,
Joe Onoratode1b3592010-10-25 20:36:47 -0700977 mBatteryLedOn, mBatteryLedOff);
978 }
979 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
980 || status == BatteryManager.BATTERY_STATUS_FULL) {
981 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
982 // Solid green when full or charging and nearly full
983 mBatteryLight.setColor(mBatteryFullARGB);
984 } else {
985 // Solid orange when charging and halfway full
986 mBatteryLight.setColor(mBatteryMediumARGB);
987 }
988 } else {
989 // No lights if not charging and not low
990 mBatteryLight.turnOff();
991 }
992 }
993 }
Todd Poynor26faecc2013-05-22 18:54:48 -0700994
Yifan Hong89d55c12017-10-11 11:29:01 -0700995 private final class HealthHalCallback extends IHealthInfoCallback.Stub
996 implements HealthServiceWrapper.Callback {
997 @Override public void healthInfoChanged(HealthInfo props) {
998 BatteryService.this.update(props);
999 }
1000 // on new service registered
1001 @Override public void onRegistration(IHealth oldService, IHealth newService,
1002 String instance) {
1003 if (newService == null) return;
1004
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001005 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001006 if (oldService != null) {
1007 int r = oldService.unregisterCallback(this);
1008 if (r != Result.SUCCESS) {
1009 Slog.w(TAG, "health: cannot unregister previous callback: " +
1010 Result.toString(r));
1011 }
1012 }
1013 } catch (RemoteException ex) {
1014 Slog.w(TAG, "health: cannot unregister previous callback (transaction error): "
1015 + ex.getMessage());
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001016 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001017
1018 try {
1019 int r = newService.registerCallback(this);
1020 if (r != Result.SUCCESS) {
1021 Slog.w(TAG, "health: cannot register callback: " + Result.toString(r));
1022 return;
1023 }
1024 // registerCallback does NOT guarantee that update is called
1025 // immediately, so request a manual update here.
1026 newService.update();
1027 } catch (RemoteException ex) {
1028 Slog.e(TAG, "health: cannot register callback (transaction error): "
1029 + ex.getMessage());
1030 }
1031 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001032 }
Jeff Brown21392762014-06-13 19:00:36 -07001033
1034 private final class BinderService extends Binder {
Dianne Hackborn2e441072015-10-28 18:00:57 -07001035 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001036 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown21392762014-06-13 19:00:36 -07001037
Netta Pe2a3cd82017-01-26 18:03:51 -08001038 if (args.length > 0 && "--proto".equals(args[0])) {
1039 dumpProto(fd);
1040 } else {
1041 dumpInternal(fd, pw, args);
1042 }
Dianne Hackborn2e441072015-10-28 18:00:57 -07001043 }
1044
1045 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001046 FileDescriptor err, String[] args, ShellCallback callback,
1047 ResultReceiver resultReceiver) {
1048 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Jeff Brown21392762014-06-13 19:00:36 -07001049 }
1050 }
1051
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001052 // Reduced IBatteryPropertiesRegistrar that only implements getProperty for usage
1053 // in BatteryManager.
1054 private final class BatteryPropertiesRegistrar extends IBatteryPropertiesRegistrar.Stub {
1055 public void registerListener(IBatteryPropertiesListener listener) {
1056 Slog.e(TAG, "health: must not call registerListener on battery properties");
1057 }
1058 public void unregisterListener(IBatteryPropertiesListener listener) {
1059 Slog.e(TAG, "health: must not call unregisterListener on battery properties");
1060 }
1061 public int getProperty(int id, final BatteryProperty prop) throws RemoteException {
1062 IHealth service = mHealthServiceWrapper.getLastService();
1063 final MutableInt outResult = new MutableInt(Result.NOT_SUPPORTED);
1064 switch(id) {
1065 case BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER:
1066 service.getChargeCounter((int result, int value) -> {
1067 outResult.value = result;
1068 if (result == Result.SUCCESS) prop.setLong(value);
1069 });
1070 break;
1071 case BatteryManager.BATTERY_PROPERTY_CURRENT_NOW:
1072 service.getCurrentNow((int result, int value) -> {
1073 outResult.value = result;
1074 if (result == Result.SUCCESS) prop.setLong(value);
1075 });
1076 break;
1077 case BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE:
1078 service.getCurrentAverage((int result, int value) -> {
1079 outResult.value = result;
1080 if (result == Result.SUCCESS) prop.setLong(value);
1081 });
1082 break;
1083 case BatteryManager.BATTERY_PROPERTY_CAPACITY:
1084 service.getCapacity((int result, int value) -> {
1085 outResult.value = result;
1086 if (result == Result.SUCCESS) prop.setLong(value);
1087 });
1088 break;
1089 case BatteryManager.BATTERY_PROPERTY_STATUS:
1090 service.getChargeStatus((int result, int value) -> {
1091 outResult.value = result;
1092 if (result == Result.SUCCESS) prop.setLong(value);
1093 });
1094 break;
1095 case BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER:
1096 service.getEnergyCounter((int result, long value) -> {
1097 outResult.value = result;
1098 if (result == Result.SUCCESS) prop.setLong(value);
1099 });
1100 break;
1101 }
1102 return outResult.value;
1103 }
1104 public void scheduleUpdate() {
1105 Slog.e(TAG, "health: must not call scheduleUpdate on battery properties");
1106 }
1107 }
1108
Jeff Brown21392762014-06-13 19:00:36 -07001109 private final class LocalService extends BatteryManagerInternal {
1110 @Override
1111 public boolean isPowered(int plugTypeSet) {
1112 synchronized (mLock) {
1113 return isPoweredLocked(plugTypeSet);
1114 }
1115 }
1116
1117 @Override
1118 public int getPlugType() {
1119 synchronized (mLock) {
1120 return mPlugType;
1121 }
1122 }
1123
1124 @Override
1125 public int getBatteryLevel() {
1126 synchronized (mLock) {
Yifan Hong932190b2017-10-11 11:00:51 -07001127 return mHealthInfo.legacy.batteryLevel;
Jeff Brown21392762014-06-13 19:00:36 -07001128 }
1129 }
1130
1131 @Override
1132 public boolean getBatteryLevelLow() {
1133 synchronized (mLock) {
1134 return mBatteryLevelLow;
1135 }
1136 }
1137
1138 @Override
1139 public int getInvalidCharger() {
1140 synchronized (mLock) {
1141 return mInvalidCharger;
1142 }
1143 }
1144 }
Yifan Hong98852792017-10-12 11:35:14 -07001145
1146 /**
1147 * HealthServiceWrapper wraps the internal IHealth service and refreshes the service when
1148 * necessary.
1149 *
1150 * On new registration of IHealth service, {@link #onRegistration onRegistration} is called and
1151 * the internal service is refreshed.
1152 * On death of an existing IHealth service, the internal service is NOT cleared to avoid
1153 * race condition between death notification and new service notification. Hence,
1154 * a caller must check for transaction errors when calling into the service.
1155 *
1156 * @hide Should only be used internally.
1157 */
1158 @VisibleForTesting
1159 static final class HealthServiceWrapper {
1160 private static final String TAG = "HealthServiceWrapper";
1161 public static final String INSTANCE_HEALTHD = "backup";
1162 public static final String INSTANCE_VENDOR = "default";
1163 // All interesting instances, sorted by priority high -> low.
1164 private static final List<String> sAllInstances =
1165 Arrays.asList(INSTANCE_VENDOR, INSTANCE_HEALTHD);
1166
1167 private final IServiceNotification mNotification = new Notification();
1168 private Callback mCallback;
1169 private IHealthSupplier mHealthSupplier;
1170
Yifan Hong89d55c12017-10-11 11:29:01 -07001171 private final Object mLastServiceSetLock = new Object();
1172 // Last IHealth service received.
1173 // set must be also be guarded with mLastServiceSetLock to ensure ordering.
1174 private final AtomicReference<IHealth> mLastService = new AtomicReference<>();
1175
Yifan Hong98852792017-10-12 11:35:14 -07001176 /**
1177 * init should be called after constructor. For testing purposes, init is not called by
1178 * constructor.
1179 */
1180 HealthServiceWrapper() {
1181 }
1182
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001183 IHealth getLastService() {
1184 return mLastService.get();
1185 }
1186
Yifan Hong98852792017-10-12 11:35:14 -07001187 /**
1188 * Start monitoring registration of new IHealth services. Only instances that are in
1189 * {@code sAllInstances} and in device / framework manifest are used. This function should
1190 * only be called once.
1191 * @throws RemoteException transaction error when talking to IServiceManager
1192 * @throws NoSuchElementException if one of the following cases:
1193 * - No service manager;
1194 * - none of {@code sAllInstances} are in manifests (i.e. not
1195 * available on this device), or none of these instances are available to current
1196 * process.
1197 * @throws NullPointerException when callback is null or supplier is null
1198 */
1199 void init(Callback callback,
1200 IServiceManagerSupplier managerSupplier,
1201 IHealthSupplier healthSupplier)
1202 throws RemoteException, NoSuchElementException, NullPointerException {
1203 if (callback == null || managerSupplier == null || healthSupplier == null)
1204 throw new NullPointerException();
1205
1206 mCallback = callback;
1207 mHealthSupplier = healthSupplier;
1208
1209 IServiceManager manager = managerSupplier.get();
1210 for (String name : sAllInstances) {
1211 if (manager.getTransport(IHealth.kInterfaceName, name) ==
1212 IServiceManager.Transport.EMPTY) {
1213 continue;
1214 }
1215
1216 manager.registerForNotifications(IHealth.kInterfaceName, name, mNotification);
1217 Slog.i(TAG, "health: HealthServiceWrapper listening to instance " + name);
1218 return;
1219 }
1220
1221 throw new NoSuchElementException(String.format(
1222 "No IHealth service instance among %s is available. Perhaps no permission?",
1223 sAllInstances.toString()));
1224 }
1225
1226 interface Callback {
1227 /**
1228 * This function is invoked asynchronously when a new and related IServiceNotification
1229 * is received.
1230 * @param service the recently retrieved service from IServiceManager.
1231 * Can be a dead service before service notification of a new service is delivered.
1232 * Implementation must handle cases for {@link RemoteException}s when calling
1233 * into service.
1234 * @param instance instance name.
1235 */
Yifan Hong89d55c12017-10-11 11:29:01 -07001236 void onRegistration(IHealth oldService, IHealth newService, String instance);
Yifan Hong98852792017-10-12 11:35:14 -07001237 }
1238
1239 /**
1240 * Supplier of services.
1241 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1242 */
1243 interface IServiceManagerSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001244 default IServiceManager get() throws NoSuchElementException, RemoteException {
1245 return IServiceManager.getService();
1246 }
Yifan Hong98852792017-10-12 11:35:14 -07001247 }
1248 /**
1249 * Supplier of services.
1250 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1251 */
1252 interface IHealthSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001253 default IHealth get(String name) throws NoSuchElementException, RemoteException {
1254 return IHealth.getService(name);
1255 }
Yifan Hong98852792017-10-12 11:35:14 -07001256 }
1257
1258 private class Notification extends IServiceNotification.Stub {
1259 @Override
1260 public final void onRegistration(String interfaceName, String instanceName,
1261 boolean preexisting) {
1262 if (!IHealth.kInterfaceName.equals(interfaceName)) return;
1263 if (!sAllInstances.contains(instanceName)) return;
1264 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001265 // ensures the order of multiple onRegistration on different threads.
1266 synchronized (mLastServiceSetLock) {
1267 IHealth newService = mHealthSupplier.get(instanceName);
1268 IHealth oldService = mLastService.getAndSet(newService);
1269 Slog.i(TAG, "health: new instance registered " + instanceName);
1270 mCallback.onRegistration(oldService, newService, instanceName);
1271 }
Yifan Hong98852792017-10-12 11:35:14 -07001272 } catch (NoSuchElementException | RemoteException ex) {
1273 Slog.e(TAG, "health: Cannot get instance '" + instanceName + "': " +
1274 ex.getMessage() + ". Perhaps no permission?");
1275 }
1276 }
1277 }
1278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279}