blob: 924e736bab07cd327942ec835f8cd10aaebca43b [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
Yifan Honge41e9392017-11-06 12:56:59 -0800424 mBatteryLevelCritical = (mHealthInfo.batteryLevel <= mCriticalBatteryLevel);
425 if (mHealthInfo.chargerAcOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
Yifan Honge41e9392017-11-06 12:56:59 -0800427 } else if (mHealthInfo.chargerUsbOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Yifan Honge41e9392017-11-06 12:56:59 -0800429 } else if (mHealthInfo.chargerWirelessOnline) {
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700430 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 } else {
432 mPlugType = BATTERY_PLUGGED_NONE;
433 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700434
Jeff Browna4d82042012-10-02 19:11:19 -0700435 if (DEBUG) {
436 Slog.d(TAG, "Processing new values: "
Yifan Hong932190b2017-10-11 11:00:51 -0700437 + "info=" + mHealthInfo
Jeff Browna4d82042012-10-02 19:11:19 -0700438 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
439 + ", mPlugType=" + mPlugType);
440 }
441
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700442 // Let the battery stats keep track of the current level.
443 try {
Yifan Honge41e9392017-11-06 12:56:59 -0800444 mBatteryStats.setBatteryState(mHealthInfo.batteryStatus, mHealthInfo.batteryHealth,
445 mPlugType, mHealthInfo.batteryLevel, mHealthInfo.batteryTemperature,
446 mHealthInfo.batteryVoltage, mHealthInfo.batteryChargeCounter,
447 mHealthInfo.batteryFullCharge);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700448 } catch (RemoteException e) {
449 // Should never happen.
450 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700451
Jeff Browna4d82042012-10-02 19:11:19 -0700452 shutdownIfNoPowerLocked();
453 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700454
Yifan Honge41e9392017-11-06 12:56:59 -0800455 if (force || (mHealthInfo.batteryStatus != mLastBatteryStatus ||
456 mHealthInfo.batteryHealth != mLastBatteryHealth ||
457 mHealthInfo.batteryPresent != mLastBatteryPresent ||
458 mHealthInfo.batteryLevel != mLastBatteryLevel ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 mPlugType != mLastPlugType ||
Yifan Honge41e9392017-11-06 12:56:59 -0800460 mHealthInfo.batteryVoltage != mLastBatteryVoltage ||
461 mHealthInfo.batteryTemperature != mLastBatteryTemperature ||
462 mHealthInfo.maxChargingCurrent != mLastMaxChargingCurrent ||
463 mHealthInfo.maxChargingVoltage != mLastMaxChargingVoltage ||
464 mHealthInfo.batteryChargeCounter != mLastChargeCounter ||
Dianne Hackborn14272302014-06-10 23:13:02 -0700465 mInvalidCharger != mLastInvalidCharger)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 if (mPlugType != mLastPlugType) {
468 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
469 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 // There's no value in this data unless we've discharged at least once and the
472 // battery level has changed; so don't log until it does.
Yifan Honge41e9392017-11-06 12:56:59 -0800473 if (mDischargeStartTime != 0 && mDischargeStartLevel != mHealthInfo.batteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700474 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
475 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800476 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
Yifan Honge41e9392017-11-06 12:56:59 -0800477 mDischargeStartLevel, mHealthInfo.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800479 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 }
481 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
482 // charging -> discharging or we just powered up
483 mDischargeStartTime = SystemClock.elapsedRealtime();
Yifan Honge41e9392017-11-06 12:56:59 -0800484 mDischargeStartLevel = mHealthInfo.batteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 }
486 }
Yifan Honge41e9392017-11-06 12:56:59 -0800487 if (mHealthInfo.batteryStatus != mLastBatteryStatus ||
488 mHealthInfo.batteryHealth != mLastBatteryHealth ||
489 mHealthInfo.batteryPresent != mLastBatteryPresent ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800491 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
Yifan Honge41e9392017-11-06 12:56:59 -0800492 mHealthInfo.batteryStatus, mHealthInfo.batteryHealth, mHealthInfo.batteryPresent ? 1 : 0,
493 mPlugType, mHealthInfo.batteryTechnology);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
Yifan Honge41e9392017-11-06 12:56:59 -0800495 if (mHealthInfo.batteryLevel != mLastBatteryLevel) {
Dianne Hackborncf1171642013-07-12 17:26:02 -0700496 // Don't do this just from voltage or temperature changes, that is
497 // too noisy.
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800498 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
Yifan Honge41e9392017-11-06 12:56:59 -0800499 mHealthInfo.batteryLevel, mHealthInfo.batteryVoltage, mHealthInfo.batteryTemperature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
501 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
502 mPlugType == BATTERY_PLUGGED_NONE) {
503 // We want to make sure we log discharge cycle outliers
504 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700505 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
506 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800508
Dianne Hackborn14272302014-06-10 23:13:02 -0700509 if (!mBatteryLevelLow) {
510 // Should we now switch in to low battery mode?
511 if (mPlugType == BATTERY_PLUGGED_NONE
Yifan Honge41e9392017-11-06 12:56:59 -0800512 && mHealthInfo.batteryLevel <= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700513 mBatteryLevelLow = true;
514 }
515 } else {
516 // Should we now switch out of low battery mode?
517 if (mPlugType != BATTERY_PLUGGED_NONE) {
518 mBatteryLevelLow = false;
Yifan Honge41e9392017-11-06 12:56:59 -0800519 } else if (mHealthInfo.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700520 mBatteryLevelLow = false;
Yifan Honge41e9392017-11-06 12:56:59 -0800521 } else if (force && mHealthInfo.batteryLevel >= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700522 // If being forced, the previous state doesn't matter, we will just
523 // absolutely check to see if we are now above the warning level.
524 mBatteryLevelLow = false;
525 }
526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800527
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800528 mSequence++;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800529
Christopher Tate06ba5542009-04-09 16:03:56 -0700530 // Separate broadcast is sent for power connected / not connected
531 // since the standard intent will not wake any applications and some
532 // applications may want to have smart behavior based on this.
533 if (mPlugType != 0 && mLastPlugType == 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800534 final Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
535 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
536 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700537 mHandler.post(new Runnable() {
538 @Override
539 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700540 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
541 }
542 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700543 }
544 else if (mPlugType == 0 && mLastPlugType != 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800545 final Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
546 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
547 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700548 mHandler.post(new Runnable() {
549 @Override
550 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700551 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
552 }
553 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700554 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200555
Dianne Hackborn14272302014-06-10 23:13:02 -0700556 if (shouldSendBatteryLowLocked()) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700557 mSentLowBatteryBroadcast = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800558 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
559 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
560 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700561 mHandler.post(new Runnable() {
562 @Override
563 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700564 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
565 }
566 });
Dianne Hackborn532ea262017-03-17 17:50:55 -0700567 } else if (mSentLowBatteryBroadcast &&
Yifan Honge41e9392017-11-06 12:56:59 -0800568 mHealthInfo.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700569 mSentLowBatteryBroadcast = false;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800570 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
571 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
572 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700573 mHandler.post(new Runnable() {
574 @Override
575 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700576 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
577 }
578 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800580
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800581 // We are doing this after sending the above broadcasts, so anything processing
582 // them will get the new sequence number at that point. (See for example how testing
583 // of JobScheduler's BatteryController works.)
584 sendIntentLocked();
585
Joe Onoratode1b3592010-10-25 20:36:47 -0700586 // Update the battery LED
587 mLed.updateLightsLocked();
588
The Android Open Source Project10592532009-03-18 17:39:46 -0700589 // This needs to be done after sendIntent() so that we get the lastest battery stats.
590 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700591 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800593
Yifan Honge41e9392017-11-06 12:56:59 -0800594 mLastBatteryStatus = mHealthInfo.batteryStatus;
595 mLastBatteryHealth = mHealthInfo.batteryHealth;
596 mLastBatteryPresent = mHealthInfo.batteryPresent;
597 mLastBatteryLevel = mHealthInfo.batteryLevel;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700598 mLastPlugType = mPlugType;
Yifan Honge41e9392017-11-06 12:56:59 -0800599 mLastBatteryVoltage = mHealthInfo.batteryVoltage;
600 mLastBatteryTemperature = mHealthInfo.batteryTemperature;
601 mLastMaxChargingCurrent = mHealthInfo.maxChargingCurrent;
602 mLastMaxChargingVoltage = mHealthInfo.maxChargingVoltage;
603 mLastChargeCounter = mHealthInfo.batteryChargeCounter;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700604 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400605 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607 }
608
Jeff Browna4d82042012-10-02 19:11:19 -0700609 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700611 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800612 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
613 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800614
Yifan Honge41e9392017-11-06 12:56:59 -0800615 int icon = getIconLocked(mHealthInfo.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800617 intent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Yifan Honge41e9392017-11-06 12:56:59 -0800618 intent.putExtra(BatteryManager.EXTRA_STATUS, mHealthInfo.batteryStatus);
619 intent.putExtra(BatteryManager.EXTRA_HEALTH, mHealthInfo.batteryHealth);
620 intent.putExtra(BatteryManager.EXTRA_PRESENT, mHealthInfo.batteryPresent);
621 intent.putExtra(BatteryManager.EXTRA_LEVEL, mHealthInfo.batteryLevel);
Dianne Hackborn74ed6ec2017-11-21 16:33:44 -0800622 intent.putExtra(BatteryManager.EXTRA_BATTERY_LOW, mSentLowBatteryBroadcast);
Dianne Hackbornedd93162009-09-19 14:03:05 -0700623 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
624 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
625 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
Yifan Honge41e9392017-11-06 12:56:59 -0800626 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mHealthInfo.batteryVoltage);
627 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mHealthInfo.batteryTemperature);
628 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mHealthInfo.batteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400629 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
Yifan Honge41e9392017-11-06 12:56:59 -0800630 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mHealthInfo.maxChargingCurrent);
631 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE, mHealthInfo.maxChargingVoltage);
632 intent.putExtra(BatteryManager.EXTRA_CHARGE_COUNTER, mHealthInfo.batteryChargeCounter);
Jeff Browna4d82042012-10-02 19:11:19 -0700633 if (DEBUG) {
Yifan Hong932190b2017-10-11 11:00:51 -0700634 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. scale:" + BATTERY_SCALE
635 + ", info:" + mHealthInfo.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 }
637
Jeff Brown605ea692012-10-05 16:33:10 -0700638 mHandler.post(new Runnable() {
639 @Override
640 public void run() {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800641 ActivityManager.broadcastStickyIntent(intent, UserHandle.USER_ALL);
Jeff Brown605ea692012-10-05 16:33:10 -0700642 }
643 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645
Jeff Browna4d82042012-10-02 19:11:19 -0700646 private void logBatteryStatsLocked() {
Dianne Hackborn8c841092013-06-24 13:46:13 -0700647 IBinder batteryInfoService = ServiceManager.getService(BatteryStats.SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800648 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649
Dan Egnor18e93962010-02-10 19:27:58 -0800650 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
651 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
652
653 File dumpFile = null;
654 FileOutputStream dumpStream = null;
655 try {
656 // dump the service to a file
Dianne Hackborn8c841092013-06-24 13:46:13 -0700657 dumpFile = new File(DUMPSYS_DATA_PATH + BatteryStats.SERVICE_NAME + ".dump");
Dan Egnor18e93962010-02-10 19:27:58 -0800658 dumpStream = new FileOutputStream(dumpFile);
659 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700660 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800661
662 // add dump file to drop box
663 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
664 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800665 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800666 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800667 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800668 } finally {
669 // make sure we clean up
670 if (dumpStream != null) {
671 try {
672 dumpStream.close();
673 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
Dan Egnor18e93962010-02-10 19:27:58 -0800676 }
677 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800678 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800679 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 }
681 }
682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800683
Jeff Browna4d82042012-10-02 19:11:19 -0700684 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700686 String dischargeThresholdString = Settings.Global.getString(cr,
687 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
688 String durationThresholdString = Settings.Global.getString(cr,
689 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 if (dischargeThresholdString != null && durationThresholdString != null) {
692 try {
693 long durationThreshold = Long.parseLong(durationThresholdString);
694 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800695 if (duration <= durationThreshold &&
Yifan Honge41e9392017-11-06 12:56:59 -0800696 mDischargeStartLevel - mHealthInfo.batteryLevel >= dischargeThreshold) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700698 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 }
Jeff Browna4d82042012-10-02 19:11:19 -0700700 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700702 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
Yifan Honge41e9392017-11-06 12:56:59 -0800703 (mDischargeStartLevel - mHealthInfo.batteryLevel));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800705 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 durationThresholdString + " or " + dischargeThresholdString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
708 }
709 }
710
Jeff Browna4d82042012-10-02 19:11:19 -0700711 private int getIconLocked(int level) {
Yifan Honge41e9392017-11-06 12:56:59 -0800712 if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 return com.android.internal.R.drawable.stat_sys_battery_charge;
Yifan Honge41e9392017-11-06 12:56:59 -0800714 } else if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 return com.android.internal.R.drawable.stat_sys_battery;
Yifan Honge41e9392017-11-06 12:56:59 -0800716 } else if (mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
717 || mHealthInfo.batteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700718 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
Yifan Honge41e9392017-11-06 12:56:59 -0800719 && mHealthInfo.batteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800720 return com.android.internal.R.drawable.stat_sys_battery_charge;
721 } else {
722 return com.android.internal.R.drawable.stat_sys_battery;
723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 } else {
725 return com.android.internal.R.drawable.stat_sys_battery_unknown;
726 }
727 }
728
Dianne Hackborn2e441072015-10-28 18:00:57 -0700729 class Shell extends ShellCommand {
730 @Override
731 public int onCommand(String cmd) {
732 return onShellCommand(this, cmd);
733 }
734
735 @Override
736 public void onHelp() {
737 PrintWriter pw = getOutPrintWriter();
738 dumpHelp(pw);
739 }
740 }
741
742 static void dumpHelp(PrintWriter pw) {
743 pw.println("Battery service (battery) commands:");
744 pw.println(" help");
745 pw.println(" Print this help text.");
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700746 pw.println(" set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700747 pw.println(" Force a battery property value, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800748 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
749 pw.println(" unplug [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700750 pw.println(" Force battery unplugged, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800751 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
752 pw.println(" reset [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700753 pw.println(" Unfreeze battery state, returning to current hardware values.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800754 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
755 }
756
757 static final int OPTION_FORCE_UPDATE = 1<<0;
758
759 int parseOptions(Shell shell) {
760 String opt;
761 int opts = 0;
762 while ((opt = shell.getNextOption()) != null) {
763 if ("-f".equals(opt)) {
764 opts |= OPTION_FORCE_UPDATE;
765 }
766 }
767 return opts;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700768 }
769
770 int onShellCommand(Shell shell, String cmd) {
771 if (cmd == null) {
772 return shell.handleDefaultCommands(cmd);
773 }
774 PrintWriter pw = shell.getOutPrintWriter();
775 switch (cmd) {
776 case "unplug": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800777 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700778 getContext().enforceCallingOrSelfPermission(
779 android.Manifest.permission.DEVICE_POWER, null);
780 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700781 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700782 }
Yifan Honge41e9392017-11-06 12:56:59 -0800783 mHealthInfo.chargerAcOnline = false;
784 mHealthInfo.chargerUsbOnline = false;
785 mHealthInfo.chargerWirelessOnline = false;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700786 long ident = Binder.clearCallingIdentity();
787 try {
788 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800789 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700790 } finally {
791 Binder.restoreCallingIdentity(ident);
792 }
793 } break;
794 case "set": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800795 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700796 getContext().enforceCallingOrSelfPermission(
797 android.Manifest.permission.DEVICE_POWER, null);
798 final String key = shell.getNextArg();
799 if (key == null) {
800 pw.println("No property specified");
801 return -1;
802
803 }
804 final String value = shell.getNextArg();
805 if (value == null) {
806 pw.println("No value specified");
807 return -1;
808
809 }
810 try {
811 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700812 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700813 }
814 boolean update = true;
815 switch (key) {
Christopher Tate630d98b2017-03-07 14:12:26 -0800816 case "present":
Yifan Honge41e9392017-11-06 12:56:59 -0800817 mHealthInfo.batteryPresent = Integer.parseInt(value) != 0;
Christopher Tate630d98b2017-03-07 14:12:26 -0800818 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700819 case "ac":
Yifan Honge41e9392017-11-06 12:56:59 -0800820 mHealthInfo.chargerAcOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700821 break;
822 case "usb":
Yifan Honge41e9392017-11-06 12:56:59 -0800823 mHealthInfo.chargerUsbOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700824 break;
825 case "wireless":
Yifan Honge41e9392017-11-06 12:56:59 -0800826 mHealthInfo.chargerWirelessOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700827 break;
828 case "status":
Yifan Honge41e9392017-11-06 12:56:59 -0800829 mHealthInfo.batteryStatus = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700830 break;
831 case "level":
Yifan Honge41e9392017-11-06 12:56:59 -0800832 mHealthInfo.batteryLevel = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700833 break;
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700834 case "temp":
Yifan Honge41e9392017-11-06 12:56:59 -0800835 mHealthInfo.batteryTemperature = Integer.parseInt(value);
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700836 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700837 case "invalid":
838 mInvalidCharger = Integer.parseInt(value);
839 break;
840 default:
841 pw.println("Unknown set option: " + key);
842 update = false;
843 break;
844 }
845 if (update) {
846 long ident = Binder.clearCallingIdentity();
847 try {
848 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800849 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700850 } finally {
851 Binder.restoreCallingIdentity(ident);
852 }
853 }
854 } catch (NumberFormatException ex) {
855 pw.println("Bad value: " + value);
856 return -1;
857 }
858 } break;
859 case "reset": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800860 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700861 getContext().enforceCallingOrSelfPermission(
862 android.Manifest.permission.DEVICE_POWER, null);
863 long ident = Binder.clearCallingIdentity();
864 try {
865 if (mUpdatesStopped) {
866 mUpdatesStopped = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700867 copy(mHealthInfo, mLastHealthInfo);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800868 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700869 }
870 } finally {
871 Binder.restoreCallingIdentity(ident);
872 }
873 } break;
874 default:
875 return shell.handleDefaultCommands(cmd);
876 }
877 return 0;
878 }
879
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800880 private void processValuesFromShellLocked(PrintWriter pw, int opts) {
881 processValuesLocked((opts & OPTION_FORCE_UPDATE) != 0);
882 if ((opts & OPTION_FORCE_UPDATE) != 0) {
883 pw.println(mSequence);
884 }
885 }
886
Dianne Hackborn2e441072015-10-28 18:00:57 -0700887 private void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna4d82042012-10-02 19:11:19 -0700888 synchronized (mLock) {
889 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700890 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700891 if (mUpdatesStopped) {
892 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
893 }
Yifan Honge41e9392017-11-06 12:56:59 -0800894 pw.println(" AC powered: " + mHealthInfo.chargerAcOnline);
895 pw.println(" USB powered: " + mHealthInfo.chargerUsbOnline);
896 pw.println(" Wireless powered: " + mHealthInfo.chargerWirelessOnline);
897 pw.println(" Max charging current: " + mHealthInfo.maxChargingCurrent);
898 pw.println(" Max charging voltage: " + mHealthInfo.maxChargingVoltage);
899 pw.println(" Charge counter: " + mHealthInfo.batteryChargeCounter);
900 pw.println(" status: " + mHealthInfo.batteryStatus);
901 pw.println(" health: " + mHealthInfo.batteryHealth);
902 pw.println(" present: " + mHealthInfo.batteryPresent);
903 pw.println(" level: " + mHealthInfo.batteryLevel);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700904 pw.println(" scale: " + BATTERY_SCALE);
Yifan Honge41e9392017-11-06 12:56:59 -0800905 pw.println(" voltage: " + mHealthInfo.batteryVoltage);
906 pw.println(" temperature: " + mHealthInfo.batteryTemperature);
907 pw.println(" technology: " + mHealthInfo.batteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700908 } else {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700909 Shell shell = new Shell();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700910 shell.exec(mBinderService, null, fd, null, args, null, new ResultReceiver(null));
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
913 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700914
Netta Pe2a3cd82017-01-26 18:03:51 -0800915 private void dumpProto(FileDescriptor fd) {
916 final ProtoOutputStream proto = new ProtoOutputStream(fd);
917
918 synchronized (mLock) {
919 proto.write(BatteryServiceDumpProto.ARE_UPDATES_STOPPED, mUpdatesStopped);
Kweku Adamse6b00c22017-10-23 16:46:45 -0700920 int batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_NONE;
Yifan Honge41e9392017-11-06 12:56:59 -0800921 if (mHealthInfo.chargerAcOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700922 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_AC;
Yifan Honge41e9392017-11-06 12:56:59 -0800923 } else if (mHealthInfo.chargerUsbOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700924 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_USB;
Yifan Honge41e9392017-11-06 12:56:59 -0800925 } else if (mHealthInfo.chargerWirelessOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700926 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_WIRELESS;
Netta Pe2a3cd82017-01-26 18:03:51 -0800927 }
928 proto.write(BatteryServiceDumpProto.PLUGGED, batteryPluggedValue);
Yifan Honge41e9392017-11-06 12:56:59 -0800929 proto.write(BatteryServiceDumpProto.MAX_CHARGING_CURRENT, mHealthInfo.maxChargingCurrent);
930 proto.write(BatteryServiceDumpProto.MAX_CHARGING_VOLTAGE, mHealthInfo.maxChargingVoltage);
931 proto.write(BatteryServiceDumpProto.CHARGE_COUNTER, mHealthInfo.batteryChargeCounter);
932 proto.write(BatteryServiceDumpProto.STATUS, mHealthInfo.batteryStatus);
933 proto.write(BatteryServiceDumpProto.HEALTH, mHealthInfo.batteryHealth);
934 proto.write(BatteryServiceDumpProto.IS_PRESENT, mHealthInfo.batteryPresent);
935 proto.write(BatteryServiceDumpProto.LEVEL, mHealthInfo.batteryLevel);
Netta Pe2a3cd82017-01-26 18:03:51 -0800936 proto.write(BatteryServiceDumpProto.SCALE, BATTERY_SCALE);
Yifan Honge41e9392017-11-06 12:56:59 -0800937 proto.write(BatteryServiceDumpProto.VOLTAGE, mHealthInfo.batteryVoltage);
938 proto.write(BatteryServiceDumpProto.TEMPERATURE, mHealthInfo.batteryTemperature);
939 proto.write(BatteryServiceDumpProto.TECHNOLOGY, mHealthInfo.batteryTechnology);
Netta Pe2a3cd82017-01-26 18:03:51 -0800940 }
941 proto.flush();
942 }
943
Yifan Hong8cc18ef2017-10-31 12:27:47 -0700944 private static void traceBegin(String name) {
945 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, name);
946 }
947
948 private static void traceEnd() {
949 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
950 }
951
Jeff Browna4d82042012-10-02 19:11:19 -0700952 private final class Led {
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800953 private final Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700954
Jeff Browna4d82042012-10-02 19:11:19 -0700955 private final int mBatteryLowARGB;
956 private final int mBatteryMediumARGB;
957 private final int mBatteryFullARGB;
958 private final int mBatteryLedOn;
959 private final int mBatteryLedOff;
960
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800961 public Led(Context context, LightsManager lights) {
962 mBatteryLight = lights.getLight(LightsManager.LIGHT_ID_BATTERY);
Joe Onoratode1b3592010-10-25 20:36:47 -0700963
Jeff Browna4d82042012-10-02 19:11:19 -0700964 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700965 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700966 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700967 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700968 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700969 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700970 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700971 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700972 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700973 com.android.internal.R.integer.config_notificationsBatteryLedOff);
974 }
975
976 /**
977 * Synchronize on BatteryService.
978 */
Jeff Browna4d82042012-10-02 19:11:19 -0700979 public void updateLightsLocked() {
Yifan Honge41e9392017-11-06 12:56:59 -0800980 final int level = mHealthInfo.batteryLevel;
981 final int status = mHealthInfo.batteryStatus;
Joe Onoratode1b3592010-10-25 20:36:47 -0700982 if (level < mLowBatteryWarningLevel) {
983 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
984 // Solid red when battery is charging
985 mBatteryLight.setColor(mBatteryLowARGB);
986 } else {
987 // Flash red when battery is low and not charging
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800988 mBatteryLight.setFlashing(mBatteryLowARGB, Light.LIGHT_FLASH_TIMED,
Joe Onoratode1b3592010-10-25 20:36:47 -0700989 mBatteryLedOn, mBatteryLedOff);
990 }
991 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
992 || status == BatteryManager.BATTERY_STATUS_FULL) {
993 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
994 // Solid green when full or charging and nearly full
995 mBatteryLight.setColor(mBatteryFullARGB);
996 } else {
997 // Solid orange when charging and halfway full
998 mBatteryLight.setColor(mBatteryMediumARGB);
999 }
1000 } else {
1001 // No lights if not charging and not low
1002 mBatteryLight.turnOff();
1003 }
1004 }
1005 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001006
Yifan Hong89d55c12017-10-11 11:29:01 -07001007 private final class HealthHalCallback extends IHealthInfoCallback.Stub
1008 implements HealthServiceWrapper.Callback {
1009 @Override public void healthInfoChanged(HealthInfo props) {
1010 BatteryService.this.update(props);
1011 }
1012 // on new service registered
1013 @Override public void onRegistration(IHealth oldService, IHealth newService,
1014 String instance) {
1015 if (newService == null) return;
1016
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001017 traceBegin("HealthUnregisterCallback");
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001018 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001019 if (oldService != null) {
1020 int r = oldService.unregisterCallback(this);
1021 if (r != Result.SUCCESS) {
1022 Slog.w(TAG, "health: cannot unregister previous callback: " +
1023 Result.toString(r));
1024 }
1025 }
1026 } catch (RemoteException ex) {
1027 Slog.w(TAG, "health: cannot unregister previous callback (transaction error): "
1028 + ex.getMessage());
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001029 } finally {
1030 traceEnd();
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001031 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001032
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001033 traceBegin("HealthRegisterCallback");
Yifan Hong89d55c12017-10-11 11:29:01 -07001034 try {
1035 int r = newService.registerCallback(this);
1036 if (r != Result.SUCCESS) {
1037 Slog.w(TAG, "health: cannot register callback: " + Result.toString(r));
1038 return;
1039 }
1040 // registerCallback does NOT guarantee that update is called
1041 // immediately, so request a manual update here.
1042 newService.update();
1043 } catch (RemoteException ex) {
1044 Slog.e(TAG, "health: cannot register callback (transaction error): "
1045 + ex.getMessage());
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001046 } finally {
1047 traceEnd();
Yifan Hong89d55c12017-10-11 11:29:01 -07001048 }
1049 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001050 }
Jeff Brown21392762014-06-13 19:00:36 -07001051
1052 private final class BinderService extends Binder {
Dianne Hackborn2e441072015-10-28 18:00:57 -07001053 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001054 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown21392762014-06-13 19:00:36 -07001055
Netta Pe2a3cd82017-01-26 18:03:51 -08001056 if (args.length > 0 && "--proto".equals(args[0])) {
1057 dumpProto(fd);
1058 } else {
1059 dumpInternal(fd, pw, args);
1060 }
Dianne Hackborn2e441072015-10-28 18:00:57 -07001061 }
1062
1063 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001064 FileDescriptor err, String[] args, ShellCallback callback,
1065 ResultReceiver resultReceiver) {
1066 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Jeff Brown21392762014-06-13 19:00:36 -07001067 }
1068 }
1069
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001070 // Reduced IBatteryPropertiesRegistrar that only implements getProperty for usage
1071 // in BatteryManager.
1072 private final class BatteryPropertiesRegistrar extends IBatteryPropertiesRegistrar.Stub {
1073 public void registerListener(IBatteryPropertiesListener listener) {
1074 Slog.e(TAG, "health: must not call registerListener on battery properties");
1075 }
1076 public void unregisterListener(IBatteryPropertiesListener listener) {
1077 Slog.e(TAG, "health: must not call unregisterListener on battery properties");
1078 }
1079 public int getProperty(int id, final BatteryProperty prop) throws RemoteException {
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001080 traceBegin("HealthGetProperty");
1081 try {
1082 IHealth service = mHealthServiceWrapper.getLastService();
1083 if (service == null) throw new RemoteException("no health service");
1084 final MutableInt outResult = new MutableInt(Result.NOT_SUPPORTED);
1085 switch(id) {
1086 case BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER:
1087 service.getChargeCounter((int result, int value) -> {
1088 outResult.value = result;
1089 if (result == Result.SUCCESS) prop.setLong(value);
1090 });
1091 break;
1092 case BatteryManager.BATTERY_PROPERTY_CURRENT_NOW:
1093 service.getCurrentNow((int result, int value) -> {
1094 outResult.value = result;
1095 if (result == Result.SUCCESS) prop.setLong(value);
1096 });
1097 break;
1098 case BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE:
1099 service.getCurrentAverage((int result, int value) -> {
1100 outResult.value = result;
1101 if (result == Result.SUCCESS) prop.setLong(value);
1102 });
1103 break;
1104 case BatteryManager.BATTERY_PROPERTY_CAPACITY:
1105 service.getCapacity((int result, int value) -> {
1106 outResult.value = result;
1107 if (result == Result.SUCCESS) prop.setLong(value);
1108 });
1109 break;
1110 case BatteryManager.BATTERY_PROPERTY_STATUS:
1111 service.getChargeStatus((int result, int value) -> {
1112 outResult.value = result;
1113 if (result == Result.SUCCESS) prop.setLong(value);
1114 });
1115 break;
1116 case BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER:
1117 service.getEnergyCounter((int result, long value) -> {
1118 outResult.value = result;
1119 if (result == Result.SUCCESS) prop.setLong(value);
1120 });
1121 break;
1122 }
1123 return outResult.value;
1124 } finally {
1125 traceEnd();
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001126 }
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001127 }
Yifan Hong7838fcb2017-10-24 16:06:27 -07001128 public void scheduleUpdate() throws RemoteException {
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001129 traceBegin("HealthScheduleUpdate");
1130 try {
1131 IHealth service = mHealthServiceWrapper.getLastService();
1132 if (service == null) throw new RemoteException("no health service");
1133 service.update();
1134 } finally {
1135 traceEnd();
1136 }
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001137 }
1138 }
1139
Jeff Brown21392762014-06-13 19:00:36 -07001140 private final class LocalService extends BatteryManagerInternal {
1141 @Override
1142 public boolean isPowered(int plugTypeSet) {
1143 synchronized (mLock) {
1144 return isPoweredLocked(plugTypeSet);
1145 }
1146 }
1147
1148 @Override
1149 public int getPlugType() {
1150 synchronized (mLock) {
1151 return mPlugType;
1152 }
1153 }
1154
1155 @Override
1156 public int getBatteryLevel() {
1157 synchronized (mLock) {
Yifan Honge41e9392017-11-06 12:56:59 -08001158 return mHealthInfo.batteryLevel;
Jeff Brown21392762014-06-13 19:00:36 -07001159 }
1160 }
1161
1162 @Override
1163 public boolean getBatteryLevelLow() {
1164 synchronized (mLock) {
1165 return mBatteryLevelLow;
1166 }
1167 }
1168
1169 @Override
1170 public int getInvalidCharger() {
1171 synchronized (mLock) {
1172 return mInvalidCharger;
1173 }
1174 }
1175 }
Yifan Hong98852792017-10-12 11:35:14 -07001176
1177 /**
1178 * HealthServiceWrapper wraps the internal IHealth service and refreshes the service when
1179 * necessary.
1180 *
1181 * On new registration of IHealth service, {@link #onRegistration onRegistration} is called and
1182 * the internal service is refreshed.
1183 * On death of an existing IHealth service, the internal service is NOT cleared to avoid
1184 * race condition between death notification and new service notification. Hence,
1185 * a caller must check for transaction errors when calling into the service.
1186 *
1187 * @hide Should only be used internally.
1188 */
1189 @VisibleForTesting
1190 static final class HealthServiceWrapper {
1191 private static final String TAG = "HealthServiceWrapper";
1192 public static final String INSTANCE_HEALTHD = "backup";
1193 public static final String INSTANCE_VENDOR = "default";
1194 // All interesting instances, sorted by priority high -> low.
1195 private static final List<String> sAllInstances =
1196 Arrays.asList(INSTANCE_VENDOR, INSTANCE_HEALTHD);
1197
1198 private final IServiceNotification mNotification = new Notification();
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001199 private final HandlerThread mHandlerThread = new HandlerThread("HealthServiceRefresh");
Yifan Hong1fff9842017-10-27 13:53:10 -07001200 // These variables are fixed after init.
Yifan Hong98852792017-10-12 11:35:14 -07001201 private Callback mCallback;
1202 private IHealthSupplier mHealthSupplier;
Yifan Hong1fff9842017-10-27 13:53:10 -07001203 private String mInstanceName;
Yifan Hong98852792017-10-12 11:35:14 -07001204
Yifan Hong89d55c12017-10-11 11:29:01 -07001205 // Last IHealth service received.
Yifan Hong89d55c12017-10-11 11:29:01 -07001206 private final AtomicReference<IHealth> mLastService = new AtomicReference<>();
1207
Yifan Hong98852792017-10-12 11:35:14 -07001208 /**
1209 * init should be called after constructor. For testing purposes, init is not called by
1210 * constructor.
1211 */
1212 HealthServiceWrapper() {
1213 }
1214
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001215 IHealth getLastService() {
1216 return mLastService.get();
1217 }
1218
Yifan Hong98852792017-10-12 11:35:14 -07001219 /**
1220 * Start monitoring registration of new IHealth services. Only instances that are in
1221 * {@code sAllInstances} and in device / framework manifest are used. This function should
1222 * only be called once.
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001223 *
1224 * mCallback.onRegistration() is called synchronously (aka in init thread) before
1225 * this method returns.
1226 *
Yifan Hong98852792017-10-12 11:35:14 -07001227 * @throws RemoteException transaction error when talking to IServiceManager
1228 * @throws NoSuchElementException if one of the following cases:
1229 * - No service manager;
1230 * - none of {@code sAllInstances} are in manifests (i.e. not
1231 * available on this device), or none of these instances are available to current
1232 * process.
1233 * @throws NullPointerException when callback is null or supplier is null
1234 */
1235 void init(Callback callback,
1236 IServiceManagerSupplier managerSupplier,
1237 IHealthSupplier healthSupplier)
1238 throws RemoteException, NoSuchElementException, NullPointerException {
1239 if (callback == null || managerSupplier == null || healthSupplier == null)
1240 throw new NullPointerException();
1241
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001242 IServiceManager manager;
1243
Yifan Hong98852792017-10-12 11:35:14 -07001244 mCallback = callback;
1245 mHealthSupplier = healthSupplier;
1246
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001247 // Initialize mLastService and call callback for the first time (in init thread)
1248 IHealth newService = null;
Yifan Hong98852792017-10-12 11:35:14 -07001249 for (String name : sAllInstances) {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001250 traceBegin("HealthInitGetService_" + name);
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001251 try {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001252 newService = healthSupplier.get(name);
1253 } catch (NoSuchElementException ex) {
1254 /* ignored, handled below */
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001255 } finally {
1256 traceEnd();
Yifan Hong98852792017-10-12 11:35:14 -07001257 }
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001258 if (newService != null) {
1259 mInstanceName = name;
1260 mLastService.set(newService);
1261 break;
1262 }
Yifan Hong98852792017-10-12 11:35:14 -07001263 }
1264
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001265 if (mInstanceName == null || newService == null) {
Yifan Hong1fff9842017-10-27 13:53:10 -07001266 throw new NoSuchElementException(String.format(
1267 "No IHealth service instance among %s is available. Perhaps no permission?",
1268 sAllInstances.toString()));
1269 }
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001270 mCallback.onRegistration(null, newService, mInstanceName);
Yifan Hong1fff9842017-10-27 13:53:10 -07001271
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001272 // Register for future service registrations
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001273 traceBegin("HealthInitRegisterNotification");
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001274 mHandlerThread.start();
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001275 try {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001276 managerSupplier.get().registerForNotifications(
1277 IHealth.kInterfaceName, mInstanceName, mNotification);
Yifan Hong8cc18ef2017-10-31 12:27:47 -07001278 } finally {
1279 traceEnd();
1280 }
Yifan Hong1fff9842017-10-27 13:53:10 -07001281 Slog.i(TAG, "health: HealthServiceWrapper listening to instance " + mInstanceName);
Yifan Hong98852792017-10-12 11:35:14 -07001282 }
1283
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001284 @VisibleForTesting
1285 HandlerThread getHandlerThread() {
1286 return mHandlerThread;
1287 }
1288
Yifan Hong98852792017-10-12 11:35:14 -07001289 interface Callback {
1290 /**
1291 * This function is invoked asynchronously when a new and related IServiceNotification
1292 * is received.
1293 * @param service the recently retrieved service from IServiceManager.
1294 * Can be a dead service before service notification of a new service is delivered.
1295 * Implementation must handle cases for {@link RemoteException}s when calling
1296 * into service.
1297 * @param instance instance name.
1298 */
Yifan Hong89d55c12017-10-11 11:29:01 -07001299 void onRegistration(IHealth oldService, IHealth newService, String instance);
Yifan Hong98852792017-10-12 11:35:14 -07001300 }
1301
1302 /**
1303 * Supplier of services.
1304 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1305 */
1306 interface IServiceManagerSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001307 default IServiceManager get() throws NoSuchElementException, RemoteException {
1308 return IServiceManager.getService();
1309 }
Yifan Hong98852792017-10-12 11:35:14 -07001310 }
1311 /**
1312 * Supplier of services.
1313 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1314 */
1315 interface IHealthSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001316 default IHealth get(String name) throws NoSuchElementException, RemoteException {
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001317 return IHealth.getService(name, true /* retry */);
Yifan Hong89d55c12017-10-11 11:29:01 -07001318 }
Yifan Hong98852792017-10-12 11:35:14 -07001319 }
1320
1321 private class Notification extends IServiceNotification.Stub {
1322 @Override
1323 public final void onRegistration(String interfaceName, String instanceName,
1324 boolean preexisting) {
1325 if (!IHealth.kInterfaceName.equals(interfaceName)) return;
Yifan Hong1fff9842017-10-27 13:53:10 -07001326 if (!mInstanceName.equals(instanceName)) return;
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001327
1328 // This runnable only runs on mHandlerThread and ordering is ensured, hence
1329 // no locking is needed inside the runnable.
1330 mHandlerThread.getThreadHandler().post(new Runnable() {
1331 @Override
1332 public void run() {
1333 try {
1334 IHealth newService = mHealthSupplier.get(mInstanceName);
1335 IHealth oldService = mLastService.getAndSet(newService);
1336
1337 // preexisting may be inaccurate (race). Check for equality here.
1338 if (Objects.equals(newService, oldService)) return;
1339
1340 Slog.i(TAG, "health: new instance registered " + mInstanceName);
1341 mCallback.onRegistration(oldService, newService, mInstanceName);
1342 } catch (NoSuchElementException | RemoteException ex) {
1343 Slog.e(TAG, "health: Cannot get instance '" + mInstanceName
1344 + "': " + ex.getMessage() + ". Perhaps no permission?");
1345 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001346 }
Yifan Hongcf9a8b22017-11-02 18:43:06 -07001347 });
Yifan Hong98852792017-10-12 11:35:14 -07001348 }
1349 }
1350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351}