blob: 04d292fa1ae40faaf11cb1fd1292e16543db9620 [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 Honge41e9392017-11-06 12:56:59 -080041import android.hardware.health.V1_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;
Kweku Adamse6b00c22017-10-23 16:46:45 -070046import android.os.BatteryManagerProto;
Jeff Brown21392762014-06-13 19:00:36 -070047import android.os.BatteryManagerInternal;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070048import android.os.BatteryProperty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.Binder;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070050import android.os.FileUtils;
Jeff Brown605ea692012-10-05 16:33:10 -070051import android.os.Handler;
Yifan Hongcf9a8b22017-11-02 18:43:06 -070052import android.os.HandlerThread;
Todd Poynor26faecc2013-05-22 18:54:48 -070053import android.os.IBatteryPropertiesListener;
54import android.os.IBatteryPropertiesRegistrar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.IBinder;
Dan Egnor18e93962010-02-10 19:27:58 -080056import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.RemoteException;
58import android.os.ServiceManager;
59import android.os.SystemClock;
Yifan Hong8cc18ef2017-10-31 12:27:47 -070060import android.os.Trace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.os.UEventObserver;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070062import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.provider.Settings;
Netta Pe2a3cd82017-01-26 18:03:51 -080064import android.service.battery.BatteryServiceDumpProto;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.util.EventLog;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070066import android.util.MutableInt;
Joe Onorato8a9b2202010-02-26 18:56:32 -080067import android.util.Slog;
Netta Pe2a3cd82017-01-26 18:03:51 -080068import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70import java.io.File;
71import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.io.FileOutputStream;
73import java.io.IOException;
74import java.io.PrintWriter;
75
Yifan Hong98852792017-10-12 11:35:14 -070076import java.util.Arrays;
77import java.util.List;
78import java.util.NoSuchElementException;
Yifan Hongcf9a8b22017-11-02 18:43:06 -070079import java.util.Objects;
Yifan Hong89d55c12017-10-11 11:29:01 -070080import java.util.concurrent.atomic.AtomicReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82/**
83 * <p>BatteryService monitors the charging status, and charge level of the device
84 * battery. When these values change this service broadcasts the new values
85 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
86 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
87 * BATTERY_CHANGED} action.</p>
88 * <p>The new values are stored in the Intent data and can be retrieved by
89 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
90 * following keys:</p>
91 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
92 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
93 * <p>&quot;status&quot; - String, the current charging status.<br />
94 * <p>&quot;health&quot; - String, the current battery health.<br />
95 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
96 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
97 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
98 * into an AC power adapter; 2 if plugged in via USB.</p>
99 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
100 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
101 * a degree Centigrade</p>
102 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
Jeff Brown605ea692012-10-05 16:33:10 -0700103 *
104 * <p>
105 * The battery service may be called by the power manager while holding its locks so
106 * we take care to post all outcalls into the activity manager to a handler.
107 *
108 * FIXME: Ideally the power manager would perform all of its calls into the battery
109 * service asynchronously itself.
110 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 */
Jeff Brown21392762014-06-13 19:00:36 -0700112public final class BatteryService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private static final String TAG = BatteryService.class.getSimpleName();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800114
Jeff Browna4d82042012-10-02 19:11:19 -0700115 private static final boolean DEBUG = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800116
Jeff Browna4d82042012-10-02 19:11:19 -0700117 private static final int BATTERY_SCALE = 100; // battery capacity is a percentage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Yifan Hong89d55c12017-10-11 11:29:01 -0700119 private static final long HEALTH_HAL_WAIT_MS = 1000;
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 // Used locally for determining when to make a last ditch effort to log
122 // discharge stats before the device dies.
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700123 private int mCriticalBatteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Jeff Sharkeyec43a6b2013-04-30 13:33:18 -0700125 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "--unplugged" };
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final String DUMPSYS_DATA_PATH = "/data/system/";
128
129 // This should probably be exposed in the API, though it's not critical
130 private static final int BATTERY_PLUGGED_NONE = 0;
131
132 private final Context mContext;
133 private final IBatteryStats mBatteryStats;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700134 BinderService mBinderService;
Jeff Brown605ea692012-10-05 16:33:10 -0700135 private final Handler mHandler;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800136
Jeff Browna4d82042012-10-02 19:11:19 -0700137 private final Object mLock = new Object();
138
Yifan Hong932190b2017-10-11 11:00:51 -0700139 private HealthInfo mHealthInfo;
140 private final HealthInfo mLastHealthInfo = new HealthInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 private boolean mBatteryLevelCritical;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private int mLastBatteryStatus;
143 private int mLastBatteryHealth;
144 private boolean mLastBatteryPresent;
145 private int mLastBatteryLevel;
146 private int mLastBatteryVoltage;
147 private int mLastBatteryTemperature;
148 private boolean mLastBatteryLevelCritical;
Adrian Roos76dc5a52015-07-21 16:20:36 -0700149 private int mLastMaxChargingCurrent;
Badhri Jagan Sridharanf92fcfe2015-10-27 13:59:34 -0700150 private int mLastMaxChargingVoltage;
Ruchi Kandoi6361e222016-04-07 11:28:30 -0700151 private int mLastChargeCounter;
Jeff Browna4d82042012-10-02 19:11:19 -0700152
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800153 private int mSequence = 1;
154
Jeff Browna4d82042012-10-02 19:11:19 -0700155 private int mInvalidCharger;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700156 private int mLastInvalidCharger;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400157
158 private int mLowBatteryWarningLevel;
159 private int mLowBatteryCloseWarningLevel;
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700160 private int mShutdownBatteryTemperature;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private int mPlugType;
163 private int mLastPlugType = -1; // Extra state so we can detect first run
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800164
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700165 private boolean mBatteryLevelLow;
166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 private long mDischargeStartTime;
168 private int mDischargeStartLevel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800169
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700170 private boolean mUpdatesStopped;
171
Joe Onoratode1b3592010-10-25 20:36:47 -0700172 private Led mLed;
173
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700174 private boolean mSentLowBatteryBroadcast = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800175
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700176 private ActivityManagerInternal mActivityManagerInternal;
177
Yifan Hong89d55c12017-10-11 11:29:01 -0700178 private HealthServiceWrapper mHealthServiceWrapper;
179 private HealthHalCallback mHealthHalCallback;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -0700180 private BatteryPropertiesRegistrar mBatteryPropertiesRegistrar;
Yifan Hongcf9a8b22017-11-02 18:43:06 -0700181 private HandlerThread mHandlerThread;
Yifan Hong89d55c12017-10-11 11:29:01 -0700182
Jeff Brown21392762014-06-13 19:00:36 -0700183 public BatteryService(Context context) {
184 super(context);
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 mContext = context;
Jeff Brown605ea692012-10-05 16:33:10 -0700187 mHandler = new Handler(true /*async*/);
Jeff Brown21392762014-06-13 19:00:36 -0700188 mLed = new Led(context, getLocalService(LightsManager.class));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 mBatteryStats = BatteryStatsService.getService();
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700190 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700192 mCriticalBatteryLevel = mContext.getResources().getInteger(
193 com.android.internal.R.integer.config_criticalBatteryWarningLevel);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400194 mLowBatteryWarningLevel = mContext.getResources().getInteger(
195 com.android.internal.R.integer.config_lowBatteryWarningLevel);
Dianne Hackborn14272302014-06-10 23:13:02 -0700196 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
197 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700198 mShutdownBatteryTemperature = mContext.getResources().getInteger(
199 com.android.internal.R.integer.config_shutdownBatteryTemperature);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400200
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400201 // watch for invalid charger messages if the invalid_charger switch exists
202 if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700203 UEventObserver invalidChargerObserver = new UEventObserver() {
204 @Override
205 public void onUEvent(UEvent event) {
206 final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
207 synchronized (mLock) {
208 if (mInvalidCharger != invalidCharger) {
209 mInvalidCharger = invalidCharger;
210 }
211 }
212 }
213 };
214 invalidChargerObserver.startObserving(
Jeff Browna4d82042012-10-02 19:11:19 -0700215 "DEVPATH=/devices/virtual/switch/invalid_charger");
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400216 }
Jeff Brown21392762014-06-13 19:00:36 -0700217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Jeff Brown21392762014-06-13 19:00:36 -0700219 @Override
220 public void onStart() {
Yifan Hong89d55c12017-10-11 11:29:01 -0700221 registerHealthCallback();
Jeff Brown21392762014-06-13 19:00:36 -0700222
Dianne Hackborn2e441072015-10-28 18:00:57 -0700223 mBinderService = new BinderService();
224 publishBinderService("battery", mBinderService);
Yifan Hong1fd86f4c2017-10-09 16:50:33 -0700225 mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
226 publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
Jeff Brown21392762014-06-13 19:00:36 -0700227 publishLocalService(BatteryManagerInternal.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 }
229
Jeff Brown21392762014-06-13 19:00:36 -0700230 @Override
231 public void onBootPhase(int phase) {
232 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
233 // check our power situation now that it is safe to display the shutdown dialog.
234 synchronized (mLock) {
235 ContentObserver obs = new ContentObserver(mHandler) {
236 @Override
237 public void onChange(boolean selfChange) {
238 synchronized (mLock) {
239 updateBatteryWarningLevelLocked();
240 }
Dianne Hackborn14272302014-06-10 23:13:02 -0700241 }
Jeff Brown21392762014-06-13 19:00:36 -0700242 };
243 final ContentResolver resolver = mContext.getContentResolver();
244 resolver.registerContentObserver(Settings.Global.getUriFor(
245 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
246 false, obs, UserHandle.USER_ALL);
247 updateBatteryWarningLevelLocked();
248 }
Jeff Browna4d82042012-10-02 19:11:19 -0700249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 }
251
Yifan Hong89d55c12017-10-11 11:29:01 -0700252 private void registerHealthCallback() {
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700253 traceBegin("HealthInitWrapper");
Yifan Hong89d55c12017-10-11 11:29:01 -0700254 mHealthServiceWrapper = new HealthServiceWrapper();
255 mHealthHalCallback = new HealthHalCallback();
256 // IHealth is lazily retrieved.
257 try {
258 mHealthServiceWrapper.init(mHealthHalCallback,
259 new HealthServiceWrapper.IServiceManagerSupplier() {},
260 new HealthServiceWrapper.IHealthSupplier() {});
Yifan Hong78e8af12017-10-26 15:57:19 -0700261 } catch (RemoteException ex) {
262 Slog.e(TAG, "health: cannot register callback. (RemoteException)");
263 throw ex.rethrowFromSystemServer();
264 } catch (NoSuchElementException ex) {
265 Slog.e(TAG, "health: cannot register callback. (no supported health HAL service)");
266 throw ex;
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700267 } finally {
268 traceEnd();
Yifan Hong89d55c12017-10-11 11:29:01 -0700269 }
270
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700271 traceBegin("HealthInitWaitUpdate");
Yifan Hong89d55c12017-10-11 11:29:01 -0700272 // init register for new service notifications, and IServiceManager should return the
273 // existing service in a near future. Wait for this.update() to instantiate
274 // the initial mHealthInfo.
Yifan Hong78e8af12017-10-26 15:57:19 -0700275 long beforeWait = SystemClock.uptimeMillis();
Yifan Hong89d55c12017-10-11 11:29:01 -0700276 synchronized (mLock) {
Yifan Hong78e8af12017-10-26 15:57:19 -0700277 while (mHealthInfo == null) {
278 Slog.i(TAG, "health: Waited " + (SystemClock.uptimeMillis() - beforeWait) +
279 "ms for callbacks. Waiting another " + HEALTH_HAL_WAIT_MS + " ms...");
Yifan Hong89d55c12017-10-11 11:29:01 -0700280 try {
Yifan Hong78e8af12017-10-26 15:57:19 -0700281 mLock.wait(HEALTH_HAL_WAIT_MS);
Yifan Hong89d55c12017-10-11 11:29:01 -0700282 } catch (InterruptedException ex) {
Yifan Hong78e8af12017-10-26 15:57:19 -0700283 Slog.i(TAG, "health: InterruptedException when waiting for update. "
284 + " Continuing...");
Yifan Hong89d55c12017-10-11 11:29:01 -0700285 }
286 }
Yifan Hong89d55c12017-10-11 11:29:01 -0700287 }
288
Yifan Hong78e8af12017-10-26 15:57:19 -0700289 Slog.i(TAG, "health: Waited " + (SystemClock.uptimeMillis() - beforeWait)
290 + "ms and received the update.");
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700291 traceEnd();
Yifan Hong89d55c12017-10-11 11:29:01 -0700292 }
293
Jeff Brown21392762014-06-13 19:00:36 -0700294 private void updateBatteryWarningLevelLocked() {
Dianne Hackborn14272302014-06-10 23:13:02 -0700295 final ContentResolver resolver = mContext.getContentResolver();
296 int defWarnLevel = mContext.getResources().getInteger(
297 com.android.internal.R.integer.config_lowBatteryWarningLevel);
298 mLowBatteryWarningLevel = Settings.Global.getInt(resolver,
299 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, defWarnLevel);
300 if (mLowBatteryWarningLevel == 0) {
301 mLowBatteryWarningLevel = defWarnLevel;
302 }
303 if (mLowBatteryWarningLevel < mCriticalBatteryLevel) {
304 mLowBatteryWarningLevel = mCriticalBatteryLevel;
305 }
306 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
307 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
308 processValuesLocked(true);
309 }
310
Jeff Browna4d82042012-10-02 19:11:19 -0700311 private boolean isPoweredLocked(int plugTypeSet) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 // assume we are powered if battery state is unknown so
313 // the "stay on while plugged in" option will work.
Yifan Honge41e9392017-11-06 12:56:59 -0800314 if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 return true;
316 }
Yifan Honge41e9392017-11-06 12:56:59 -0800317 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_AC) != 0 && mHealthInfo.chargerAcOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700318 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 }
Yifan Honge41e9392017-11-06 12:56:59 -0800320 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_USB) != 0 && mHealthInfo.chargerUsbOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700321 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 }
Yifan Honge41e9392017-11-06 12:56:59 -0800323 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0 && mHealthInfo.chargerWirelessOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700324 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
Jeff Browna4d82042012-10-02 19:11:19 -0700326 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
328
Jeff Brown21392762014-06-13 19:00:36 -0700329 private boolean shouldSendBatteryLowLocked() {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700330 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
331 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
332
333 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
334 * - is just un-plugged (previously was plugged) and battery level is
335 * less than or equal to WARNING, or
336 * - is not plugged and battery level falls to WARNING boundary
337 * (becomes <= mLowBatteryWarningLevel).
338 */
339 return !plugged
Yifan Honge41e9392017-11-06 12:56:59 -0800340 && mHealthInfo.batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
341 && mHealthInfo.batteryLevel <= mLowBatteryWarningLevel
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700342 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
343 }
344
Jeff Browna4d82042012-10-02 19:11:19 -0700345 private void shutdownIfNoPowerLocked() {
Mike Lockwood07a500f2009-08-12 09:56:44 -0400346 // shut down gracefully if our battery is critically low and we are not powered.
347 // wait until the system has booted before attempting to display the shutdown dialog.
Yifan Honge41e9392017-11-06 12:56:59 -0800348 if (mHealthInfo.batteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
Jeff Brown605ea692012-10-05 16:33:10 -0700349 mHandler.post(new Runnable() {
350 @Override
351 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700352 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700353 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
354 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700355 intent.putExtra(Intent.EXTRA_REASON,
356 PowerManager.SHUTDOWN_LOW_BATTERY);
Jeff Brown605ea692012-10-05 16:33:10 -0700357 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
358 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
359 }
360 }
361 });
Mike Lockwood07a500f2009-08-12 09:56:44 -0400362 }
363 }
364
Jeff Browna4d82042012-10-02 19:11:19 -0700365 private void shutdownIfOverTempLocked() {
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700366 // shut down gracefully if temperature is too high (> 68.0C by default)
367 // wait until the system has booted before attempting to display the
368 // shutdown dialog.
Yifan Honge41e9392017-11-06 12:56:59 -0800369 if (mHealthInfo.batteryTemperature > mShutdownBatteryTemperature) {
Jeff Brown605ea692012-10-05 16:33:10 -0700370 mHandler.post(new Runnable() {
371 @Override
372 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700373 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700374 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
375 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700376 intent.putExtra(Intent.EXTRA_REASON,
377 PowerManager.SHUTDOWN_BATTERY_THERMAL_STATE);
Jeff Brown605ea692012-10-05 16:33:10 -0700378 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
379 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
380 }
381 }
382 });
Eric Olsen6a362a92010-03-26 15:38:41 -0700383 }
384 }
385
Yifan Hong89d55c12017-10-11 11:29:01 -0700386 private void update(HealthInfo info) {
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700387 traceBegin("HealthInfoUpdate");
Todd Poynor26faecc2013-05-22 18:54:48 -0700388 synchronized (mLock) {
389 if (!mUpdatesStopped) {
Yifan Hong89d55c12017-10-11 11:29:01 -0700390 mHealthInfo = info;
Todd Poynor26faecc2013-05-22 18:54:48 -0700391 // Process the new values.
Dianne Hackborn14272302014-06-10 23:13:02 -0700392 processValuesLocked(false);
Yifan Hong89d55c12017-10-11 11:29:01 -0700393 mLock.notifyAll(); // for any waiters on new info
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800394 } else {
Yifan Hong89d55c12017-10-11 11:29:01 -0700395 copy(mLastHealthInfo, info);
Todd Poynor26faecc2013-05-22 18:54:48 -0700396 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700397 }
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700398 traceEnd();
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400
Yifan Hong932190b2017-10-11 11:00:51 -0700401 private static void copy(HealthInfo dst, HealthInfo src) {
Yifan Honge41e9392017-11-06 12:56:59 -0800402 dst.chargerAcOnline = src.chargerAcOnline;
403 dst.chargerUsbOnline = src.chargerUsbOnline;
404 dst.chargerWirelessOnline = src.chargerWirelessOnline;
405 dst.maxChargingCurrent = src.maxChargingCurrent;
406 dst.maxChargingVoltage = src.maxChargingVoltage;
407 dst.batteryStatus = src.batteryStatus;
408 dst.batteryHealth = src.batteryHealth;
409 dst.batteryPresent = src.batteryPresent;
410 dst.batteryLevel = src.batteryLevel;
411 dst.batteryVoltage = src.batteryVoltage;
412 dst.batteryTemperature = src.batteryTemperature;
413 dst.batteryCurrent = src.batteryCurrent;
414 dst.batteryCycleCount = src.batteryCycleCount;
415 dst.batteryFullCharge = src.batteryFullCharge;
416 dst.batteryChargeCounter = src.batteryChargeCounter;
417 dst.batteryTechnology = src.batteryTechnology;
Yifan Hong932190b2017-10-11 11:00:51 -0700418 }
419
Dianne Hackborn14272302014-06-10 23:13:02 -0700420 private void processValuesLocked(boolean force) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700421 boolean logOutlier = false;
422 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700423
Todd Poynorb41df4422017-12-08 10:44:40 -0800424 mBatteryLevelCritical =
425 mHealthInfo.batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
426 && mHealthInfo.batteryLevel <= mCriticalBatteryLevel;
Yifan Honge41e9392017-11-06 12:56:59 -0800427 if (mHealthInfo.chargerAcOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
Yifan Honge41e9392017-11-06 12:56:59 -0800429 } else if (mHealthInfo.chargerUsbOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Yifan Honge41e9392017-11-06 12:56:59 -0800431 } else if (mHealthInfo.chargerWirelessOnline) {
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700432 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 } else {
434 mPlugType = BATTERY_PLUGGED_NONE;
435 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700436
Jeff Browna4d82042012-10-02 19:11:19 -0700437 if (DEBUG) {
438 Slog.d(TAG, "Processing new values: "
Yifan Hong932190b2017-10-11 11:00:51 -0700439 + "info=" + mHealthInfo
Jeff Browna4d82042012-10-02 19:11:19 -0700440 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
441 + ", mPlugType=" + mPlugType);
442 }
443
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700444 // Let the battery stats keep track of the current level.
445 try {
Yifan Honge41e9392017-11-06 12:56:59 -0800446 mBatteryStats.setBatteryState(mHealthInfo.batteryStatus, mHealthInfo.batteryHealth,
447 mPlugType, mHealthInfo.batteryLevel, mHealthInfo.batteryTemperature,
448 mHealthInfo.batteryVoltage, mHealthInfo.batteryChargeCounter,
449 mHealthInfo.batteryFullCharge);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700450 } catch (RemoteException e) {
451 // Should never happen.
452 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700453
Jeff Browna4d82042012-10-02 19:11:19 -0700454 shutdownIfNoPowerLocked();
455 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700456
Yifan Honge41e9392017-11-06 12:56:59 -0800457 if (force || (mHealthInfo.batteryStatus != mLastBatteryStatus ||
458 mHealthInfo.batteryHealth != mLastBatteryHealth ||
459 mHealthInfo.batteryPresent != mLastBatteryPresent ||
460 mHealthInfo.batteryLevel != mLastBatteryLevel ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 mPlugType != mLastPlugType ||
Yifan Honge41e9392017-11-06 12:56:59 -0800462 mHealthInfo.batteryVoltage != mLastBatteryVoltage ||
463 mHealthInfo.batteryTemperature != mLastBatteryTemperature ||
464 mHealthInfo.maxChargingCurrent != mLastMaxChargingCurrent ||
465 mHealthInfo.maxChargingVoltage != mLastMaxChargingVoltage ||
466 mHealthInfo.batteryChargeCounter != mLastChargeCounter ||
Dianne Hackborn14272302014-06-10 23:13:02 -0700467 mInvalidCharger != mLastInvalidCharger)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 if (mPlugType != mLastPlugType) {
470 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
471 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 // There's no value in this data unless we've discharged at least once and the
474 // battery level has changed; so don't log until it does.
Yifan Honge41e9392017-11-06 12:56:59 -0800475 if (mDischargeStartTime != 0 && mDischargeStartLevel != mHealthInfo.batteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700476 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
477 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800478 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
Yifan Honge41e9392017-11-06 12:56:59 -0800479 mDischargeStartLevel, mHealthInfo.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800481 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 }
483 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
484 // charging -> discharging or we just powered up
485 mDischargeStartTime = SystemClock.elapsedRealtime();
Yifan Honge41e9392017-11-06 12:56:59 -0800486 mDischargeStartLevel = mHealthInfo.batteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
488 }
Yifan Honge41e9392017-11-06 12:56:59 -0800489 if (mHealthInfo.batteryStatus != mLastBatteryStatus ||
490 mHealthInfo.batteryHealth != mLastBatteryHealth ||
491 mHealthInfo.batteryPresent != mLastBatteryPresent ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800493 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
Yifan Honge41e9392017-11-06 12:56:59 -0800494 mHealthInfo.batteryStatus, mHealthInfo.batteryHealth, mHealthInfo.batteryPresent ? 1 : 0,
495 mPlugType, mHealthInfo.batteryTechnology);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
Yifan Honge41e9392017-11-06 12:56:59 -0800497 if (mHealthInfo.batteryLevel != mLastBatteryLevel) {
Dianne Hackborncf1171642013-07-12 17:26:02 -0700498 // Don't do this just from voltage or temperature changes, that is
499 // too noisy.
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800500 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
Yifan Honge41e9392017-11-06 12:56:59 -0800501 mHealthInfo.batteryLevel, mHealthInfo.batteryVoltage, mHealthInfo.batteryTemperature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 }
503 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
504 mPlugType == BATTERY_PLUGGED_NONE) {
505 // We want to make sure we log discharge cycle outliers
506 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700507 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
508 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800510
Dianne Hackborn14272302014-06-10 23:13:02 -0700511 if (!mBatteryLevelLow) {
512 // Should we now switch in to low battery mode?
513 if (mPlugType == BATTERY_PLUGGED_NONE
Todd Poynorb41df4422017-12-08 10:44:40 -0800514 && mHealthInfo.batteryStatus !=
515 BatteryManager.BATTERY_STATUS_UNKNOWN
Yifan Honge41e9392017-11-06 12:56:59 -0800516 && mHealthInfo.batteryLevel <= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700517 mBatteryLevelLow = true;
518 }
519 } else {
520 // Should we now switch out of low battery mode?
521 if (mPlugType != BATTERY_PLUGGED_NONE) {
522 mBatteryLevelLow = false;
Yifan Honge41e9392017-11-06 12:56:59 -0800523 } else if (mHealthInfo.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700524 mBatteryLevelLow = false;
Yifan Honge41e9392017-11-06 12:56:59 -0800525 } else if (force && mHealthInfo.batteryLevel >= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700526 // If being forced, the previous state doesn't matter, we will just
527 // absolutely check to see if we are now above the warning level.
528 mBatteryLevelLow = false;
529 }
530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800531
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800532 mSequence++;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800533
Christopher Tate06ba5542009-04-09 16:03:56 -0700534 // Separate broadcast is sent for power connected / not connected
535 // since the standard intent will not wake any applications and some
536 // applications may want to have smart behavior based on this.
537 if (mPlugType != 0 && mLastPlugType == 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800538 final Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
539 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
540 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700541 mHandler.post(new Runnable() {
542 @Override
543 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700544 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
545 }
546 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700547 }
548 else if (mPlugType == 0 && mLastPlugType != 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800549 final Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
550 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
551 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700552 mHandler.post(new Runnable() {
553 @Override
554 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700555 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
556 }
557 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700558 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200559
Dianne Hackborn14272302014-06-10 23:13:02 -0700560 if (shouldSendBatteryLowLocked()) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700561 mSentLowBatteryBroadcast = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800562 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
563 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
564 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700565 mHandler.post(new Runnable() {
566 @Override
567 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700568 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
569 }
570 });
Dianne Hackborn532ea262017-03-17 17:50:55 -0700571 } else if (mSentLowBatteryBroadcast &&
Yifan Honge41e9392017-11-06 12:56:59 -0800572 mHealthInfo.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700573 mSentLowBatteryBroadcast = false;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800574 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
575 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
576 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700577 mHandler.post(new Runnable() {
578 @Override
579 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700580 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
581 }
582 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800584
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800585 // We are doing this after sending the above broadcasts, so anything processing
586 // them will get the new sequence number at that point. (See for example how testing
587 // of JobScheduler's BatteryController works.)
588 sendIntentLocked();
589
Joe Onoratode1b3592010-10-25 20:36:47 -0700590 // Update the battery LED
591 mLed.updateLightsLocked();
592
The Android Open Source Project10592532009-03-18 17:39:46 -0700593 // This needs to be done after sendIntent() so that we get the lastest battery stats.
594 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700595 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800597
Yifan Honge41e9392017-11-06 12:56:59 -0800598 mLastBatteryStatus = mHealthInfo.batteryStatus;
599 mLastBatteryHealth = mHealthInfo.batteryHealth;
600 mLastBatteryPresent = mHealthInfo.batteryPresent;
601 mLastBatteryLevel = mHealthInfo.batteryLevel;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700602 mLastPlugType = mPlugType;
Yifan Honge41e9392017-11-06 12:56:59 -0800603 mLastBatteryVoltage = mHealthInfo.batteryVoltage;
604 mLastBatteryTemperature = mHealthInfo.batteryTemperature;
605 mLastMaxChargingCurrent = mHealthInfo.maxChargingCurrent;
606 mLastMaxChargingVoltage = mHealthInfo.maxChargingVoltage;
607 mLastChargeCounter = mHealthInfo.batteryChargeCounter;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700608 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400609 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
611 }
612
Jeff Browna4d82042012-10-02 19:11:19 -0700613 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700615 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800616 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
617 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800618
Yifan Honge41e9392017-11-06 12:56:59 -0800619 int icon = getIconLocked(mHealthInfo.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800621 intent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Yifan Honge41e9392017-11-06 12:56:59 -0800622 intent.putExtra(BatteryManager.EXTRA_STATUS, mHealthInfo.batteryStatus);
623 intent.putExtra(BatteryManager.EXTRA_HEALTH, mHealthInfo.batteryHealth);
624 intent.putExtra(BatteryManager.EXTRA_PRESENT, mHealthInfo.batteryPresent);
625 intent.putExtra(BatteryManager.EXTRA_LEVEL, mHealthInfo.batteryLevel);
Dianne Hackborn74ed6ec2017-11-21 16:33:44 -0800626 intent.putExtra(BatteryManager.EXTRA_BATTERY_LOW, mSentLowBatteryBroadcast);
Dianne Hackbornedd93162009-09-19 14:03:05 -0700627 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
628 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
629 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
Yifan Honge41e9392017-11-06 12:56:59 -0800630 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mHealthInfo.batteryVoltage);
631 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mHealthInfo.batteryTemperature);
632 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mHealthInfo.batteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400633 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
Yifan Honge41e9392017-11-06 12:56:59 -0800634 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mHealthInfo.maxChargingCurrent);
635 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE, mHealthInfo.maxChargingVoltage);
636 intent.putExtra(BatteryManager.EXTRA_CHARGE_COUNTER, mHealthInfo.batteryChargeCounter);
Jeff Browna4d82042012-10-02 19:11:19 -0700637 if (DEBUG) {
Yifan Hong932190b2017-10-11 11:00:51 -0700638 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. scale:" + BATTERY_SCALE
639 + ", info:" + mHealthInfo.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 }
641
Jeff Brown605ea692012-10-05 16:33:10 -0700642 mHandler.post(new Runnable() {
643 @Override
644 public void run() {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800645 ActivityManager.broadcastStickyIntent(intent, UserHandle.USER_ALL);
Jeff Brown605ea692012-10-05 16:33:10 -0700646 }
647 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649
Jeff Browna4d82042012-10-02 19:11:19 -0700650 private void logBatteryStatsLocked() {
Dianne Hackborn8c841092013-06-24 13:46:13 -0700651 IBinder batteryInfoService = ServiceManager.getService(BatteryStats.SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800652 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653
Dan Egnor18e93962010-02-10 19:27:58 -0800654 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
655 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
656
657 File dumpFile = null;
658 FileOutputStream dumpStream = null;
659 try {
660 // dump the service to a file
Dianne Hackborn8c841092013-06-24 13:46:13 -0700661 dumpFile = new File(DUMPSYS_DATA_PATH + BatteryStats.SERVICE_NAME + ".dump");
Dan Egnor18e93962010-02-10 19:27:58 -0800662 dumpStream = new FileOutputStream(dumpFile);
663 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700664 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800665
666 // add dump file to drop box
667 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
668 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800669 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800670 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800671 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800672 } finally {
673 // make sure we clean up
674 if (dumpStream != null) {
675 try {
676 dumpStream.close();
677 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800678 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
Dan Egnor18e93962010-02-10 19:27:58 -0800680 }
681 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800682 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800683 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685 }
686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800687
Jeff Browna4d82042012-10-02 19:11:19 -0700688 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700690 String dischargeThresholdString = Settings.Global.getString(cr,
691 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
692 String durationThresholdString = Settings.Global.getString(cr,
693 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 if (dischargeThresholdString != null && durationThresholdString != null) {
696 try {
697 long durationThreshold = Long.parseLong(durationThresholdString);
698 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699 if (duration <= durationThreshold &&
Yifan Honge41e9392017-11-06 12:56:59 -0800700 mDischargeStartLevel - mHealthInfo.batteryLevel >= dischargeThreshold) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700702 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
Jeff Browna4d82042012-10-02 19:11:19 -0700704 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700706 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
Yifan Honge41e9392017-11-06 12:56:59 -0800707 (mDischargeStartLevel - mHealthInfo.batteryLevel));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800709 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 durationThresholdString + " or " + dischargeThresholdString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712 }
713 }
714
Jeff Browna4d82042012-10-02 19:11:19 -0700715 private int getIconLocked(int level) {
Yifan Honge41e9392017-11-06 12:56:59 -0800716 if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 return com.android.internal.R.drawable.stat_sys_battery_charge;
Yifan Honge41e9392017-11-06 12:56:59 -0800718 } else if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 return com.android.internal.R.drawable.stat_sys_battery;
Yifan Honge41e9392017-11-06 12:56:59 -0800720 } else if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
721 || mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700722 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
Yifan Honge41e9392017-11-06 12:56:59 -0800723 && mHealthInfo.batteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800724 return com.android.internal.R.drawable.stat_sys_battery_charge;
725 } else {
726 return com.android.internal.R.drawable.stat_sys_battery;
727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 } else {
729 return com.android.internal.R.drawable.stat_sys_battery_unknown;
730 }
731 }
732
Dianne Hackborn2e441072015-10-28 18:00:57 -0700733 class Shell extends ShellCommand {
734 @Override
735 public int onCommand(String cmd) {
736 return onShellCommand(this, cmd);
737 }
738
739 @Override
740 public void onHelp() {
741 PrintWriter pw = getOutPrintWriter();
742 dumpHelp(pw);
743 }
744 }
745
746 static void dumpHelp(PrintWriter pw) {
747 pw.println("Battery service (battery) commands:");
748 pw.println(" help");
749 pw.println(" Print this help text.");
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700750 pw.println(" set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700751 pw.println(" Force a battery property value, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800752 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
753 pw.println(" unplug [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700754 pw.println(" Force battery unplugged, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800755 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
756 pw.println(" reset [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700757 pw.println(" Unfreeze battery state, returning to current hardware values.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800758 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
759 }
760
761 static final int OPTION_FORCE_UPDATE = 1<<0;
762
763 int parseOptions(Shell shell) {
764 String opt;
765 int opts = 0;
766 while ((opt = shell.getNextOption()) != null) {
767 if ("-f".equals(opt)) {
768 opts |= OPTION_FORCE_UPDATE;
769 }
770 }
771 return opts;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700772 }
773
774 int onShellCommand(Shell shell, String cmd) {
775 if (cmd == null) {
776 return shell.handleDefaultCommands(cmd);
777 }
778 PrintWriter pw = shell.getOutPrintWriter();
779 switch (cmd) {
780 case "unplug": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800781 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700782 getContext().enforceCallingOrSelfPermission(
783 android.Manifest.permission.DEVICE_POWER, null);
784 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700785 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700786 }
Yifan Honge41e9392017-11-06 12:56:59 -0800787 mHealthInfo.chargerAcOnline = false;
788 mHealthInfo.chargerUsbOnline = false;
789 mHealthInfo.chargerWirelessOnline = false;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700790 long ident = Binder.clearCallingIdentity();
791 try {
792 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800793 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700794 } finally {
795 Binder.restoreCallingIdentity(ident);
796 }
797 } break;
798 case "set": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800799 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700800 getContext().enforceCallingOrSelfPermission(
801 android.Manifest.permission.DEVICE_POWER, null);
802 final String key = shell.getNextArg();
803 if (key == null) {
804 pw.println("No property specified");
805 return -1;
806
807 }
808 final String value = shell.getNextArg();
809 if (value == null) {
810 pw.println("No value specified");
811 return -1;
812
813 }
814 try {
815 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700816 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700817 }
818 boolean update = true;
819 switch (key) {
Christopher Tate630d98b2017-03-07 14:12:26 -0800820 case "present":
Yifan Honge41e9392017-11-06 12:56:59 -0800821 mHealthInfo.batteryPresent = Integer.parseInt(value) != 0;
Christopher Tate630d98b2017-03-07 14:12:26 -0800822 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700823 case "ac":
Yifan Honge41e9392017-11-06 12:56:59 -0800824 mHealthInfo.chargerAcOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700825 break;
826 case "usb":
Yifan Honge41e9392017-11-06 12:56:59 -0800827 mHealthInfo.chargerUsbOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700828 break;
829 case "wireless":
Yifan Honge41e9392017-11-06 12:56:59 -0800830 mHealthInfo.chargerWirelessOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700831 break;
832 case "status":
Yifan Honge41e9392017-11-06 12:56:59 -0800833 mHealthInfo.batteryStatus = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700834 break;
835 case "level":
Yifan Honge41e9392017-11-06 12:56:59 -0800836 mHealthInfo.batteryLevel = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700837 break;
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700838 case "temp":
Yifan Honge41e9392017-11-06 12:56:59 -0800839 mHealthInfo.batteryTemperature = Integer.parseInt(value);
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700840 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700841 case "invalid":
842 mInvalidCharger = Integer.parseInt(value);
843 break;
844 default:
845 pw.println("Unknown set option: " + key);
846 update = false;
847 break;
848 }
849 if (update) {
850 long ident = Binder.clearCallingIdentity();
851 try {
852 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800853 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700854 } finally {
855 Binder.restoreCallingIdentity(ident);
856 }
857 }
858 } catch (NumberFormatException ex) {
859 pw.println("Bad value: " + value);
860 return -1;
861 }
862 } break;
863 case "reset": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800864 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700865 getContext().enforceCallingOrSelfPermission(
866 android.Manifest.permission.DEVICE_POWER, null);
867 long ident = Binder.clearCallingIdentity();
868 try {
869 if (mUpdatesStopped) {
870 mUpdatesStopped = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700871 copy(mHealthInfo, mLastHealthInfo);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800872 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700873 }
874 } finally {
875 Binder.restoreCallingIdentity(ident);
876 }
877 } break;
878 default:
879 return shell.handleDefaultCommands(cmd);
880 }
881 return 0;
882 }
883
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800884 private void processValuesFromShellLocked(PrintWriter pw, int opts) {
885 processValuesLocked((opts & OPTION_FORCE_UPDATE) != 0);
886 if ((opts & OPTION_FORCE_UPDATE) != 0) {
887 pw.println(mSequence);
888 }
889 }
890
Dianne Hackborn2e441072015-10-28 18:00:57 -0700891 private void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna4d82042012-10-02 19:11:19 -0700892 synchronized (mLock) {
893 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700894 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700895 if (mUpdatesStopped) {
896 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
897 }
Yifan Honge41e9392017-11-06 12:56:59 -0800898 pw.println(" AC powered: " + mHealthInfo.chargerAcOnline);
899 pw.println(" USB powered: " + mHealthInfo.chargerUsbOnline);
900 pw.println(" Wireless powered: " + mHealthInfo.chargerWirelessOnline);
901 pw.println(" Max charging current: " + mHealthInfo.maxChargingCurrent);
902 pw.println(" Max charging voltage: " + mHealthInfo.maxChargingVoltage);
903 pw.println(" Charge counter: " + mHealthInfo.batteryChargeCounter);
904 pw.println(" status: " + mHealthInfo.batteryStatus);
905 pw.println(" health: " + mHealthInfo.batteryHealth);
906 pw.println(" present: " + mHealthInfo.batteryPresent);
907 pw.println(" level: " + mHealthInfo.batteryLevel);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700908 pw.println(" scale: " + BATTERY_SCALE);
Yifan Honge41e9392017-11-06 12:56:59 -0800909 pw.println(" voltage: " + mHealthInfo.batteryVoltage);
910 pw.println(" temperature: " + mHealthInfo.batteryTemperature);
911 pw.println(" technology: " + mHealthInfo.batteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700912 } else {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700913 Shell shell = new Shell();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700914 shell.exec(mBinderService, null, fd, null, args, null, new ResultReceiver(null));
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700918
Netta Pe2a3cd82017-01-26 18:03:51 -0800919 private void dumpProto(FileDescriptor fd) {
920 final ProtoOutputStream proto = new ProtoOutputStream(fd);
921
922 synchronized (mLock) {
923 proto.write(BatteryServiceDumpProto.ARE_UPDATES_STOPPED, mUpdatesStopped);
Kweku Adamse6b00c22017-10-23 16:46:45 -0700924 int batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_NONE;
Yifan Honge41e9392017-11-06 12:56:59 -0800925 if (mHealthInfo.chargerAcOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700926 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_AC;
Yifan Honge41e9392017-11-06 12:56:59 -0800927 } else if (mHealthInfo.chargerUsbOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700928 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_USB;
Yifan Honge41e9392017-11-06 12:56:59 -0800929 } else if (mHealthInfo.chargerWirelessOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700930 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_WIRELESS;
Netta Pe2a3cd82017-01-26 18:03:51 -0800931 }
932 proto.write(BatteryServiceDumpProto.PLUGGED, batteryPluggedValue);
Yifan Honge41e9392017-11-06 12:56:59 -0800933 proto.write(BatteryServiceDumpProto.MAX_CHARGING_CURRENT, mHealthInfo.maxChargingCurrent);
934 proto.write(BatteryServiceDumpProto.MAX_CHARGING_VOLTAGE, mHealthInfo.maxChargingVoltage);
935 proto.write(BatteryServiceDumpProto.CHARGE_COUNTER, mHealthInfo.batteryChargeCounter);
936 proto.write(BatteryServiceDumpProto.STATUS, mHealthInfo.batteryStatus);
937 proto.write(BatteryServiceDumpProto.HEALTH, mHealthInfo.batteryHealth);
938 proto.write(BatteryServiceDumpProto.IS_PRESENT, mHealthInfo.batteryPresent);
939 proto.write(BatteryServiceDumpProto.LEVEL, mHealthInfo.batteryLevel);
Netta Pe2a3cd82017-01-26 18:03:51 -0800940 proto.write(BatteryServiceDumpProto.SCALE, BATTERY_SCALE);
Yifan Honge41e9392017-11-06 12:56:59 -0800941 proto.write(BatteryServiceDumpProto.VOLTAGE, mHealthInfo.batteryVoltage);
942 proto.write(BatteryServiceDumpProto.TEMPERATURE, mHealthInfo.batteryTemperature);
943 proto.write(BatteryServiceDumpProto.TECHNOLOGY, mHealthInfo.batteryTechnology);
Netta Pe2a3cd82017-01-26 18:03:51 -0800944 }
945 proto.flush();
946 }
947
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700948 private static void traceBegin(String name) {
949 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, name);
950 }
951
952 private static void traceEnd() {
953 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
954 }
955
Jeff Browna4d82042012-10-02 19:11:19 -0700956 private final class Led {
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800957 private final Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700958
Jeff Browna4d82042012-10-02 19:11:19 -0700959 private final int mBatteryLowARGB;
960 private final int mBatteryMediumARGB;
961 private final int mBatteryFullARGB;
962 private final int mBatteryLedOn;
963 private final int mBatteryLedOff;
964
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800965 public Led(Context context, LightsManager lights) {
966 mBatteryLight = lights.getLight(LightsManager.LIGHT_ID_BATTERY);
Joe Onoratode1b3592010-10-25 20:36:47 -0700967
Jeff Browna4d82042012-10-02 19:11:19 -0700968 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700969 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700970 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700971 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700972 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700973 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700974 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700975 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700976 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700977 com.android.internal.R.integer.config_notificationsBatteryLedOff);
978 }
979
980 /**
981 * Synchronize on BatteryService.
982 */
Jeff Browna4d82042012-10-02 19:11:19 -0700983 public void updateLightsLocked() {
Yifan Honge41e9392017-11-06 12:56:59 -0800984 final int level = mHealthInfo.batteryLevel;
985 final int status = mHealthInfo.batteryStatus;
Joe Onoratode1b3592010-10-25 20:36:47 -0700986 if (level < mLowBatteryWarningLevel) {
987 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
988 // Solid red when battery is charging
989 mBatteryLight.setColor(mBatteryLowARGB);
990 } else {
991 // Flash red when battery is low and not charging
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800992 mBatteryLight.setFlashing(mBatteryLowARGB, Light.LIGHT_FLASH_TIMED,
Joe Onoratode1b3592010-10-25 20:36:47 -0700993 mBatteryLedOn, mBatteryLedOff);
994 }
995 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
996 || status == BatteryManager.BATTERY_STATUS_FULL) {
997 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
998 // Solid green when full or charging and nearly full
999 mBatteryLight.setColor(mBatteryFullARGB);
1000 } else {
1001 // Solid orange when charging and halfway full
1002 mBatteryLight.setColor(mBatteryMediumARGB);
1003 }
1004 } else {
1005 // No lights if not charging and not low
1006 mBatteryLight.turnOff();
1007 }
1008 }
1009 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001010
Yifan Hong89d55c12017-10-11 11:29:01 -07001011 private final class HealthHalCallback extends IHealthInfoCallback.Stub
1012 implements HealthServiceWrapper.Callback {
1013 @Override public void healthInfoChanged(HealthInfo props) {
1014 BatteryService.this.update(props);
1015 }
1016 // on new service registered
1017 @Override public void onRegistration(IHealth oldService, IHealth newService,
1018 String instance) {
1019 if (newService == null) return;
1020
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001021 traceBegin("HealthUnregisterCallback");
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001022 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001023 if (oldService != null) {
1024 int r = oldService.unregisterCallback(this);
1025 if (r != Result.SUCCESS) {
1026 Slog.w(TAG, "health: cannot unregister previous callback: " +
1027 Result.toString(r));
1028 }
1029 }
1030 } catch (RemoteException ex) {
1031 Slog.w(TAG, "health: cannot unregister previous callback (transaction error): "
1032 + ex.getMessage());
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001033 } finally {
1034 traceEnd();
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001035 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001036
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001037 traceBegin("HealthRegisterCallback");
Yifan Hong89d55c12017-10-11 11:29:01 -07001038 try {
1039 int r = newService.registerCallback(this);
1040 if (r != Result.SUCCESS) {
1041 Slog.w(TAG, "health: cannot register callback: " + Result.toString(r));
1042 return;
1043 }
1044 // registerCallback does NOT guarantee that update is called
1045 // immediately, so request a manual update here.
1046 newService.update();
1047 } catch (RemoteException ex) {
1048 Slog.e(TAG, "health: cannot register callback (transaction error): "
1049 + ex.getMessage());
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001050 } finally {
1051 traceEnd();
Yifan Hong89d55c12017-10-11 11:29:01 -07001052 }
1053 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001054 }
Jeff Brown21392762014-06-13 19:00:36 -07001055
1056 private final class BinderService extends Binder {
Dianne Hackborn2e441072015-10-28 18:00:57 -07001057 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001058 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown21392762014-06-13 19:00:36 -07001059
Netta Pe2a3cd82017-01-26 18:03:51 -08001060 if (args.length > 0 && "--proto".equals(args[0])) {
1061 dumpProto(fd);
1062 } else {
1063 dumpInternal(fd, pw, args);
1064 }
Dianne Hackborn2e441072015-10-28 18:00:57 -07001065 }
1066
1067 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001068 FileDescriptor err, String[] args, ShellCallback callback,
1069 ResultReceiver resultReceiver) {
1070 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Jeff Brown21392762014-06-13 19:00:36 -07001071 }
1072 }
1073
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001074 // Reduced IBatteryPropertiesRegistrar that only implements getProperty for usage
1075 // in BatteryManager.
1076 private final class BatteryPropertiesRegistrar extends IBatteryPropertiesRegistrar.Stub {
1077 public void registerListener(IBatteryPropertiesListener listener) {
1078 Slog.e(TAG, "health: must not call registerListener on battery properties");
1079 }
1080 public void unregisterListener(IBatteryPropertiesListener listener) {
1081 Slog.e(TAG, "health: must not call unregisterListener on battery properties");
1082 }
1083 public int getProperty(int id, final BatteryProperty prop) throws RemoteException {
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001084 traceBegin("HealthGetProperty");
1085 try {
1086 IHealth service = mHealthServiceWrapper.getLastService();
1087 if (service == null) throw new RemoteException("no health service");
1088 final MutableInt outResult = new MutableInt(Result.NOT_SUPPORTED);
1089 switch(id) {
1090 case BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER:
1091 service.getChargeCounter((int result, int value) -> {
1092 outResult.value = result;
1093 if (result == Result.SUCCESS) prop.setLong(value);
1094 });
1095 break;
1096 case BatteryManager.BATTERY_PROPERTY_CURRENT_NOW:
1097 service.getCurrentNow((int result, int value) -> {
1098 outResult.value = result;
1099 if (result == Result.SUCCESS) prop.setLong(value);
1100 });
1101 break;
1102 case BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE:
1103 service.getCurrentAverage((int result, int value) -> {
1104 outResult.value = result;
1105 if (result == Result.SUCCESS) prop.setLong(value);
1106 });
1107 break;
1108 case BatteryManager.BATTERY_PROPERTY_CAPACITY:
1109 service.getCapacity((int result, int value) -> {
1110 outResult.value = result;
1111 if (result == Result.SUCCESS) prop.setLong(value);
1112 });
1113 break;
1114 case BatteryManager.BATTERY_PROPERTY_STATUS:
1115 service.getChargeStatus((int result, int value) -> {
1116 outResult.value = result;
1117 if (result == Result.SUCCESS) prop.setLong(value);
1118 });
1119 break;
1120 case BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER:
1121 service.getEnergyCounter((int result, long value) -> {
1122 outResult.value = result;
1123 if (result == Result.SUCCESS) prop.setLong(value);
1124 });
1125 break;
1126 }
1127 return outResult.value;
1128 } finally {
1129 traceEnd();
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001130 }
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001131 }
Yifan Hong7838fcb2017-10-24 16:06:27 -07001132 public void scheduleUpdate() throws RemoteException {
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001133 traceBegin("HealthScheduleUpdate");
1134 try {
1135 IHealth service = mHealthServiceWrapper.getLastService();
1136 if (service == null) throw new RemoteException("no health service");
1137 service.update();
1138 } finally {
1139 traceEnd();
1140 }
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001141 }
1142 }
1143
Jeff Brown21392762014-06-13 19:00:36 -07001144 private final class LocalService extends BatteryManagerInternal {
1145 @Override
1146 public boolean isPowered(int plugTypeSet) {
1147 synchronized (mLock) {
1148 return isPoweredLocked(plugTypeSet);
1149 }
1150 }
1151
1152 @Override
1153 public int getPlugType() {
1154 synchronized (mLock) {
1155 return mPlugType;
1156 }
1157 }
1158
1159 @Override
1160 public int getBatteryLevel() {
1161 synchronized (mLock) {
Yifan Honge41e9392017-11-06 12:56:59 -08001162 return mHealthInfo.batteryLevel;
Jeff Brown21392762014-06-13 19:00:36 -07001163 }
1164 }
1165
1166 @Override
1167 public boolean getBatteryLevelLow() {
1168 synchronized (mLock) {
1169 return mBatteryLevelLow;
1170 }
1171 }
1172
1173 @Override
1174 public int getInvalidCharger() {
1175 synchronized (mLock) {
1176 return mInvalidCharger;
1177 }
1178 }
1179 }
Yifan Hong98852792017-10-12 11:35:14 -07001180
1181 /**
1182 * HealthServiceWrapper wraps the internal IHealth service and refreshes the service when
1183 * necessary.
1184 *
1185 * On new registration of IHealth service, {@link #onRegistration onRegistration} is called and
1186 * the internal service is refreshed.
1187 * On death of an existing IHealth service, the internal service is NOT cleared to avoid
1188 * race condition between death notification and new service notification. Hence,
1189 * a caller must check for transaction errors when calling into the service.
1190 *
1191 * @hide Should only be used internally.
1192 */
1193 @VisibleForTesting
1194 static final class HealthServiceWrapper {
1195 private static final String TAG = "HealthServiceWrapper";
1196 public static final String INSTANCE_HEALTHD = "backup";
1197 public static final String INSTANCE_VENDOR = "default";
1198 // All interesting instances, sorted by priority high -> low.
1199 private static final List<String> sAllInstances =
1200 Arrays.asList(INSTANCE_VENDOR, INSTANCE_HEALTHD);
1201
1202 private final IServiceNotification mNotification = new Notification();
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001203 private final HandlerThread mHandlerThread = new HandlerThread("HealthServiceRefresh");
Yifan Hong1fff9842017-10-27 13:53:10 -07001204 // These variables are fixed after init.
Yifan Hong98852792017-10-12 11:35:14 -07001205 private Callback mCallback;
1206 private IHealthSupplier mHealthSupplier;
Yifan Hong1fff9842017-10-27 13:53:10 -07001207 private String mInstanceName;
Yifan Hong98852792017-10-12 11:35:14 -07001208
Yifan Hong89d55c12017-10-11 11:29:01 -07001209 // Last IHealth service received.
Yifan Hong89d55c12017-10-11 11:29:01 -07001210 private final AtomicReference<IHealth> mLastService = new AtomicReference<>();
1211
Yifan Hong98852792017-10-12 11:35:14 -07001212 /**
1213 * init should be called after constructor. For testing purposes, init is not called by
1214 * constructor.
1215 */
1216 HealthServiceWrapper() {
1217 }
1218
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001219 IHealth getLastService() {
1220 return mLastService.get();
1221 }
1222
Yifan Hong98852792017-10-12 11:35:14 -07001223 /**
1224 * Start monitoring registration of new IHealth services. Only instances that are in
1225 * {@code sAllInstances} and in device / framework manifest are used. This function should
1226 * only be called once.
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001227 *
1228 * mCallback.onRegistration() is called synchronously (aka in init thread) before
1229 * this method returns.
1230 *
Yifan Hong98852792017-10-12 11:35:14 -07001231 * @throws RemoteException transaction error when talking to IServiceManager
1232 * @throws NoSuchElementException if one of the following cases:
1233 * - No service manager;
1234 * - none of {@code sAllInstances} are in manifests (i.e. not
1235 * available on this device), or none of these instances are available to current
1236 * process.
1237 * @throws NullPointerException when callback is null or supplier is null
1238 */
1239 void init(Callback callback,
1240 IServiceManagerSupplier managerSupplier,
1241 IHealthSupplier healthSupplier)
1242 throws RemoteException, NoSuchElementException, NullPointerException {
1243 if (callback == null || managerSupplier == null || healthSupplier == null)
1244 throw new NullPointerException();
1245
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001246 IServiceManager manager;
1247
Yifan Hong98852792017-10-12 11:35:14 -07001248 mCallback = callback;
1249 mHealthSupplier = healthSupplier;
1250
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001251 // Initialize mLastService and call callback for the first time (in init thread)
1252 IHealth newService = null;
Yifan Hong98852792017-10-12 11:35:14 -07001253 for (String name : sAllInstances) {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001254 traceBegin("HealthInitGetService_" + name);
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001255 try {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001256 newService = healthSupplier.get(name);
1257 } catch (NoSuchElementException ex) {
1258 /* ignored, handled below */
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001259 } finally {
1260 traceEnd();
Yifan Hong98852792017-10-12 11:35:14 -07001261 }
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001262 if (newService != null) {
1263 mInstanceName = name;
1264 mLastService.set(newService);
1265 break;
1266 }
Yifan Hong98852792017-10-12 11:35:14 -07001267 }
1268
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001269 if (mInstanceName == null || newService == null) {
Yifan Hong1fff9842017-10-27 13:53:10 -07001270 throw new NoSuchElementException(String.format(
1271 "No IHealth service instance among %s is available. Perhaps no permission?",
1272 sAllInstances.toString()));
1273 }
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001274 mCallback.onRegistration(null, newService, mInstanceName);
Yifan Hong1fff9842017-10-27 13:53:10 -07001275
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001276 // Register for future service registrations
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001277 traceBegin("HealthInitRegisterNotification");
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001278 mHandlerThread.start();
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001279 try {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001280 managerSupplier.get().registerForNotifications(
1281 IHealth.kInterfaceName, mInstanceName, mNotification);
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001282 } finally {
1283 traceEnd();
1284 }
Yifan Hong1fff9842017-10-27 13:53:10 -07001285 Slog.i(TAG, "health: HealthServiceWrapper listening to instance " + mInstanceName);
Yifan Hong98852792017-10-12 11:35:14 -07001286 }
1287
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001288 @VisibleForTesting
1289 HandlerThread getHandlerThread() {
1290 return mHandlerThread;
1291 }
1292
Yifan Hong98852792017-10-12 11:35:14 -07001293 interface Callback {
1294 /**
1295 * This function is invoked asynchronously when a new and related IServiceNotification
1296 * is received.
1297 * @param service the recently retrieved service from IServiceManager.
1298 * Can be a dead service before service notification of a new service is delivered.
1299 * Implementation must handle cases for {@link RemoteException}s when calling
1300 * into service.
1301 * @param instance instance name.
1302 */
Yifan Hong89d55c12017-10-11 11:29:01 -07001303 void onRegistration(IHealth oldService, IHealth newService, String instance);
Yifan Hong98852792017-10-12 11:35:14 -07001304 }
1305
1306 /**
1307 * Supplier of services.
1308 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1309 */
1310 interface IServiceManagerSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001311 default IServiceManager get() throws NoSuchElementException, RemoteException {
1312 return IServiceManager.getService();
1313 }
Yifan Hong98852792017-10-12 11:35:14 -07001314 }
1315 /**
1316 * Supplier of services.
1317 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1318 */
1319 interface IHealthSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001320 default IHealth get(String name) throws NoSuchElementException, RemoteException {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001321 return IHealth.getService(name, true /* retry */);
Yifan Hong89d55c12017-10-11 11:29:01 -07001322 }
Yifan Hong98852792017-10-12 11:35:14 -07001323 }
1324
1325 private class Notification extends IServiceNotification.Stub {
1326 @Override
1327 public final void onRegistration(String interfaceName, String instanceName,
1328 boolean preexisting) {
1329 if (!IHealth.kInterfaceName.equals(interfaceName)) return;
Yifan Hong1fff9842017-10-27 13:53:10 -07001330 if (!mInstanceName.equals(instanceName)) return;
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001331
1332 // This runnable only runs on mHandlerThread and ordering is ensured, hence
1333 // no locking is needed inside the runnable.
1334 mHandlerThread.getThreadHandler().post(new Runnable() {
1335 @Override
1336 public void run() {
1337 try {
1338 IHealth newService = mHealthSupplier.get(mInstanceName);
1339 IHealth oldService = mLastService.getAndSet(newService);
1340
1341 // preexisting may be inaccurate (race). Check for equality here.
1342 if (Objects.equals(newService, oldService)) return;
1343
1344 Slog.i(TAG, "health: new instance registered " + mInstanceName);
1345 mCallback.onRegistration(oldService, newService, mInstanceName);
1346 } catch (NoSuchElementException | RemoteException ex) {
1347 Slog.e(TAG, "health: Cannot get instance '" + mInstanceName
1348 + "': " + ex.getMessage() + ". Perhaps no permission?");
1349 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001350 }
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001351 });
Yifan Hong98852792017-10-12 11:35:14 -07001352 }
1353 }
1354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355}