blob: 68546bd2222180e698f5ccce6614476c402998e6 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Sudheer Shankafc46e9b2016-10-21 17:55:27 -070019import android.app.ActivityManagerInternal;
Dianne Hackborn14272302014-06-10 23:13:02 -070020import android.database.ContentObserver;
Dianne Hackborn8c841092013-06-24 13:46:13 -070021import android.os.BatteryStats;
Jeff Brown21392762014-06-13 19:00:36 -070022
Sudheer Shanka292637f2017-09-25 10:36:23 -070023import android.os.PowerManager;
Dianne Hackborn2e441072015-10-28 18:00:57 -070024import android.os.ResultReceiver;
Dianne Hackborn354736e2016-08-22 17:00:05 -070025import android.os.ShellCallback;
Dianne Hackborn2e441072015-10-28 18:00:57 -070026import android.os.ShellCommand;
Yifan Hong98852792017-10-12 11:35:14 -070027import com.android.internal.annotations.VisibleForTesting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import com.android.internal.app.IBatteryStats;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060029import com.android.internal.util.DumpUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import com.android.server.am.BatteryStatsService;
Adam Lesinskief2ea1f2013-12-05 16:48:06 -080031import com.android.server.lights.Light;
32import com.android.server.lights.LightsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Sudheer Shankadc589ac2016-11-10 15:30:17 -080034import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
38import android.content.pm.PackageManager;
Yifan Hong98852792017-10-12 11:35:14 -070039import android.hidl.manager.V1_0.IServiceManager;
40import android.hidl.manager.V1_0.IServiceNotification;
Yifan Hong932190b2017-10-11 11:00:51 -070041import android.hardware.health.V2_0.HealthInfo;
Yifan Hong89d55c12017-10-11 11:29:01 -070042import android.hardware.health.V2_0.IHealthInfoCallback;
Yifan Hong98852792017-10-12 11:35:14 -070043import android.hardware.health.V2_0.IHealth;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070044import android.hardware.health.V2_0.Result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.BatteryManager;
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;
Todd Poynor26faecc2013-05-22 18:54:48 -070052import android.os.IBatteryPropertiesListener;
53import android.os.IBatteryPropertiesRegistrar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.IBinder;
Dan Egnor18e93962010-02-10 19:27:58 -080055import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.RemoteException;
57import android.os.ServiceManager;
58import android.os.SystemClock;
59import android.os.UEventObserver;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070060import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.provider.Settings;
Netta Pe2a3cd82017-01-26 18:03:51 -080062import android.service.battery.BatteryServiceDumpProto;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.EventLog;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -070064import android.util.MutableInt;
Joe Onorato8a9b2202010-02-26 18:56:32 -080065import android.util.Slog;
Netta Pe2a3cd82017-01-26 18:03:51 -080066import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68import java.io.File;
69import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.io.FileOutputStream;
71import java.io.IOException;
72import java.io.PrintWriter;
73
Yifan Hong98852792017-10-12 11:35:14 -070074import java.util.Arrays;
75import java.util.List;
76import java.util.NoSuchElementException;
Yifan Hong89d55c12017-10-11 11:29:01 -070077import java.util.concurrent.atomic.AtomicReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79/**
80 * <p>BatteryService monitors the charging status, and charge level of the device
81 * battery. When these values change this service broadcasts the new values
82 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
83 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
84 * BATTERY_CHANGED} action.</p>
85 * <p>The new values are stored in the Intent data and can be retrieved by
86 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
87 * following keys:</p>
88 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
89 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
90 * <p>&quot;status&quot; - String, the current charging status.<br />
91 * <p>&quot;health&quot; - String, the current battery health.<br />
92 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
93 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
94 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
95 * into an AC power adapter; 2 if plugged in via USB.</p>
96 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
97 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
98 * a degree Centigrade</p>
99 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
Jeff Brown605ea692012-10-05 16:33:10 -0700100 *
101 * <p>
102 * The battery service may be called by the power manager while holding its locks so
103 * we take care to post all outcalls into the activity manager to a handler.
104 *
105 * FIXME: Ideally the power manager would perform all of its calls into the battery
106 * service asynchronously itself.
107 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 */
Jeff Brown21392762014-06-13 19:00:36 -0700109public final class BatteryService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 private static final String TAG = BatteryService.class.getSimpleName();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800111
Jeff Browna4d82042012-10-02 19:11:19 -0700112 private static final boolean DEBUG = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800113
Jeff Browna4d82042012-10-02 19:11:19 -0700114 private static final int BATTERY_SCALE = 100; // battery capacity is a percentage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Yifan Hong89d55c12017-10-11 11:29:01 -0700116 private static final long HEALTH_HAL_WAIT_MS = 1000;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 // Used locally for determining when to make a last ditch effort to log
119 // discharge stats before the device dies.
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700120 private int mCriticalBatteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
Jeff Sharkeyec43a6b2013-04-30 13:33:18 -0700122 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "--unplugged" };
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private static final String DUMPSYS_DATA_PATH = "/data/system/";
125
126 // This should probably be exposed in the API, though it's not critical
127 private static final int BATTERY_PLUGGED_NONE = 0;
128
129 private final Context mContext;
130 private final IBatteryStats mBatteryStats;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700131 BinderService mBinderService;
Jeff Brown605ea692012-10-05 16:33:10 -0700132 private final Handler mHandler;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800133
Jeff Browna4d82042012-10-02 19:11:19 -0700134 private final Object mLock = new Object();
135
Yifan Hong932190b2017-10-11 11:00:51 -0700136 private HealthInfo mHealthInfo;
137 private final HealthInfo mLastHealthInfo = new HealthInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private boolean mBatteryLevelCritical;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private int mLastBatteryStatus;
140 private int mLastBatteryHealth;
141 private boolean mLastBatteryPresent;
142 private int mLastBatteryLevel;
143 private int mLastBatteryVoltage;
144 private int mLastBatteryTemperature;
145 private boolean mLastBatteryLevelCritical;
Adrian Roos76dc5a52015-07-21 16:20:36 -0700146 private int mLastMaxChargingCurrent;
Badhri Jagan Sridharanf92fcfe2015-10-27 13:59:34 -0700147 private int mLastMaxChargingVoltage;
Ruchi Kandoi6361e222016-04-07 11:28:30 -0700148 private int mLastChargeCounter;
Jeff Browna4d82042012-10-02 19:11:19 -0700149
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800150 private int mSequence = 1;
151
Jeff Browna4d82042012-10-02 19:11:19 -0700152 private int mInvalidCharger;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700153 private int mLastInvalidCharger;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400154
155 private int mLowBatteryWarningLevel;
156 private int mLowBatteryCloseWarningLevel;
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700157 private int mShutdownBatteryTemperature;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mPlugType;
160 private int mLastPlugType = -1; // Extra state so we can detect first run
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800161
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700162 private boolean mBatteryLevelLow;
163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private long mDischargeStartTime;
165 private int mDischargeStartLevel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800166
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700167 private boolean mUpdatesStopped;
168
Joe Onoratode1b3592010-10-25 20:36:47 -0700169 private Led mLed;
170
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700171 private boolean mSentLowBatteryBroadcast = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800172
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700173 private ActivityManagerInternal mActivityManagerInternal;
174
Yifan Hong89d55c12017-10-11 11:29:01 -0700175 private HealthServiceWrapper mHealthServiceWrapper;
176 private HealthHalCallback mHealthHalCallback;
Yifan Hong1fd86f4c2017-10-09 16:50:33 -0700177 private BatteryPropertiesRegistrar mBatteryPropertiesRegistrar;
Yifan Hong89d55c12017-10-11 11:29:01 -0700178
Jeff Brown21392762014-06-13 19:00:36 -0700179 public BatteryService(Context context) {
180 super(context);
181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 mContext = context;
Jeff Brown605ea692012-10-05 16:33:10 -0700183 mHandler = new Handler(true /*async*/);
Jeff Brown21392762014-06-13 19:00:36 -0700184 mLed = new Led(context, getLocalService(LightsManager.class));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 mBatteryStats = BatteryStatsService.getService();
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700186 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700188 mCriticalBatteryLevel = mContext.getResources().getInteger(
189 com.android.internal.R.integer.config_criticalBatteryWarningLevel);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400190 mLowBatteryWarningLevel = mContext.getResources().getInteger(
191 com.android.internal.R.integer.config_lowBatteryWarningLevel);
Dianne Hackborn14272302014-06-10 23:13:02 -0700192 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
193 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700194 mShutdownBatteryTemperature = mContext.getResources().getInteger(
195 com.android.internal.R.integer.config_shutdownBatteryTemperature);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400196
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400197 // watch for invalid charger messages if the invalid_charger switch exists
198 if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700199 UEventObserver invalidChargerObserver = new UEventObserver() {
200 @Override
201 public void onUEvent(UEvent event) {
202 final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
203 synchronized (mLock) {
204 if (mInvalidCharger != invalidCharger) {
205 mInvalidCharger = invalidCharger;
206 }
207 }
208 }
209 };
210 invalidChargerObserver.startObserving(
Jeff Browna4d82042012-10-02 19:11:19 -0700211 "DEVPATH=/devices/virtual/switch/invalid_charger");
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400212 }
Jeff Brown21392762014-06-13 19:00:36 -0700213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Jeff Brown21392762014-06-13 19:00:36 -0700215 @Override
216 public void onStart() {
Yifan Hong89d55c12017-10-11 11:29:01 -0700217 registerHealthCallback();
Jeff Brown21392762014-06-13 19:00:36 -0700218
Dianne Hackborn2e441072015-10-28 18:00:57 -0700219 mBinderService = new BinderService();
220 publishBinderService("battery", mBinderService);
Yifan Hong1fd86f4c2017-10-09 16:50:33 -0700221 mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
222 publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
Jeff Brown21392762014-06-13 19:00:36 -0700223 publishLocalService(BatteryManagerInternal.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 }
225
Jeff Brown21392762014-06-13 19:00:36 -0700226 @Override
227 public void onBootPhase(int phase) {
228 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
229 // check our power situation now that it is safe to display the shutdown dialog.
230 synchronized (mLock) {
231 ContentObserver obs = new ContentObserver(mHandler) {
232 @Override
233 public void onChange(boolean selfChange) {
234 synchronized (mLock) {
235 updateBatteryWarningLevelLocked();
236 }
Dianne Hackborn14272302014-06-10 23:13:02 -0700237 }
Jeff Brown21392762014-06-13 19:00:36 -0700238 };
239 final ContentResolver resolver = mContext.getContentResolver();
240 resolver.registerContentObserver(Settings.Global.getUriFor(
241 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
242 false, obs, UserHandle.USER_ALL);
243 updateBatteryWarningLevelLocked();
244 }
Jeff Browna4d82042012-10-02 19:11:19 -0700245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 }
247
Yifan Hong89d55c12017-10-11 11:29:01 -0700248 private void registerHealthCallback() {
249 mHealthServiceWrapper = new HealthServiceWrapper();
250 mHealthHalCallback = new HealthHalCallback();
251 // IHealth is lazily retrieved.
252 try {
253 mHealthServiceWrapper.init(mHealthHalCallback,
254 new HealthServiceWrapper.IServiceManagerSupplier() {},
255 new HealthServiceWrapper.IHealthSupplier() {});
Yifan Hong78e8af12017-10-26 15:57:19 -0700256 } catch (RemoteException ex) {
257 Slog.e(TAG, "health: cannot register callback. (RemoteException)");
258 throw ex.rethrowFromSystemServer();
259 } catch (NoSuchElementException ex) {
260 Slog.e(TAG, "health: cannot register callback. (no supported health HAL service)");
261 throw ex;
Yifan Hong89d55c12017-10-11 11:29:01 -0700262 }
263
264 // init register for new service notifications, and IServiceManager should return the
265 // existing service in a near future. Wait for this.update() to instantiate
266 // the initial mHealthInfo.
Yifan Hong78e8af12017-10-26 15:57:19 -0700267 long beforeWait = SystemClock.uptimeMillis();
Yifan Hong89d55c12017-10-11 11:29:01 -0700268 synchronized (mLock) {
Yifan Hong78e8af12017-10-26 15:57:19 -0700269 while (mHealthInfo == null) {
270 Slog.i(TAG, "health: Waited " + (SystemClock.uptimeMillis() - beforeWait) +
271 "ms for callbacks. Waiting another " + HEALTH_HAL_WAIT_MS + " ms...");
Yifan Hong89d55c12017-10-11 11:29:01 -0700272 try {
Yifan Hong78e8af12017-10-26 15:57:19 -0700273 mLock.wait(HEALTH_HAL_WAIT_MS);
Yifan Hong89d55c12017-10-11 11:29:01 -0700274 } catch (InterruptedException ex) {
Yifan Hong78e8af12017-10-26 15:57:19 -0700275 Slog.i(TAG, "health: InterruptedException when waiting for update. "
276 + " Continuing...");
Yifan Hong89d55c12017-10-11 11:29:01 -0700277 }
278 }
Yifan Hong89d55c12017-10-11 11:29:01 -0700279 }
280
Yifan Hong78e8af12017-10-26 15:57:19 -0700281 Slog.i(TAG, "health: Waited " + (SystemClock.uptimeMillis() - beforeWait)
282 + "ms and received the update.");
Yifan Hong89d55c12017-10-11 11:29:01 -0700283 }
284
Jeff Brown21392762014-06-13 19:00:36 -0700285 private void updateBatteryWarningLevelLocked() {
Dianne Hackborn14272302014-06-10 23:13:02 -0700286 final ContentResolver resolver = mContext.getContentResolver();
287 int defWarnLevel = mContext.getResources().getInteger(
288 com.android.internal.R.integer.config_lowBatteryWarningLevel);
289 mLowBatteryWarningLevel = Settings.Global.getInt(resolver,
290 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, defWarnLevel);
291 if (mLowBatteryWarningLevel == 0) {
292 mLowBatteryWarningLevel = defWarnLevel;
293 }
294 if (mLowBatteryWarningLevel < mCriticalBatteryLevel) {
295 mLowBatteryWarningLevel = mCriticalBatteryLevel;
296 }
297 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
298 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
299 processValuesLocked(true);
300 }
301
Jeff Browna4d82042012-10-02 19:11:19 -0700302 private boolean isPoweredLocked(int plugTypeSet) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 // assume we are powered if battery state is unknown so
304 // the "stay on while plugged in" option will work.
Yifan Hong932190b2017-10-11 11:00:51 -0700305 if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 return true;
307 }
Yifan Hong932190b2017-10-11 11:00:51 -0700308 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_AC) != 0 && mHealthInfo.legacy.chargerAcOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700309 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
Yifan Hong932190b2017-10-11 11:00:51 -0700311 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_USB) != 0 && mHealthInfo.legacy.chargerUsbOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700312 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
Yifan Hong932190b2017-10-11 11:00:51 -0700314 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0 && mHealthInfo.legacy.chargerWirelessOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700315 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 }
Jeff Browna4d82042012-10-02 19:11:19 -0700317 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319
Jeff Brown21392762014-06-13 19:00:36 -0700320 private boolean shouldSendBatteryLowLocked() {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700321 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
322 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
323
324 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
325 * - is just un-plugged (previously was plugged) and battery level is
326 * less than or equal to WARNING, or
327 * - is not plugged and battery level falls to WARNING boundary
328 * (becomes <= mLowBatteryWarningLevel).
329 */
330 return !plugged
Yifan Hong932190b2017-10-11 11:00:51 -0700331 && mHealthInfo.legacy.batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
332 && mHealthInfo.legacy.batteryLevel <= mLowBatteryWarningLevel
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700333 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
334 }
335
Jeff Browna4d82042012-10-02 19:11:19 -0700336 private void shutdownIfNoPowerLocked() {
Mike Lockwood07a500f2009-08-12 09:56:44 -0400337 // shut down gracefully if our battery is critically low and we are not powered.
338 // wait until the system has booted before attempting to display the shutdown dialog.
Yifan Hong932190b2017-10-11 11:00:51 -0700339 if (mHealthInfo.legacy.batteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
Jeff Brown605ea692012-10-05 16:33:10 -0700340 mHandler.post(new Runnable() {
341 @Override
342 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700343 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700344 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
345 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700346 intent.putExtra(Intent.EXTRA_REASON,
347 PowerManager.SHUTDOWN_LOW_BATTERY);
Jeff Brown605ea692012-10-05 16:33:10 -0700348 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
349 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
350 }
351 }
352 });
Mike Lockwood07a500f2009-08-12 09:56:44 -0400353 }
354 }
355
Jeff Browna4d82042012-10-02 19:11:19 -0700356 private void shutdownIfOverTempLocked() {
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700357 // shut down gracefully if temperature is too high (> 68.0C by default)
358 // wait until the system has booted before attempting to display the
359 // shutdown dialog.
Yifan Hong932190b2017-10-11 11:00:51 -0700360 if (mHealthInfo.legacy.batteryTemperature > mShutdownBatteryTemperature) {
Jeff Brown605ea692012-10-05 16:33:10 -0700361 mHandler.post(new Runnable() {
362 @Override
363 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700364 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700365 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
366 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700367 intent.putExtra(Intent.EXTRA_REASON,
368 PowerManager.SHUTDOWN_BATTERY_THERMAL_STATE);
Jeff Brown605ea692012-10-05 16:33:10 -0700369 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
370 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
371 }
372 }
373 });
Eric Olsen6a362a92010-03-26 15:38:41 -0700374 }
375 }
376
Yifan Hong89d55c12017-10-11 11:29:01 -0700377 private void update(HealthInfo info) {
Todd Poynor26faecc2013-05-22 18:54:48 -0700378 synchronized (mLock) {
379 if (!mUpdatesStopped) {
Yifan Hong89d55c12017-10-11 11:29:01 -0700380 mHealthInfo = info;
Todd Poynor26faecc2013-05-22 18:54:48 -0700381 // Process the new values.
Dianne Hackborn14272302014-06-10 23:13:02 -0700382 processValuesLocked(false);
Yifan Hong89d55c12017-10-11 11:29:01 -0700383 mLock.notifyAll(); // for any waiters on new info
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800384 } else {
Yifan Hong89d55c12017-10-11 11:29:01 -0700385 copy(mLastHealthInfo, info);
Todd Poynor26faecc2013-05-22 18:54:48 -0700386 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700387 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389
Yifan Hong932190b2017-10-11 11:00:51 -0700390 private static void copy(HealthInfo dst, HealthInfo src) {
391 dst.legacy.chargerAcOnline = src.legacy.chargerAcOnline;
392 dst.legacy.chargerUsbOnline = src.legacy.chargerUsbOnline;
393 dst.legacy.chargerWirelessOnline = src.legacy.chargerWirelessOnline;
394 dst.legacy.maxChargingCurrent = src.legacy.maxChargingCurrent;
395 dst.legacy.maxChargingVoltage = src.legacy.maxChargingVoltage;
396 dst.legacy.batteryStatus = src.legacy.batteryStatus;
397 dst.legacy.batteryHealth = src.legacy.batteryHealth;
398 dst.legacy.batteryPresent = src.legacy.batteryPresent;
399 dst.legacy.batteryLevel = src.legacy.batteryLevel;
400 dst.legacy.batteryVoltage = src.legacy.batteryVoltage;
401 dst.legacy.batteryTemperature = src.legacy.batteryTemperature;
402 dst.legacy.batteryCurrent = src.legacy.batteryCurrent;
403 dst.legacy.batteryCycleCount = src.legacy.batteryCycleCount;
404 dst.legacy.batteryFullCharge = src.legacy.batteryFullCharge;
405 dst.legacy.batteryChargeCounter = src.legacy.batteryChargeCounter;
406 dst.legacy.batteryTechnology = src.legacy.batteryTechnology;
407 dst.batteryCurrentAverage = src.batteryCurrentAverage;
408 dst.batteryCapacity = src.batteryCapacity;
409 dst.energyCounter = src.energyCounter;
410 }
411
Dianne Hackborn14272302014-06-10 23:13:02 -0700412 private void processValuesLocked(boolean force) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700413 boolean logOutlier = false;
414 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700415
Yifan Hong932190b2017-10-11 11:00:51 -0700416 mBatteryLevelCritical = (mHealthInfo.legacy.batteryLevel <= mCriticalBatteryLevel);
417 if (mHealthInfo.legacy.chargerAcOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
Yifan Hong932190b2017-10-11 11:00:51 -0700419 } else if (mHealthInfo.legacy.chargerUsbOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Yifan Hong932190b2017-10-11 11:00:51 -0700421 } else if (mHealthInfo.legacy.chargerWirelessOnline) {
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700422 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 } else {
424 mPlugType = BATTERY_PLUGGED_NONE;
425 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700426
Jeff Browna4d82042012-10-02 19:11:19 -0700427 if (DEBUG) {
428 Slog.d(TAG, "Processing new values: "
Yifan Hong932190b2017-10-11 11:00:51 -0700429 + "info=" + mHealthInfo
Jeff Browna4d82042012-10-02 19:11:19 -0700430 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
431 + ", mPlugType=" + mPlugType);
432 }
433
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700434 // Let the battery stats keep track of the current level.
435 try {
Yifan Hong932190b2017-10-11 11:00:51 -0700436 mBatteryStats.setBatteryState(mHealthInfo.legacy.batteryStatus, mHealthInfo.legacy.batteryHealth,
437 mPlugType, mHealthInfo.legacy.batteryLevel, mHealthInfo.legacy.batteryTemperature,
438 mHealthInfo.legacy.batteryVoltage, mHealthInfo.legacy.batteryChargeCounter,
439 mHealthInfo.legacy.batteryFullCharge);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700440 } catch (RemoteException e) {
441 // Should never happen.
442 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700443
Jeff Browna4d82042012-10-02 19:11:19 -0700444 shutdownIfNoPowerLocked();
445 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700446
Yifan Hong932190b2017-10-11 11:00:51 -0700447 if (force || (mHealthInfo.legacy.batteryStatus != mLastBatteryStatus ||
448 mHealthInfo.legacy.batteryHealth != mLastBatteryHealth ||
449 mHealthInfo.legacy.batteryPresent != mLastBatteryPresent ||
450 mHealthInfo.legacy.batteryLevel != mLastBatteryLevel ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 mPlugType != mLastPlugType ||
Yifan Hong932190b2017-10-11 11:00:51 -0700452 mHealthInfo.legacy.batteryVoltage != mLastBatteryVoltage ||
453 mHealthInfo.legacy.batteryTemperature != mLastBatteryTemperature ||
454 mHealthInfo.legacy.maxChargingCurrent != mLastMaxChargingCurrent ||
455 mHealthInfo.legacy.maxChargingVoltage != mLastMaxChargingVoltage ||
456 mHealthInfo.legacy.batteryChargeCounter != mLastChargeCounter ||
Dianne Hackborn14272302014-06-10 23:13:02 -0700457 mInvalidCharger != mLastInvalidCharger)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 if (mPlugType != mLastPlugType) {
460 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
461 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 // There's no value in this data unless we've discharged at least once and the
464 // battery level has changed; so don't log until it does.
Yifan Hong932190b2017-10-11 11:00:51 -0700465 if (mDischargeStartTime != 0 && mDischargeStartLevel != mHealthInfo.legacy.batteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700466 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
467 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
Yifan Hong932190b2017-10-11 11:00:51 -0700469 mDischargeStartLevel, mHealthInfo.legacy.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800471 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
473 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
474 // charging -> discharging or we just powered up
475 mDischargeStartTime = SystemClock.elapsedRealtime();
Yifan Hong932190b2017-10-11 11:00:51 -0700476 mDischargeStartLevel = mHealthInfo.legacy.batteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478 }
Yifan Hong932190b2017-10-11 11:00:51 -0700479 if (mHealthInfo.legacy.batteryStatus != mLastBatteryStatus ||
480 mHealthInfo.legacy.batteryHealth != mLastBatteryHealth ||
481 mHealthInfo.legacy.batteryPresent != mLastBatteryPresent ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800483 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
Yifan Hong932190b2017-10-11 11:00:51 -0700484 mHealthInfo.legacy.batteryStatus, mHealthInfo.legacy.batteryHealth, mHealthInfo.legacy.batteryPresent ? 1 : 0,
485 mPlugType, mHealthInfo.legacy.batteryTechnology);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 }
Yifan Hong932190b2017-10-11 11:00:51 -0700487 if (mHealthInfo.legacy.batteryLevel != mLastBatteryLevel) {
Dianne Hackborncf1171642013-07-12 17:26:02 -0700488 // Don't do this just from voltage or temperature changes, that is
489 // too noisy.
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800490 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
Yifan Hong932190b2017-10-11 11:00:51 -0700491 mHealthInfo.legacy.batteryLevel, mHealthInfo.legacy.batteryVoltage, mHealthInfo.legacy.batteryTemperature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
494 mPlugType == BATTERY_PLUGGED_NONE) {
495 // We want to make sure we log discharge cycle outliers
496 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700497 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
498 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800500
Dianne Hackborn14272302014-06-10 23:13:02 -0700501 if (!mBatteryLevelLow) {
502 // Should we now switch in to low battery mode?
503 if (mPlugType == BATTERY_PLUGGED_NONE
Yifan Hong932190b2017-10-11 11:00:51 -0700504 && mHealthInfo.legacy.batteryLevel <= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700505 mBatteryLevelLow = true;
506 }
507 } else {
508 // Should we now switch out of low battery mode?
509 if (mPlugType != BATTERY_PLUGGED_NONE) {
510 mBatteryLevelLow = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700511 } else if (mHealthInfo.legacy.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700512 mBatteryLevelLow = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700513 } else if (force && mHealthInfo.legacy.batteryLevel >= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700514 // If being forced, the previous state doesn't matter, we will just
515 // absolutely check to see if we are now above the warning level.
516 mBatteryLevelLow = false;
517 }
518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800519
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800520 mSequence++;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
Christopher Tate06ba5542009-04-09 16:03:56 -0700522 // Separate broadcast is sent for power connected / not connected
523 // since the standard intent will not wake any applications and some
524 // applications may want to have smart behavior based on this.
525 if (mPlugType != 0 && mLastPlugType == 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800526 final Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
527 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
528 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700529 mHandler.post(new Runnable() {
530 @Override
531 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700532 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
533 }
534 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700535 }
536 else if (mPlugType == 0 && mLastPlugType != 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800537 final Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
538 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
539 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700540 mHandler.post(new Runnable() {
541 @Override
542 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700543 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
544 }
545 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700546 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200547
Dianne Hackborn14272302014-06-10 23:13:02 -0700548 if (shouldSendBatteryLowLocked()) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700549 mSentLowBatteryBroadcast = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800550 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
551 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
552 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700553 mHandler.post(new Runnable() {
554 @Override
555 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700556 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
557 }
558 });
Dianne Hackborn532ea262017-03-17 17:50:55 -0700559 } else if (mSentLowBatteryBroadcast &&
Yifan Hong932190b2017-10-11 11:00:51 -0700560 mHealthInfo.legacy.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700561 mSentLowBatteryBroadcast = false;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800562 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
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 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800572
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800573 // We are doing this after sending the above broadcasts, so anything processing
574 // them will get the new sequence number at that point. (See for example how testing
575 // of JobScheduler's BatteryController works.)
576 sendIntentLocked();
577
Joe Onoratode1b3592010-10-25 20:36:47 -0700578 // Update the battery LED
579 mLed.updateLightsLocked();
580
The Android Open Source Project10592532009-03-18 17:39:46 -0700581 // This needs to be done after sendIntent() so that we get the lastest battery stats.
582 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700583 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800585
Yifan Hong932190b2017-10-11 11:00:51 -0700586 mLastBatteryStatus = mHealthInfo.legacy.batteryStatus;
587 mLastBatteryHealth = mHealthInfo.legacy.batteryHealth;
588 mLastBatteryPresent = mHealthInfo.legacy.batteryPresent;
589 mLastBatteryLevel = mHealthInfo.legacy.batteryLevel;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700590 mLastPlugType = mPlugType;
Yifan Hong932190b2017-10-11 11:00:51 -0700591 mLastBatteryVoltage = mHealthInfo.legacy.batteryVoltage;
592 mLastBatteryTemperature = mHealthInfo.legacy.batteryTemperature;
593 mLastMaxChargingCurrent = mHealthInfo.legacy.maxChargingCurrent;
594 mLastMaxChargingVoltage = mHealthInfo.legacy.maxChargingVoltage;
595 mLastChargeCounter = mHealthInfo.legacy.batteryChargeCounter;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700596 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400597 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
599 }
600
Jeff Browna4d82042012-10-02 19:11:19 -0700601 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700603 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800604 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
605 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800606
Yifan Hong932190b2017-10-11 11:00:51 -0700607 int icon = getIconLocked(mHealthInfo.legacy.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800609 intent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Yifan Hong932190b2017-10-11 11:00:51 -0700610 intent.putExtra(BatteryManager.EXTRA_STATUS, mHealthInfo.legacy.batteryStatus);
611 intent.putExtra(BatteryManager.EXTRA_HEALTH, mHealthInfo.legacy.batteryHealth);
612 intent.putExtra(BatteryManager.EXTRA_PRESENT, mHealthInfo.legacy.batteryPresent);
613 intent.putExtra(BatteryManager.EXTRA_LEVEL, mHealthInfo.legacy.batteryLevel);
Dianne Hackbornedd93162009-09-19 14:03:05 -0700614 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
615 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
616 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
Yifan Hong932190b2017-10-11 11:00:51 -0700617 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mHealthInfo.legacy.batteryVoltage);
618 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mHealthInfo.legacy.batteryTemperature);
619 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mHealthInfo.legacy.batteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400620 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
Yifan Hong932190b2017-10-11 11:00:51 -0700621 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mHealthInfo.legacy.maxChargingCurrent);
622 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE, mHealthInfo.legacy.maxChargingVoltage);
623 intent.putExtra(BatteryManager.EXTRA_CHARGE_COUNTER, mHealthInfo.legacy.batteryChargeCounter);
Jeff Browna4d82042012-10-02 19:11:19 -0700624 if (DEBUG) {
Yifan Hong932190b2017-10-11 11:00:51 -0700625 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. scale:" + BATTERY_SCALE
626 + ", info:" + mHealthInfo.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 }
628
Jeff Brown605ea692012-10-05 16:33:10 -0700629 mHandler.post(new Runnable() {
630 @Override
631 public void run() {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800632 ActivityManager.broadcastStickyIntent(intent, UserHandle.USER_ALL);
Jeff Brown605ea692012-10-05 16:33:10 -0700633 }
634 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636
Jeff Browna4d82042012-10-02 19:11:19 -0700637 private void logBatteryStatsLocked() {
Dianne Hackborn8c841092013-06-24 13:46:13 -0700638 IBinder batteryInfoService = ServiceManager.getService(BatteryStats.SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800639 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640
Dan Egnor18e93962010-02-10 19:27:58 -0800641 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
642 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
643
644 File dumpFile = null;
645 FileOutputStream dumpStream = null;
646 try {
647 // dump the service to a file
Dianne Hackborn8c841092013-06-24 13:46:13 -0700648 dumpFile = new File(DUMPSYS_DATA_PATH + BatteryStats.SERVICE_NAME + ".dump");
Dan Egnor18e93962010-02-10 19:27:58 -0800649 dumpStream = new FileOutputStream(dumpFile);
650 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700651 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800652
653 // add dump file to drop box
654 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
655 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800656 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800657 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800658 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800659 } finally {
660 // make sure we clean up
661 if (dumpStream != null) {
662 try {
663 dumpStream.close();
664 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800665 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
Dan Egnor18e93962010-02-10 19:27:58 -0800667 }
668 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800669 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800670 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672 }
673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800674
Jeff Browna4d82042012-10-02 19:11:19 -0700675 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700677 String dischargeThresholdString = Settings.Global.getString(cr,
678 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
679 String durationThresholdString = Settings.Global.getString(cr,
680 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 if (dischargeThresholdString != null && durationThresholdString != null) {
683 try {
684 long durationThreshold = Long.parseLong(durationThresholdString);
685 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800686 if (duration <= durationThreshold &&
Yifan Hong932190b2017-10-11 11:00:51 -0700687 mDischargeStartLevel - mHealthInfo.legacy.batteryLevel >= dischargeThreshold) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700689 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 }
Jeff Browna4d82042012-10-02 19:11:19 -0700691 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700693 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
Yifan Hong932190b2017-10-11 11:00:51 -0700694 (mDischargeStartLevel - mHealthInfo.legacy.batteryLevel));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800696 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 durationThresholdString + " or " + dischargeThresholdString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
699 }
700 }
701
Jeff Browna4d82042012-10-02 19:11:19 -0700702 private int getIconLocked(int level) {
Yifan Hong932190b2017-10-11 11:00:51 -0700703 if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 return com.android.internal.R.drawable.stat_sys_battery_charge;
Yifan Hong932190b2017-10-11 11:00:51 -0700705 } else if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 return com.android.internal.R.drawable.stat_sys_battery;
Yifan Hong932190b2017-10-11 11:00:51 -0700707 } else if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
708 || mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700709 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
Yifan Hong932190b2017-10-11 11:00:51 -0700710 && mHealthInfo.legacy.batteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800711 return com.android.internal.R.drawable.stat_sys_battery_charge;
712 } else {
713 return com.android.internal.R.drawable.stat_sys_battery;
714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 } else {
716 return com.android.internal.R.drawable.stat_sys_battery_unknown;
717 }
718 }
719
Dianne Hackborn2e441072015-10-28 18:00:57 -0700720 class Shell extends ShellCommand {
721 @Override
722 public int onCommand(String cmd) {
723 return onShellCommand(this, cmd);
724 }
725
726 @Override
727 public void onHelp() {
728 PrintWriter pw = getOutPrintWriter();
729 dumpHelp(pw);
730 }
731 }
732
733 static void dumpHelp(PrintWriter pw) {
734 pw.println("Battery service (battery) commands:");
735 pw.println(" help");
736 pw.println(" Print this help text.");
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700737 pw.println(" set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700738 pw.println(" Force a battery property value, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800739 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
740 pw.println(" unplug [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700741 pw.println(" Force battery unplugged, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800742 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
743 pw.println(" reset [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700744 pw.println(" Unfreeze battery state, returning to current hardware values.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800745 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
746 }
747
748 static final int OPTION_FORCE_UPDATE = 1<<0;
749
750 int parseOptions(Shell shell) {
751 String opt;
752 int opts = 0;
753 while ((opt = shell.getNextOption()) != null) {
754 if ("-f".equals(opt)) {
755 opts |= OPTION_FORCE_UPDATE;
756 }
757 }
758 return opts;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700759 }
760
761 int onShellCommand(Shell shell, String cmd) {
762 if (cmd == null) {
763 return shell.handleDefaultCommands(cmd);
764 }
765 PrintWriter pw = shell.getOutPrintWriter();
766 switch (cmd) {
767 case "unplug": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800768 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700769 getContext().enforceCallingOrSelfPermission(
770 android.Manifest.permission.DEVICE_POWER, null);
771 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700772 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700773 }
Yifan Hong932190b2017-10-11 11:00:51 -0700774 mHealthInfo.legacy.chargerAcOnline = false;
775 mHealthInfo.legacy.chargerUsbOnline = false;
776 mHealthInfo.legacy.chargerWirelessOnline = false;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700777 long ident = Binder.clearCallingIdentity();
778 try {
779 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800780 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700781 } finally {
782 Binder.restoreCallingIdentity(ident);
783 }
784 } break;
785 case "set": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800786 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700787 getContext().enforceCallingOrSelfPermission(
788 android.Manifest.permission.DEVICE_POWER, null);
789 final String key = shell.getNextArg();
790 if (key == null) {
791 pw.println("No property specified");
792 return -1;
793
794 }
795 final String value = shell.getNextArg();
796 if (value == null) {
797 pw.println("No value specified");
798 return -1;
799
800 }
801 try {
802 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700803 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700804 }
805 boolean update = true;
806 switch (key) {
Christopher Tate630d98b2017-03-07 14:12:26 -0800807 case "present":
Yifan Hong932190b2017-10-11 11:00:51 -0700808 mHealthInfo.legacy.batteryPresent = Integer.parseInt(value) != 0;
Christopher Tate630d98b2017-03-07 14:12:26 -0800809 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700810 case "ac":
Yifan Hong932190b2017-10-11 11:00:51 -0700811 mHealthInfo.legacy.chargerAcOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700812 break;
813 case "usb":
Yifan Hong932190b2017-10-11 11:00:51 -0700814 mHealthInfo.legacy.chargerUsbOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700815 break;
816 case "wireless":
Yifan Hong932190b2017-10-11 11:00:51 -0700817 mHealthInfo.legacy.chargerWirelessOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700818 break;
819 case "status":
Yifan Hong932190b2017-10-11 11:00:51 -0700820 mHealthInfo.legacy.batteryStatus = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700821 break;
822 case "level":
Yifan Hong932190b2017-10-11 11:00:51 -0700823 mHealthInfo.legacy.batteryLevel = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700824 break;
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700825 case "temp":
Yifan Hong932190b2017-10-11 11:00:51 -0700826 mHealthInfo.legacy.batteryTemperature = Integer.parseInt(value);
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700827 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700828 case "invalid":
829 mInvalidCharger = Integer.parseInt(value);
830 break;
831 default:
832 pw.println("Unknown set option: " + key);
833 update = false;
834 break;
835 }
836 if (update) {
837 long ident = Binder.clearCallingIdentity();
838 try {
839 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800840 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700841 } finally {
842 Binder.restoreCallingIdentity(ident);
843 }
844 }
845 } catch (NumberFormatException ex) {
846 pw.println("Bad value: " + value);
847 return -1;
848 }
849 } break;
850 case "reset": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800851 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700852 getContext().enforceCallingOrSelfPermission(
853 android.Manifest.permission.DEVICE_POWER, null);
854 long ident = Binder.clearCallingIdentity();
855 try {
856 if (mUpdatesStopped) {
857 mUpdatesStopped = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700858 copy(mHealthInfo, mLastHealthInfo);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800859 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700860 }
861 } finally {
862 Binder.restoreCallingIdentity(ident);
863 }
864 } break;
865 default:
866 return shell.handleDefaultCommands(cmd);
867 }
868 return 0;
869 }
870
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800871 private void processValuesFromShellLocked(PrintWriter pw, int opts) {
872 processValuesLocked((opts & OPTION_FORCE_UPDATE) != 0);
873 if ((opts & OPTION_FORCE_UPDATE) != 0) {
874 pw.println(mSequence);
875 }
876 }
877
Dianne Hackborn2e441072015-10-28 18:00:57 -0700878 private void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna4d82042012-10-02 19:11:19 -0700879 synchronized (mLock) {
880 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700881 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700882 if (mUpdatesStopped) {
883 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
884 }
Yifan Hong932190b2017-10-11 11:00:51 -0700885 pw.println(" AC powered: " + mHealthInfo.legacy.chargerAcOnline);
886 pw.println(" USB powered: " + mHealthInfo.legacy.chargerUsbOnline);
887 pw.println(" Wireless powered: " + mHealthInfo.legacy.chargerWirelessOnline);
888 pw.println(" Max charging current: " + mHealthInfo.legacy.maxChargingCurrent);
889 pw.println(" Max charging voltage: " + mHealthInfo.legacy.maxChargingVoltage);
890 pw.println(" Charge counter: " + mHealthInfo.legacy.batteryChargeCounter);
891 pw.println(" status: " + mHealthInfo.legacy.batteryStatus);
892 pw.println(" health: " + mHealthInfo.legacy.batteryHealth);
893 pw.println(" present: " + mHealthInfo.legacy.batteryPresent);
894 pw.println(" level: " + mHealthInfo.legacy.batteryLevel);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700895 pw.println(" scale: " + BATTERY_SCALE);
Yifan Hong932190b2017-10-11 11:00:51 -0700896 pw.println(" voltage: " + mHealthInfo.legacy.batteryVoltage);
897 pw.println(" temperature: " + mHealthInfo.legacy.batteryTemperature);
898 pw.println(" technology: " + mHealthInfo.legacy.batteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700899 } else {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700900 Shell shell = new Shell();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700901 shell.exec(mBinderService, null, fd, null, args, null, new ResultReceiver(null));
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700905
Netta Pe2a3cd82017-01-26 18:03:51 -0800906 private void dumpProto(FileDescriptor fd) {
907 final ProtoOutputStream proto = new ProtoOutputStream(fd);
908
909 synchronized (mLock) {
910 proto.write(BatteryServiceDumpProto.ARE_UPDATES_STOPPED, mUpdatesStopped);
Kweku Adamse6b00c22017-10-23 16:46:45 -0700911 int batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_NONE;
Yifan Hong932190b2017-10-11 11:00:51 -0700912 if (mHealthInfo.legacy.chargerAcOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700913 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_AC;
Yifan Hong932190b2017-10-11 11:00:51 -0700914 } else if (mHealthInfo.legacy.chargerUsbOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700915 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_USB;
Yifan Hong932190b2017-10-11 11:00:51 -0700916 } else if (mHealthInfo.legacy.chargerWirelessOnline) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700917 batteryPluggedValue = BatteryManagerProto.PLUG_TYPE_WIRELESS;
Netta Pe2a3cd82017-01-26 18:03:51 -0800918 }
919 proto.write(BatteryServiceDumpProto.PLUGGED, batteryPluggedValue);
Yifan Hong932190b2017-10-11 11:00:51 -0700920 proto.write(BatteryServiceDumpProto.MAX_CHARGING_CURRENT, mHealthInfo.legacy.maxChargingCurrent);
921 proto.write(BatteryServiceDumpProto.MAX_CHARGING_VOLTAGE, mHealthInfo.legacy.maxChargingVoltage);
922 proto.write(BatteryServiceDumpProto.CHARGE_COUNTER, mHealthInfo.legacy.batteryChargeCounter);
923 proto.write(BatteryServiceDumpProto.STATUS, mHealthInfo.legacy.batteryStatus);
924 proto.write(BatteryServiceDumpProto.HEALTH, mHealthInfo.legacy.batteryHealth);
925 proto.write(BatteryServiceDumpProto.IS_PRESENT, mHealthInfo.legacy.batteryPresent);
926 proto.write(BatteryServiceDumpProto.LEVEL, mHealthInfo.legacy.batteryLevel);
Netta Pe2a3cd82017-01-26 18:03:51 -0800927 proto.write(BatteryServiceDumpProto.SCALE, BATTERY_SCALE);
Yifan Hong932190b2017-10-11 11:00:51 -0700928 proto.write(BatteryServiceDumpProto.VOLTAGE, mHealthInfo.legacy.batteryVoltage);
929 proto.write(BatteryServiceDumpProto.TEMPERATURE, mHealthInfo.legacy.batteryTemperature);
930 proto.write(BatteryServiceDumpProto.TECHNOLOGY, mHealthInfo.legacy.batteryTechnology);
Netta Pe2a3cd82017-01-26 18:03:51 -0800931 }
932 proto.flush();
933 }
934
Jeff Browna4d82042012-10-02 19:11:19 -0700935 private final class Led {
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800936 private final Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700937
Jeff Browna4d82042012-10-02 19:11:19 -0700938 private final int mBatteryLowARGB;
939 private final int mBatteryMediumARGB;
940 private final int mBatteryFullARGB;
941 private final int mBatteryLedOn;
942 private final int mBatteryLedOff;
943
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800944 public Led(Context context, LightsManager lights) {
945 mBatteryLight = lights.getLight(LightsManager.LIGHT_ID_BATTERY);
Joe Onoratode1b3592010-10-25 20:36:47 -0700946
Jeff Browna4d82042012-10-02 19:11:19 -0700947 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700948 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700949 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700950 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700951 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700952 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700953 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700954 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700955 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700956 com.android.internal.R.integer.config_notificationsBatteryLedOff);
957 }
958
959 /**
960 * Synchronize on BatteryService.
961 */
Jeff Browna4d82042012-10-02 19:11:19 -0700962 public void updateLightsLocked() {
Yifan Hong932190b2017-10-11 11:00:51 -0700963 final int level = mHealthInfo.legacy.batteryLevel;
964 final int status = mHealthInfo.legacy.batteryStatus;
Joe Onoratode1b3592010-10-25 20:36:47 -0700965 if (level < mLowBatteryWarningLevel) {
966 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
967 // Solid red when battery is charging
968 mBatteryLight.setColor(mBatteryLowARGB);
969 } else {
970 // Flash red when battery is low and not charging
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800971 mBatteryLight.setFlashing(mBatteryLowARGB, Light.LIGHT_FLASH_TIMED,
Joe Onoratode1b3592010-10-25 20:36:47 -0700972 mBatteryLedOn, mBatteryLedOff);
973 }
974 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
975 || status == BatteryManager.BATTERY_STATUS_FULL) {
976 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
977 // Solid green when full or charging and nearly full
978 mBatteryLight.setColor(mBatteryFullARGB);
979 } else {
980 // Solid orange when charging and halfway full
981 mBatteryLight.setColor(mBatteryMediumARGB);
982 }
983 } else {
984 // No lights if not charging and not low
985 mBatteryLight.turnOff();
986 }
987 }
988 }
Todd Poynor26faecc2013-05-22 18:54:48 -0700989
Yifan Hong89d55c12017-10-11 11:29:01 -0700990 private final class HealthHalCallback extends IHealthInfoCallback.Stub
991 implements HealthServiceWrapper.Callback {
992 @Override public void healthInfoChanged(HealthInfo props) {
993 BatteryService.this.update(props);
994 }
995 // on new service registered
996 @Override public void onRegistration(IHealth oldService, IHealth newService,
997 String instance) {
998 if (newService == null) return;
999
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001000 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001001 if (oldService != null) {
1002 int r = oldService.unregisterCallback(this);
1003 if (r != Result.SUCCESS) {
1004 Slog.w(TAG, "health: cannot unregister previous callback: " +
1005 Result.toString(r));
1006 }
1007 }
1008 } catch (RemoteException ex) {
1009 Slog.w(TAG, "health: cannot unregister previous callback (transaction error): "
1010 + ex.getMessage());
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001011 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001012
1013 try {
1014 int r = newService.registerCallback(this);
1015 if (r != Result.SUCCESS) {
1016 Slog.w(TAG, "health: cannot register callback: " + Result.toString(r));
1017 return;
1018 }
1019 // registerCallback does NOT guarantee that update is called
1020 // immediately, so request a manual update here.
1021 newService.update();
1022 } catch (RemoteException ex) {
1023 Slog.e(TAG, "health: cannot register callback (transaction error): "
1024 + ex.getMessage());
1025 }
1026 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001027 }
Jeff Brown21392762014-06-13 19:00:36 -07001028
1029 private final class BinderService extends Binder {
Dianne Hackborn2e441072015-10-28 18:00:57 -07001030 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001031 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown21392762014-06-13 19:00:36 -07001032
Netta Pe2a3cd82017-01-26 18:03:51 -08001033 if (args.length > 0 && "--proto".equals(args[0])) {
1034 dumpProto(fd);
1035 } else {
1036 dumpInternal(fd, pw, args);
1037 }
Dianne Hackborn2e441072015-10-28 18:00:57 -07001038 }
1039
1040 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001041 FileDescriptor err, String[] args, ShellCallback callback,
1042 ResultReceiver resultReceiver) {
1043 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Jeff Brown21392762014-06-13 19:00:36 -07001044 }
1045 }
1046
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001047 // Reduced IBatteryPropertiesRegistrar that only implements getProperty for usage
1048 // in BatteryManager.
1049 private final class BatteryPropertiesRegistrar extends IBatteryPropertiesRegistrar.Stub {
1050 public void registerListener(IBatteryPropertiesListener listener) {
1051 Slog.e(TAG, "health: must not call registerListener on battery properties");
1052 }
1053 public void unregisterListener(IBatteryPropertiesListener listener) {
1054 Slog.e(TAG, "health: must not call unregisterListener on battery properties");
1055 }
1056 public int getProperty(int id, final BatteryProperty prop) throws RemoteException {
1057 IHealth service = mHealthServiceWrapper.getLastService();
Yifan Hong7838fcb2017-10-24 16:06:27 -07001058 if (service == null) throw new RemoteException("no health service");
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001059 final MutableInt outResult = new MutableInt(Result.NOT_SUPPORTED);
1060 switch(id) {
1061 case BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER:
1062 service.getChargeCounter((int result, int value) -> {
1063 outResult.value = result;
1064 if (result == Result.SUCCESS) prop.setLong(value);
1065 });
1066 break;
1067 case BatteryManager.BATTERY_PROPERTY_CURRENT_NOW:
1068 service.getCurrentNow((int result, int value) -> {
1069 outResult.value = result;
1070 if (result == Result.SUCCESS) prop.setLong(value);
1071 });
1072 break;
1073 case BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE:
1074 service.getCurrentAverage((int result, int value) -> {
1075 outResult.value = result;
1076 if (result == Result.SUCCESS) prop.setLong(value);
1077 });
1078 break;
1079 case BatteryManager.BATTERY_PROPERTY_CAPACITY:
1080 service.getCapacity((int result, int value) -> {
1081 outResult.value = result;
1082 if (result == Result.SUCCESS) prop.setLong(value);
1083 });
1084 break;
1085 case BatteryManager.BATTERY_PROPERTY_STATUS:
1086 service.getChargeStatus((int result, int value) -> {
1087 outResult.value = result;
1088 if (result == Result.SUCCESS) prop.setLong(value);
1089 });
1090 break;
1091 case BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER:
1092 service.getEnergyCounter((int result, long value) -> {
1093 outResult.value = result;
1094 if (result == Result.SUCCESS) prop.setLong(value);
1095 });
1096 break;
1097 }
1098 return outResult.value;
1099 }
Yifan Hong7838fcb2017-10-24 16:06:27 -07001100 public void scheduleUpdate() throws RemoteException {
1101 IHealth service = mHealthServiceWrapper.getLastService();
1102 if (service == null) throw new RemoteException("no health service");
1103 service.update();
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001104 }
1105 }
1106
Jeff Brown21392762014-06-13 19:00:36 -07001107 private final class LocalService extends BatteryManagerInternal {
1108 @Override
1109 public boolean isPowered(int plugTypeSet) {
1110 synchronized (mLock) {
1111 return isPoweredLocked(plugTypeSet);
1112 }
1113 }
1114
1115 @Override
1116 public int getPlugType() {
1117 synchronized (mLock) {
1118 return mPlugType;
1119 }
1120 }
1121
1122 @Override
1123 public int getBatteryLevel() {
1124 synchronized (mLock) {
Yifan Hong932190b2017-10-11 11:00:51 -07001125 return mHealthInfo.legacy.batteryLevel;
Jeff Brown21392762014-06-13 19:00:36 -07001126 }
1127 }
1128
1129 @Override
1130 public boolean getBatteryLevelLow() {
1131 synchronized (mLock) {
1132 return mBatteryLevelLow;
1133 }
1134 }
1135
1136 @Override
1137 public int getInvalidCharger() {
1138 synchronized (mLock) {
1139 return mInvalidCharger;
1140 }
1141 }
1142 }
Yifan Hong98852792017-10-12 11:35:14 -07001143
1144 /**
1145 * HealthServiceWrapper wraps the internal IHealth service and refreshes the service when
1146 * necessary.
1147 *
1148 * On new registration of IHealth service, {@link #onRegistration onRegistration} is called and
1149 * the internal service is refreshed.
1150 * On death of an existing IHealth service, the internal service is NOT cleared to avoid
1151 * race condition between death notification and new service notification. Hence,
1152 * a caller must check for transaction errors when calling into the service.
1153 *
1154 * @hide Should only be used internally.
1155 */
1156 @VisibleForTesting
1157 static final class HealthServiceWrapper {
1158 private static final String TAG = "HealthServiceWrapper";
1159 public static final String INSTANCE_HEALTHD = "backup";
1160 public static final String INSTANCE_VENDOR = "default";
1161 // All interesting instances, sorted by priority high -> low.
1162 private static final List<String> sAllInstances =
1163 Arrays.asList(INSTANCE_VENDOR, INSTANCE_HEALTHD);
1164
1165 private final IServiceNotification mNotification = new Notification();
1166 private Callback mCallback;
1167 private IHealthSupplier mHealthSupplier;
1168
Yifan Hong89d55c12017-10-11 11:29:01 -07001169 private final Object mLastServiceSetLock = new Object();
1170 // Last IHealth service received.
1171 // set must be also be guarded with mLastServiceSetLock to ensure ordering.
1172 private final AtomicReference<IHealth> mLastService = new AtomicReference<>();
1173
Yifan Hong98852792017-10-12 11:35:14 -07001174 /**
1175 * init should be called after constructor. For testing purposes, init is not called by
1176 * constructor.
1177 */
1178 HealthServiceWrapper() {
1179 }
1180
Yifan Hong1fd86f4c2017-10-09 16:50:33 -07001181 IHealth getLastService() {
1182 return mLastService.get();
1183 }
1184
Yifan Hong98852792017-10-12 11:35:14 -07001185 /**
1186 * Start monitoring registration of new IHealth services. Only instances that are in
1187 * {@code sAllInstances} and in device / framework manifest are used. This function should
1188 * only be called once.
1189 * @throws RemoteException transaction error when talking to IServiceManager
1190 * @throws NoSuchElementException if one of the following cases:
1191 * - No service manager;
1192 * - none of {@code sAllInstances} are in manifests (i.e. not
1193 * available on this device), or none of these instances are available to current
1194 * process.
1195 * @throws NullPointerException when callback is null or supplier is null
1196 */
1197 void init(Callback callback,
1198 IServiceManagerSupplier managerSupplier,
1199 IHealthSupplier healthSupplier)
1200 throws RemoteException, NoSuchElementException, NullPointerException {
1201 if (callback == null || managerSupplier == null || healthSupplier == null)
1202 throw new NullPointerException();
1203
1204 mCallback = callback;
1205 mHealthSupplier = healthSupplier;
1206
1207 IServiceManager manager = managerSupplier.get();
1208 for (String name : sAllInstances) {
1209 if (manager.getTransport(IHealth.kInterfaceName, name) ==
1210 IServiceManager.Transport.EMPTY) {
1211 continue;
1212 }
1213
1214 manager.registerForNotifications(IHealth.kInterfaceName, name, mNotification);
1215 Slog.i(TAG, "health: HealthServiceWrapper listening to instance " + name);
1216 return;
1217 }
1218
1219 throw new NoSuchElementException(String.format(
1220 "No IHealth service instance among %s is available. Perhaps no permission?",
1221 sAllInstances.toString()));
1222 }
1223
1224 interface Callback {
1225 /**
1226 * This function is invoked asynchronously when a new and related IServiceNotification
1227 * is received.
1228 * @param service the recently retrieved service from IServiceManager.
1229 * Can be a dead service before service notification of a new service is delivered.
1230 * Implementation must handle cases for {@link RemoteException}s when calling
1231 * into service.
1232 * @param instance instance name.
1233 */
Yifan Hong89d55c12017-10-11 11:29:01 -07001234 void onRegistration(IHealth oldService, IHealth newService, String instance);
Yifan Hong98852792017-10-12 11:35:14 -07001235 }
1236
1237 /**
1238 * Supplier of services.
1239 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1240 */
1241 interface IServiceManagerSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001242 default IServiceManager get() throws NoSuchElementException, RemoteException {
1243 return IServiceManager.getService();
1244 }
Yifan Hong98852792017-10-12 11:35:14 -07001245 }
1246 /**
1247 * Supplier of services.
1248 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1249 */
1250 interface IHealthSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001251 default IHealth get(String name) throws NoSuchElementException, RemoteException {
1252 return IHealth.getService(name);
1253 }
Yifan Hong98852792017-10-12 11:35:14 -07001254 }
1255
1256 private class Notification extends IServiceNotification.Stub {
1257 @Override
1258 public final void onRegistration(String interfaceName, String instanceName,
1259 boolean preexisting) {
1260 if (!IHealth.kInterfaceName.equals(interfaceName)) return;
1261 if (!sAllInstances.contains(instanceName)) return;
1262 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001263 // ensures the order of multiple onRegistration on different threads.
1264 synchronized (mLastServiceSetLock) {
1265 IHealth newService = mHealthSupplier.get(instanceName);
1266 IHealth oldService = mLastService.getAndSet(newService);
1267 Slog.i(TAG, "health: new instance registered " + instanceName);
1268 mCallback.onRegistration(oldService, newService, instanceName);
1269 }
Yifan Hong98852792017-10-12 11:35:14 -07001270 } catch (NoSuchElementException | RemoteException ex) {
1271 Slog.e(TAG, "health: Cannot get instance '" + instanceName + "': " +
1272 ex.getMessage() + ". Perhaps no permission?");
1273 }
1274 }
1275 }
1276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277}