blob: 1978baab7fb49a5d2c88de33328787b985391f24 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070045import android.os.BatteryManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Binder;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070047import android.os.FileUtils;
Jeff Brown605ea692012-10-05 16:33:10 -070048import android.os.Handler;
Todd Poynor26faecc2013-05-22 18:54:48 -070049import android.os.IBatteryPropertiesListener;
50import android.os.IBatteryPropertiesRegistrar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.IBinder;
Dan Egnor18e93962010-02-10 19:27:58 -080052import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
54import android.os.ServiceManager;
55import android.os.SystemClock;
56import android.os.UEventObserver;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070057import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.provider.Settings;
Netta Pe2a3cd82017-01-26 18:03:51 -080059import android.service.battery.BatteryServiceDumpProto;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080061import android.util.Slog;
Netta Pe2a3cd82017-01-26 18:03:51 -080062import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
64import java.io.File;
65import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.io.FileOutputStream;
67import java.io.IOException;
68import java.io.PrintWriter;
69
Yifan Hong98852792017-10-12 11:35:14 -070070import java.util.Arrays;
71import java.util.List;
72import java.util.NoSuchElementException;
Yifan Hong89d55c12017-10-11 11:29:01 -070073import java.util.concurrent.atomic.AtomicReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
75/**
76 * <p>BatteryService monitors the charging status, and charge level of the device
77 * battery. When these values change this service broadcasts the new values
78 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
79 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
80 * BATTERY_CHANGED} action.</p>
81 * <p>The new values are stored in the Intent data and can be retrieved by
82 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
83 * following keys:</p>
84 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
85 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
86 * <p>&quot;status&quot; - String, the current charging status.<br />
87 * <p>&quot;health&quot; - String, the current battery health.<br />
88 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
89 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
90 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
91 * into an AC power adapter; 2 if plugged in via USB.</p>
92 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
93 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
94 * a degree Centigrade</p>
95 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
Jeff Brown605ea692012-10-05 16:33:10 -070096 *
97 * <p>
98 * The battery service may be called by the power manager while holding its locks so
99 * we take care to post all outcalls into the activity manager to a handler.
100 *
101 * FIXME: Ideally the power manager would perform all of its calls into the battery
102 * service asynchronously itself.
103 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 */
Jeff Brown21392762014-06-13 19:00:36 -0700105public final class BatteryService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private static final String TAG = BatteryService.class.getSimpleName();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800107
Jeff Browna4d82042012-10-02 19:11:19 -0700108 private static final boolean DEBUG = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800109
Jeff Browna4d82042012-10-02 19:11:19 -0700110 private static final int BATTERY_SCALE = 100; // battery capacity is a percentage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Yifan Hong89d55c12017-10-11 11:29:01 -0700112 private static final long HEALTH_HAL_WAIT_MS = 1000;
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 // Used locally for determining when to make a last ditch effort to log
115 // discharge stats before the device dies.
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700116 private int mCriticalBatteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Jeff Sharkeyec43a6b2013-04-30 13:33:18 -0700118 private static final String[] DUMPSYS_ARGS = new String[] { "--checkin", "--unplugged" };
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private static final String DUMPSYS_DATA_PATH = "/data/system/";
121
122 // This should probably be exposed in the API, though it's not critical
123 private static final int BATTERY_PLUGGED_NONE = 0;
124
125 private final Context mContext;
126 private final IBatteryStats mBatteryStats;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700127 BinderService mBinderService;
Jeff Brown605ea692012-10-05 16:33:10 -0700128 private final Handler mHandler;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800129
Jeff Browna4d82042012-10-02 19:11:19 -0700130 private final Object mLock = new Object();
131
Yifan Hong932190b2017-10-11 11:00:51 -0700132 private HealthInfo mHealthInfo;
133 private final HealthInfo mLastHealthInfo = new HealthInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private boolean mBatteryLevelCritical;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private int mLastBatteryStatus;
136 private int mLastBatteryHealth;
137 private boolean mLastBatteryPresent;
138 private int mLastBatteryLevel;
139 private int mLastBatteryVoltage;
140 private int mLastBatteryTemperature;
141 private boolean mLastBatteryLevelCritical;
Adrian Roos76dc5a52015-07-21 16:20:36 -0700142 private int mLastMaxChargingCurrent;
Badhri Jagan Sridharanf92fcfe2015-10-27 13:59:34 -0700143 private int mLastMaxChargingVoltage;
Ruchi Kandoi6361e222016-04-07 11:28:30 -0700144 private int mLastChargeCounter;
Jeff Browna4d82042012-10-02 19:11:19 -0700145
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800146 private int mSequence = 1;
147
Jeff Browna4d82042012-10-02 19:11:19 -0700148 private int mInvalidCharger;
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700149 private int mLastInvalidCharger;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400150
151 private int mLowBatteryWarningLevel;
152 private int mLowBatteryCloseWarningLevel;
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700153 private int mShutdownBatteryTemperature;
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private int mPlugType;
156 private int mLastPlugType = -1; // Extra state so we can detect first run
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800157
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700158 private boolean mBatteryLevelLow;
159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private long mDischargeStartTime;
161 private int mDischargeStartLevel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800162
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700163 private boolean mUpdatesStopped;
164
Joe Onoratode1b3592010-10-25 20:36:47 -0700165 private Led mLed;
166
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700167 private boolean mSentLowBatteryBroadcast = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800168
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700169 private ActivityManagerInternal mActivityManagerInternal;
170
Yifan Hong89d55c12017-10-11 11:29:01 -0700171 private HealthServiceWrapper mHealthServiceWrapper;
172 private HealthHalCallback mHealthHalCallback;
173
Jeff Brown21392762014-06-13 19:00:36 -0700174 public BatteryService(Context context) {
175 super(context);
176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 mContext = context;
Jeff Brown605ea692012-10-05 16:33:10 -0700178 mHandler = new Handler(true /*async*/);
Jeff Brown21392762014-06-13 19:00:36 -0700179 mLed = new Led(context, getLocalService(LightsManager.class));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 mBatteryStats = BatteryStatsService.getService();
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700181 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700183 mCriticalBatteryLevel = mContext.getResources().getInteger(
184 com.android.internal.R.integer.config_criticalBatteryWarningLevel);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400185 mLowBatteryWarningLevel = mContext.getResources().getInteger(
186 com.android.internal.R.integer.config_lowBatteryWarningLevel);
Dianne Hackborn14272302014-06-10 23:13:02 -0700187 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
188 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700189 mShutdownBatteryTemperature = mContext.getResources().getInteger(
190 com.android.internal.R.integer.config_shutdownBatteryTemperature);
Mike Lockwoodd81b1f42009-09-25 09:32:19 -0400191
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400192 // watch for invalid charger messages if the invalid_charger switch exists
193 if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700194 UEventObserver invalidChargerObserver = new UEventObserver() {
195 @Override
196 public void onUEvent(UEvent event) {
197 final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
198 synchronized (mLock) {
199 if (mInvalidCharger != invalidCharger) {
200 mInvalidCharger = invalidCharger;
201 }
202 }
203 }
204 };
205 invalidChargerObserver.startObserving(
Jeff Browna4d82042012-10-02 19:11:19 -0700206 "DEVPATH=/devices/virtual/switch/invalid_charger");
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400207 }
Jeff Brown21392762014-06-13 19:00:36 -0700208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Jeff Brown21392762014-06-13 19:00:36 -0700210 @Override
211 public void onStart() {
Yifan Hong89d55c12017-10-11 11:29:01 -0700212 registerHealthCallback();
Jeff Brown21392762014-06-13 19:00:36 -0700213
Dianne Hackborn2e441072015-10-28 18:00:57 -0700214 mBinderService = new BinderService();
215 publishBinderService("battery", mBinderService);
Jeff Brown21392762014-06-13 19:00:36 -0700216 publishLocalService(BatteryManagerInternal.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 }
218
Jeff Brown21392762014-06-13 19:00:36 -0700219 @Override
220 public void onBootPhase(int phase) {
221 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
222 // check our power situation now that it is safe to display the shutdown dialog.
223 synchronized (mLock) {
224 ContentObserver obs = new ContentObserver(mHandler) {
225 @Override
226 public void onChange(boolean selfChange) {
227 synchronized (mLock) {
228 updateBatteryWarningLevelLocked();
229 }
Dianne Hackborn14272302014-06-10 23:13:02 -0700230 }
Jeff Brown21392762014-06-13 19:00:36 -0700231 };
232 final ContentResolver resolver = mContext.getContentResolver();
233 resolver.registerContentObserver(Settings.Global.getUriFor(
234 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
235 false, obs, UserHandle.USER_ALL);
236 updateBatteryWarningLevelLocked();
237 }
Jeff Browna4d82042012-10-02 19:11:19 -0700238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
240
Yifan Hong89d55c12017-10-11 11:29:01 -0700241 private void registerHealthCallback() {
242 mHealthServiceWrapper = new HealthServiceWrapper();
243 mHealthHalCallback = new HealthHalCallback();
244 // IHealth is lazily retrieved.
245 try {
246 mHealthServiceWrapper.init(mHealthHalCallback,
247 new HealthServiceWrapper.IServiceManagerSupplier() {},
248 new HealthServiceWrapper.IHealthSupplier() {});
249 } catch (RemoteException | NoSuchElementException ex) {
250 Slog.w(TAG, "health: cannot register callback. "
251 + "BatteryService will be started with dummy values. Reason: "
252 + ex.getClass().getSimpleName() + ": " + ex.getMessage());
253 update(new HealthInfo());
254 return;
255 }
256
257 // init register for new service notifications, and IServiceManager should return the
258 // existing service in a near future. Wait for this.update() to instantiate
259 // the initial mHealthInfo.
260 long timeWaited = 0;
261 synchronized (mLock) {
262 long beforeWait = SystemClock.uptimeMillis();
263 while (mHealthInfo == null &&
264 (timeWaited = SystemClock.uptimeMillis() - beforeWait) < HEALTH_HAL_WAIT_MS) {
265 try {
266 mLock.wait(HEALTH_HAL_WAIT_MS - timeWaited);
267 } catch (InterruptedException ex) {
268 break;
269 }
270 }
271 if (mHealthInfo == null) {
272 Slog.w(TAG, "health: Waited " + timeWaited + "ms for callbacks but received "
273 + "nothing. BatteryService will be started with dummy values.");
274 update(new HealthInfo());
275 return;
276 }
277 }
278
279 if (DEBUG) {
280 Slog.d(TAG, "health: Waited " + timeWaited + "ms and received the update.");
281 }
282 }
283
Jeff Brown21392762014-06-13 19:00:36 -0700284 private void updateBatteryWarningLevelLocked() {
Dianne Hackborn14272302014-06-10 23:13:02 -0700285 final ContentResolver resolver = mContext.getContentResolver();
286 int defWarnLevel = mContext.getResources().getInteger(
287 com.android.internal.R.integer.config_lowBatteryWarningLevel);
288 mLowBatteryWarningLevel = Settings.Global.getInt(resolver,
289 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, defWarnLevel);
290 if (mLowBatteryWarningLevel == 0) {
291 mLowBatteryWarningLevel = defWarnLevel;
292 }
293 if (mLowBatteryWarningLevel < mCriticalBatteryLevel) {
294 mLowBatteryWarningLevel = mCriticalBatteryLevel;
295 }
296 mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
297 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
298 processValuesLocked(true);
299 }
300
Jeff Browna4d82042012-10-02 19:11:19 -0700301 private boolean isPoweredLocked(int plugTypeSet) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 // assume we are powered if battery state is unknown so
303 // the "stay on while plugged in" option will work.
Yifan Hong932190b2017-10-11 11:00:51 -0700304 if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 return true;
306 }
Yifan Hong932190b2017-10-11 11:00:51 -0700307 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_AC) != 0 && mHealthInfo.legacy.chargerAcOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700308 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 }
Yifan Hong932190b2017-10-11 11:00:51 -0700310 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_USB) != 0 && mHealthInfo.legacy.chargerUsbOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700311 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 }
Yifan Hong932190b2017-10-11 11:00:51 -0700313 if ((plugTypeSet & BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0 && mHealthInfo.legacy.chargerWirelessOnline) {
Jeff Browna4d82042012-10-02 19:11:19 -0700314 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 }
Jeff Browna4d82042012-10-02 19:11:19 -0700316 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 }
318
Jeff Brown21392762014-06-13 19:00:36 -0700319 private boolean shouldSendBatteryLowLocked() {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700320 final boolean plugged = mPlugType != BATTERY_PLUGGED_NONE;
321 final boolean oldPlugged = mLastPlugType != BATTERY_PLUGGED_NONE;
322
323 /* The ACTION_BATTERY_LOW broadcast is sent in these situations:
324 * - is just un-plugged (previously was plugged) and battery level is
325 * less than or equal to WARNING, or
326 * - is not plugged and battery level falls to WARNING boundary
327 * (becomes <= mLowBatteryWarningLevel).
328 */
329 return !plugged
Yifan Hong932190b2017-10-11 11:00:51 -0700330 && mHealthInfo.legacy.batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
331 && mHealthInfo.legacy.batteryLevel <= mLowBatteryWarningLevel
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700332 && (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
333 }
334
Jeff Browna4d82042012-10-02 19:11:19 -0700335 private void shutdownIfNoPowerLocked() {
Mike Lockwood07a500f2009-08-12 09:56:44 -0400336 // shut down gracefully if our battery is critically low and we are not powered.
337 // wait until the system has booted before attempting to display the shutdown dialog.
Yifan Hong932190b2017-10-11 11:00:51 -0700338 if (mHealthInfo.legacy.batteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
Jeff Brown605ea692012-10-05 16:33:10 -0700339 mHandler.post(new Runnable() {
340 @Override
341 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700342 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700343 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
344 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700345 intent.putExtra(Intent.EXTRA_REASON,
346 PowerManager.SHUTDOWN_LOW_BATTERY);
Jeff Brown605ea692012-10-05 16:33:10 -0700347 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
348 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
349 }
350 }
351 });
Mike Lockwood07a500f2009-08-12 09:56:44 -0400352 }
353 }
354
Jeff Browna4d82042012-10-02 19:11:19 -0700355 private void shutdownIfOverTempLocked() {
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700356 // shut down gracefully if temperature is too high (> 68.0C by default)
357 // wait until the system has booted before attempting to display the
358 // shutdown dialog.
Yifan Hong932190b2017-10-11 11:00:51 -0700359 if (mHealthInfo.legacy.batteryTemperature > mShutdownBatteryTemperature) {
Jeff Brown605ea692012-10-05 16:33:10 -0700360 mHandler.post(new Runnable() {
361 @Override
362 public void run() {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700363 if (mActivityManagerInternal.isSystemReady()) {
Jeff Brown605ea692012-10-05 16:33:10 -0700364 Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
365 intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
Sudheer Shanka292637f2017-09-25 10:36:23 -0700366 intent.putExtra(Intent.EXTRA_REASON,
367 PowerManager.SHUTDOWN_BATTERY_THERMAL_STATE);
Jeff Brown605ea692012-10-05 16:33:10 -0700368 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
369 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
370 }
371 }
372 });
Eric Olsen6a362a92010-03-26 15:38:41 -0700373 }
374 }
375
Yifan Hong89d55c12017-10-11 11:29:01 -0700376 private void update(HealthInfo info) {
Todd Poynor26faecc2013-05-22 18:54:48 -0700377 synchronized (mLock) {
378 if (!mUpdatesStopped) {
Yifan Hong89d55c12017-10-11 11:29:01 -0700379 mHealthInfo = info;
Todd Poynor26faecc2013-05-22 18:54:48 -0700380 // Process the new values.
Dianne Hackborn14272302014-06-10 23:13:02 -0700381 processValuesLocked(false);
Yifan Hong89d55c12017-10-11 11:29:01 -0700382 mLock.notifyAll(); // for any waiters on new info
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800383 } else {
Yifan Hong89d55c12017-10-11 11:29:01 -0700384 copy(mLastHealthInfo, info);
Todd Poynor26faecc2013-05-22 18:54:48 -0700385 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700386 }
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388
Yifan Hong932190b2017-10-11 11:00:51 -0700389 private static void copy(HealthInfo dst, HealthInfo src) {
390 dst.legacy.chargerAcOnline = src.legacy.chargerAcOnline;
391 dst.legacy.chargerUsbOnline = src.legacy.chargerUsbOnline;
392 dst.legacy.chargerWirelessOnline = src.legacy.chargerWirelessOnline;
393 dst.legacy.maxChargingCurrent = src.legacy.maxChargingCurrent;
394 dst.legacy.maxChargingVoltage = src.legacy.maxChargingVoltage;
395 dst.legacy.batteryStatus = src.legacy.batteryStatus;
396 dst.legacy.batteryHealth = src.legacy.batteryHealth;
397 dst.legacy.batteryPresent = src.legacy.batteryPresent;
398 dst.legacy.batteryLevel = src.legacy.batteryLevel;
399 dst.legacy.batteryVoltage = src.legacy.batteryVoltage;
400 dst.legacy.batteryTemperature = src.legacy.batteryTemperature;
401 dst.legacy.batteryCurrent = src.legacy.batteryCurrent;
402 dst.legacy.batteryCycleCount = src.legacy.batteryCycleCount;
403 dst.legacy.batteryFullCharge = src.legacy.batteryFullCharge;
404 dst.legacy.batteryChargeCounter = src.legacy.batteryChargeCounter;
405 dst.legacy.batteryTechnology = src.legacy.batteryTechnology;
406 dst.batteryCurrentAverage = src.batteryCurrentAverage;
407 dst.batteryCapacity = src.batteryCapacity;
408 dst.energyCounter = src.energyCounter;
409 }
410
Dianne Hackborn14272302014-06-10 23:13:02 -0700411 private void processValuesLocked(boolean force) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700412 boolean logOutlier = false;
413 long dischargeDuration = 0;
Joe Onoratoa7e4cf9b2009-07-28 18:18:20 -0700414
Yifan Hong932190b2017-10-11 11:00:51 -0700415 mBatteryLevelCritical = (mHealthInfo.legacy.batteryLevel <= mCriticalBatteryLevel);
416 if (mHealthInfo.legacy.chargerAcOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
Yifan Hong932190b2017-10-11 11:00:51 -0700418 } else if (mHealthInfo.legacy.chargerUsbOnline) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
Yifan Hong932190b2017-10-11 11:00:51 -0700420 } else if (mHealthInfo.legacy.chargerWirelessOnline) {
Brian Muramatsu37a37f42012-08-14 15:21:02 -0700421 mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 } else {
423 mPlugType = BATTERY_PLUGGED_NONE;
424 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700425
Jeff Browna4d82042012-10-02 19:11:19 -0700426 if (DEBUG) {
427 Slog.d(TAG, "Processing new values: "
Yifan Hong932190b2017-10-11 11:00:51 -0700428 + "info=" + mHealthInfo
Jeff Browna4d82042012-10-02 19:11:19 -0700429 + ", mBatteryLevelCritical=" + mBatteryLevelCritical
430 + ", mPlugType=" + mPlugType);
431 }
432
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700433 // Let the battery stats keep track of the current level.
434 try {
Yifan Hong932190b2017-10-11 11:00:51 -0700435 mBatteryStats.setBatteryState(mHealthInfo.legacy.batteryStatus, mHealthInfo.legacy.batteryHealth,
436 mPlugType, mHealthInfo.legacy.batteryLevel, mHealthInfo.legacy.batteryTemperature,
437 mHealthInfo.legacy.batteryVoltage, mHealthInfo.legacy.batteryChargeCounter,
438 mHealthInfo.legacy.batteryFullCharge);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700439 } catch (RemoteException e) {
440 // Should never happen.
441 }
Brian Muramatsuf3c74f32012-08-31 15:14:48 -0700442
Jeff Browna4d82042012-10-02 19:11:19 -0700443 shutdownIfNoPowerLocked();
444 shutdownIfOverTempLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700445
Yifan Hong932190b2017-10-11 11:00:51 -0700446 if (force || (mHealthInfo.legacy.batteryStatus != mLastBatteryStatus ||
447 mHealthInfo.legacy.batteryHealth != mLastBatteryHealth ||
448 mHealthInfo.legacy.batteryPresent != mLastBatteryPresent ||
449 mHealthInfo.legacy.batteryLevel != mLastBatteryLevel ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 mPlugType != mLastPlugType ||
Yifan Hong932190b2017-10-11 11:00:51 -0700451 mHealthInfo.legacy.batteryVoltage != mLastBatteryVoltage ||
452 mHealthInfo.legacy.batteryTemperature != mLastBatteryTemperature ||
453 mHealthInfo.legacy.maxChargingCurrent != mLastMaxChargingCurrent ||
454 mHealthInfo.legacy.maxChargingVoltage != mLastMaxChargingVoltage ||
455 mHealthInfo.legacy.batteryChargeCounter != mLastChargeCounter ||
Dianne Hackborn14272302014-06-10 23:13:02 -0700456 mInvalidCharger != mLastInvalidCharger)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 if (mPlugType != mLastPlugType) {
459 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
460 // discharging -> charging
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 // There's no value in this data unless we've discharged at least once and the
463 // battery level has changed; so don't log until it does.
Yifan Hong932190b2017-10-11 11:00:51 -0700464 if (mDischargeStartTime != 0 && mDischargeStartLevel != mHealthInfo.legacy.batteryLevel) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700465 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
466 logOutlier = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467 EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,
Yifan Hong932190b2017-10-11 11:00:51 -0700468 mDischargeStartLevel, mHealthInfo.legacy.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 // make sure we see a discharge event before logging again
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800470 mDischargeStartTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
472 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
473 // charging -> discharging or we just powered up
474 mDischargeStartTime = SystemClock.elapsedRealtime();
Yifan Hong932190b2017-10-11 11:00:51 -0700475 mDischargeStartLevel = mHealthInfo.legacy.batteryLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 }
477 }
Yifan Hong932190b2017-10-11 11:00:51 -0700478 if (mHealthInfo.legacy.batteryStatus != mLastBatteryStatus ||
479 mHealthInfo.legacy.batteryHealth != mLastBatteryHealth ||
480 mHealthInfo.legacy.batteryPresent != mLastBatteryPresent ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 mPlugType != mLastPlugType) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800482 EventLog.writeEvent(EventLogTags.BATTERY_STATUS,
Yifan Hong932190b2017-10-11 11:00:51 -0700483 mHealthInfo.legacy.batteryStatus, mHealthInfo.legacy.batteryHealth, mHealthInfo.legacy.batteryPresent ? 1 : 0,
484 mPlugType, mHealthInfo.legacy.batteryTechnology);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 }
Yifan Hong932190b2017-10-11 11:00:51 -0700486 if (mHealthInfo.legacy.batteryLevel != mLastBatteryLevel) {
Dianne Hackborncf1171642013-07-12 17:26:02 -0700487 // Don't do this just from voltage or temperature changes, that is
488 // too noisy.
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800489 EventLog.writeEvent(EventLogTags.BATTERY_LEVEL,
Yifan Hong932190b2017-10-11 11:00:51 -0700490 mHealthInfo.legacy.batteryLevel, mHealthInfo.legacy.batteryVoltage, mHealthInfo.legacy.batteryTemperature);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 }
492 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
493 mPlugType == BATTERY_PLUGGED_NONE) {
494 // We want to make sure we log discharge cycle outliers
495 // if the battery is about to die.
The Android Open Source Project10592532009-03-18 17:39:46 -0700496 dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;
497 logOutlier = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800499
Dianne Hackborn14272302014-06-10 23:13:02 -0700500 if (!mBatteryLevelLow) {
501 // Should we now switch in to low battery mode?
502 if (mPlugType == BATTERY_PLUGGED_NONE
Yifan Hong932190b2017-10-11 11:00:51 -0700503 && mHealthInfo.legacy.batteryLevel <= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700504 mBatteryLevelLow = true;
505 }
506 } else {
507 // Should we now switch out of low battery mode?
508 if (mPlugType != BATTERY_PLUGGED_NONE) {
509 mBatteryLevelLow = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700510 } else if (mHealthInfo.legacy.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700511 mBatteryLevelLow = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700512 } else if (force && mHealthInfo.legacy.batteryLevel >= mLowBatteryWarningLevel) {
Dianne Hackborn14272302014-06-10 23:13:02 -0700513 // If being forced, the previous state doesn't matter, we will just
514 // absolutely check to see if we are now above the warning level.
515 mBatteryLevelLow = false;
516 }
517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800518
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800519 mSequence++;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800520
Christopher Tate06ba5542009-04-09 16:03:56 -0700521 // Separate broadcast is sent for power connected / not connected
522 // since the standard intent will not wake any applications and some
523 // applications may want to have smart behavior based on this.
524 if (mPlugType != 0 && mLastPlugType == 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800525 final Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);
526 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
527 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700528 mHandler.post(new Runnable() {
529 @Override
530 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700531 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
532 }
533 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700534 }
535 else if (mPlugType == 0 && mLastPlugType != 0) {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800536 final Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);
537 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
538 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700539 mHandler.post(new Runnable() {
540 @Override
541 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700542 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
543 }
544 });
Christopher Tate06ba5542009-04-09 16:03:56 -0700545 }
Mihai Predaa82842f2009-04-29 15:05:56 +0200546
Dianne Hackborn14272302014-06-10 23:13:02 -0700547 if (shouldSendBatteryLowLocked()) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700548 mSentLowBatteryBroadcast = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800549 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);
550 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
551 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700552 mHandler.post(new Runnable() {
553 @Override
554 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700555 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
556 }
557 });
Dianne Hackborn532ea262017-03-17 17:50:55 -0700558 } else if (mSentLowBatteryBroadcast &&
Yifan Hong932190b2017-10-11 11:00:51 -0700559 mHealthInfo.legacy.batteryLevel >= mLowBatteryCloseWarningLevel) {
Dianne Hackborn8ec5b832009-07-01 21:19:35 -0700560 mSentLowBatteryBroadcast = false;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800561 final Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);
562 statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
563 statusIntent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Jeff Brown605ea692012-10-05 16:33:10 -0700564 mHandler.post(new Runnable() {
565 @Override
566 public void run() {
Jeff Brown605ea692012-10-05 16:33:10 -0700567 mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);
568 }
569 });
Mihai Predaa82842f2009-04-29 15:05:56 +0200570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800571
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800572 // We are doing this after sending the above broadcasts, so anything processing
573 // them will get the new sequence number at that point. (See for example how testing
574 // of JobScheduler's BatteryController works.)
575 sendIntentLocked();
576
Joe Onoratode1b3592010-10-25 20:36:47 -0700577 // Update the battery LED
578 mLed.updateLightsLocked();
579
The Android Open Source Project10592532009-03-18 17:39:46 -0700580 // This needs to be done after sendIntent() so that we get the lastest battery stats.
581 if (logOutlier && dischargeDuration != 0) {
Jeff Browna4d82042012-10-02 19:11:19 -0700582 logOutlierLocked(dischargeDuration);
The Android Open Source Project10592532009-03-18 17:39:46 -0700583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800584
Yifan Hong932190b2017-10-11 11:00:51 -0700585 mLastBatteryStatus = mHealthInfo.legacy.batteryStatus;
586 mLastBatteryHealth = mHealthInfo.legacy.batteryHealth;
587 mLastBatteryPresent = mHealthInfo.legacy.batteryPresent;
588 mLastBatteryLevel = mHealthInfo.legacy.batteryLevel;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700589 mLastPlugType = mPlugType;
Yifan Hong932190b2017-10-11 11:00:51 -0700590 mLastBatteryVoltage = mHealthInfo.legacy.batteryVoltage;
591 mLastBatteryTemperature = mHealthInfo.legacy.batteryTemperature;
592 mLastMaxChargingCurrent = mHealthInfo.legacy.maxChargingCurrent;
593 mLastMaxChargingVoltage = mHealthInfo.legacy.maxChargingVoltage;
594 mLastChargeCounter = mHealthInfo.legacy.batteryChargeCounter;
Dianne Hackborn99f7eb452009-09-22 17:27:53 -0700595 mLastBatteryLevelCritical = mBatteryLevelCritical;
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400596 mLastInvalidCharger = mInvalidCharger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 }
598 }
599
Jeff Browna4d82042012-10-02 19:11:19 -0700600 private void sendIntentLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 // Pack up the values and broadcast them to everyone
Jeff Brown605ea692012-10-05 16:33:10 -0700602 final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800603 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
604 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800605
Yifan Hong932190b2017-10-11 11:00:51 -0700606 int icon = getIconLocked(mHealthInfo.legacy.batteryLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800608 intent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
Yifan Hong932190b2017-10-11 11:00:51 -0700609 intent.putExtra(BatteryManager.EXTRA_STATUS, mHealthInfo.legacy.batteryStatus);
610 intent.putExtra(BatteryManager.EXTRA_HEALTH, mHealthInfo.legacy.batteryHealth);
611 intent.putExtra(BatteryManager.EXTRA_PRESENT, mHealthInfo.legacy.batteryPresent);
612 intent.putExtra(BatteryManager.EXTRA_LEVEL, mHealthInfo.legacy.batteryLevel);
Dianne Hackbornedd93162009-09-19 14:03:05 -0700613 intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
614 intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
615 intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
Yifan Hong932190b2017-10-11 11:00:51 -0700616 intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mHealthInfo.legacy.batteryVoltage);
617 intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mHealthInfo.legacy.batteryTemperature);
618 intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mHealthInfo.legacy.batteryTechnology);
Mike Lockwooddeff9c82010-09-04 10:29:17 -0400619 intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
Yifan Hong932190b2017-10-11 11:00:51 -0700620 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mHealthInfo.legacy.maxChargingCurrent);
621 intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE, mHealthInfo.legacy.maxChargingVoltage);
622 intent.putExtra(BatteryManager.EXTRA_CHARGE_COUNTER, mHealthInfo.legacy.batteryChargeCounter);
Jeff Browna4d82042012-10-02 19:11:19 -0700623 if (DEBUG) {
Yifan Hong932190b2017-10-11 11:00:51 -0700624 Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. scale:" + BATTERY_SCALE
625 + ", info:" + mHealthInfo.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
627
Jeff Brown605ea692012-10-05 16:33:10 -0700628 mHandler.post(new Runnable() {
629 @Override
630 public void run() {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800631 ActivityManager.broadcastStickyIntent(intent, UserHandle.USER_ALL);
Jeff Brown605ea692012-10-05 16:33:10 -0700632 }
633 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 }
635
Jeff Browna4d82042012-10-02 19:11:19 -0700636 private void logBatteryStatsLocked() {
Dianne Hackborn8c841092013-06-24 13:46:13 -0700637 IBinder batteryInfoService = ServiceManager.getService(BatteryStats.SERVICE_NAME);
Dan Egnor18e93962010-02-10 19:27:58 -0800638 if (batteryInfoService == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639
Dan Egnor18e93962010-02-10 19:27:58 -0800640 DropBoxManager db = (DropBoxManager) mContext.getSystemService(Context.DROPBOX_SERVICE);
641 if (db == null || !db.isTagEnabled("BATTERY_DISCHARGE_INFO")) return;
642
643 File dumpFile = null;
644 FileOutputStream dumpStream = null;
645 try {
646 // dump the service to a file
Dianne Hackborn8c841092013-06-24 13:46:13 -0700647 dumpFile = new File(DUMPSYS_DATA_PATH + BatteryStats.SERVICE_NAME + ".dump");
Dan Egnor18e93962010-02-10 19:27:58 -0800648 dumpStream = new FileOutputStream(dumpFile);
649 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700650 FileUtils.sync(dumpStream);
Dan Egnor18e93962010-02-10 19:27:58 -0800651
652 // add dump file to drop box
653 db.addFile("BATTERY_DISCHARGE_INFO", dumpFile, DropBoxManager.IS_TEXT);
654 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800655 Slog.e(TAG, "failed to dump battery service", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800656 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800657 Slog.e(TAG, "failed to write dumpsys file", e);
Dan Egnor18e93962010-02-10 19:27:58 -0800658 } finally {
659 // make sure we clean up
660 if (dumpStream != null) {
661 try {
662 dumpStream.close();
663 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800664 Slog.e(TAG, "failed to close dumpsys output stream");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 }
Dan Egnor18e93962010-02-10 19:27:58 -0800666 }
667 if (dumpFile != null && !dumpFile.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800668 Slog.e(TAG, "failed to delete temporary dumpsys file: "
Dan Egnor18e93962010-02-10 19:27:58 -0800669 + dumpFile.getAbsolutePath());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
671 }
672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800673
Jeff Browna4d82042012-10-02 19:11:19 -0700674 private void logOutlierLocked(long duration) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 ContentResolver cr = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -0700676 String dischargeThresholdString = Settings.Global.getString(cr,
677 Settings.Global.BATTERY_DISCHARGE_THRESHOLD);
678 String durationThresholdString = Settings.Global.getString(cr,
679 Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 if (dischargeThresholdString != null && durationThresholdString != null) {
682 try {
683 long durationThreshold = Long.parseLong(durationThresholdString);
684 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800685 if (duration <= durationThreshold &&
Yifan Hong932190b2017-10-11 11:00:51 -0700686 mDischargeStartLevel - mHealthInfo.legacy.batteryLevel >= dischargeThreshold) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 // If the discharge cycle is bad enough we want to know about it.
Jeff Browna4d82042012-10-02 19:11:19 -0700688 logBatteryStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 }
Jeff Browna4d82042012-10-02 19:11:19 -0700690 if (DEBUG) Slog.v(TAG, "duration threshold: " + durationThreshold +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 " discharge threshold: " + dischargeThreshold);
Jeff Browna4d82042012-10-02 19:11:19 -0700692 if (DEBUG) Slog.v(TAG, "duration: " + duration + " discharge: " +
Yifan Hong932190b2017-10-11 11:00:51 -0700693 (mDischargeStartLevel - mHealthInfo.legacy.batteryLevel));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 } catch (NumberFormatException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800695 Slog.e(TAG, "Invalid DischargeThresholds GService string: " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 durationThresholdString + " or " + dischargeThresholdString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
698 }
699 }
700
Jeff Browna4d82042012-10-02 19:11:19 -0700701 private int getIconLocked(int level) {
Yifan Hong932190b2017-10-11 11:00:51 -0700702 if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 return com.android.internal.R.drawable.stat_sys_battery_charge;
Yifan Hong932190b2017-10-11 11:00:51 -0700704 } else if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 return com.android.internal.R.drawable.stat_sys_battery;
Yifan Hong932190b2017-10-11 11:00:51 -0700706 } else if (mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING
707 || mHealthInfo.legacy.batteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
Jeff Browna4d82042012-10-02 19:11:19 -0700708 if (isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)
Yifan Hong932190b2017-10-11 11:00:51 -0700709 && mHealthInfo.legacy.batteryLevel >= 100) {
Joe Onorato794be402010-11-21 19:22:25 -0800710 return com.android.internal.R.drawable.stat_sys_battery_charge;
711 } else {
712 return com.android.internal.R.drawable.stat_sys_battery;
713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 } else {
715 return com.android.internal.R.drawable.stat_sys_battery_unknown;
716 }
717 }
718
Dianne Hackborn2e441072015-10-28 18:00:57 -0700719 class Shell extends ShellCommand {
720 @Override
721 public int onCommand(String cmd) {
722 return onShellCommand(this, cmd);
723 }
724
725 @Override
726 public void onHelp() {
727 PrintWriter pw = getOutPrintWriter();
728 dumpHelp(pw);
729 }
730 }
731
732 static void dumpHelp(PrintWriter pw) {
733 pw.println("Battery service (battery) commands:");
734 pw.println(" help");
735 pw.println(" Print this help text.");
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700736 pw.println(" set [-f] [ac|usb|wireless|status|level|temp|present|invalid] <value>");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700737 pw.println(" Force a battery property value, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800738 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
739 pw.println(" unplug [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700740 pw.println(" Force battery unplugged, freezing battery state.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800741 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
742 pw.println(" reset [-f]");
Dianne Hackborn2e441072015-10-28 18:00:57 -0700743 pw.println(" Unfreeze battery state, returning to current hardware values.");
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800744 pw.println(" -f: force a battery change broadcast be sent, prints new sequence.");
745 }
746
747 static final int OPTION_FORCE_UPDATE = 1<<0;
748
749 int parseOptions(Shell shell) {
750 String opt;
751 int opts = 0;
752 while ((opt = shell.getNextOption()) != null) {
753 if ("-f".equals(opt)) {
754 opts |= OPTION_FORCE_UPDATE;
755 }
756 }
757 return opts;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700758 }
759
760 int onShellCommand(Shell shell, String cmd) {
761 if (cmd == null) {
762 return shell.handleDefaultCommands(cmd);
763 }
764 PrintWriter pw = shell.getOutPrintWriter();
765 switch (cmd) {
766 case "unplug": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800767 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700768 getContext().enforceCallingOrSelfPermission(
769 android.Manifest.permission.DEVICE_POWER, null);
770 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700771 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700772 }
Yifan Hong932190b2017-10-11 11:00:51 -0700773 mHealthInfo.legacy.chargerAcOnline = false;
774 mHealthInfo.legacy.chargerUsbOnline = false;
775 mHealthInfo.legacy.chargerWirelessOnline = false;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700776 long ident = Binder.clearCallingIdentity();
777 try {
778 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800779 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700780 } finally {
781 Binder.restoreCallingIdentity(ident);
782 }
783 } break;
784 case "set": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800785 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700786 getContext().enforceCallingOrSelfPermission(
787 android.Manifest.permission.DEVICE_POWER, null);
788 final String key = shell.getNextArg();
789 if (key == null) {
790 pw.println("No property specified");
791 return -1;
792
793 }
794 final String value = shell.getNextArg();
795 if (value == null) {
796 pw.println("No value specified");
797 return -1;
798
799 }
800 try {
801 if (!mUpdatesStopped) {
Yifan Hong932190b2017-10-11 11:00:51 -0700802 copy(mLastHealthInfo, mHealthInfo);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700803 }
804 boolean update = true;
805 switch (key) {
Christopher Tate630d98b2017-03-07 14:12:26 -0800806 case "present":
Yifan Hong932190b2017-10-11 11:00:51 -0700807 mHealthInfo.legacy.batteryPresent = Integer.parseInt(value) != 0;
Christopher Tate630d98b2017-03-07 14:12:26 -0800808 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700809 case "ac":
Yifan Hong932190b2017-10-11 11:00:51 -0700810 mHealthInfo.legacy.chargerAcOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700811 break;
812 case "usb":
Yifan Hong932190b2017-10-11 11:00:51 -0700813 mHealthInfo.legacy.chargerUsbOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700814 break;
815 case "wireless":
Yifan Hong932190b2017-10-11 11:00:51 -0700816 mHealthInfo.legacy.chargerWirelessOnline = Integer.parseInt(value) != 0;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700817 break;
818 case "status":
Yifan Hong932190b2017-10-11 11:00:51 -0700819 mHealthInfo.legacy.batteryStatus = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700820 break;
821 case "level":
Yifan Hong932190b2017-10-11 11:00:51 -0700822 mHealthInfo.legacy.batteryLevel = Integer.parseInt(value);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700823 break;
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700824 case "temp":
Yifan Hong932190b2017-10-11 11:00:51 -0700825 mHealthInfo.legacy.batteryTemperature = Integer.parseInt(value);
Adam Lesinski29ddfe52017-03-29 19:29:00 -0700826 break;
Dianne Hackborn2e441072015-10-28 18:00:57 -0700827 case "invalid":
828 mInvalidCharger = Integer.parseInt(value);
829 break;
830 default:
831 pw.println("Unknown set option: " + key);
832 update = false;
833 break;
834 }
835 if (update) {
836 long ident = Binder.clearCallingIdentity();
837 try {
838 mUpdatesStopped = true;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800839 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700840 } finally {
841 Binder.restoreCallingIdentity(ident);
842 }
843 }
844 } catch (NumberFormatException ex) {
845 pw.println("Bad value: " + value);
846 return -1;
847 }
848 } break;
849 case "reset": {
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800850 int opts = parseOptions(shell);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700851 getContext().enforceCallingOrSelfPermission(
852 android.Manifest.permission.DEVICE_POWER, null);
853 long ident = Binder.clearCallingIdentity();
854 try {
855 if (mUpdatesStopped) {
856 mUpdatesStopped = false;
Yifan Hong932190b2017-10-11 11:00:51 -0700857 copy(mHealthInfo, mLastHealthInfo);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800858 processValuesFromShellLocked(pw, opts);
Dianne Hackborn2e441072015-10-28 18:00:57 -0700859 }
860 } finally {
861 Binder.restoreCallingIdentity(ident);
862 }
863 } break;
864 default:
865 return shell.handleDefaultCommands(cmd);
866 }
867 return 0;
868 }
869
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800870 private void processValuesFromShellLocked(PrintWriter pw, int opts) {
871 processValuesLocked((opts & OPTION_FORCE_UPDATE) != 0);
872 if ((opts & OPTION_FORCE_UPDATE) != 0) {
873 pw.println(mSequence);
874 }
875 }
876
Dianne Hackborn2e441072015-10-28 18:00:57 -0700877 private void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna4d82042012-10-02 19:11:19 -0700878 synchronized (mLock) {
879 if (args == null || args.length == 0 || "-a".equals(args[0])) {
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700880 pw.println("Current Battery Service state:");
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700881 if (mUpdatesStopped) {
882 pw.println(" (UPDATES STOPPED -- use 'reset' to restart)");
883 }
Yifan Hong932190b2017-10-11 11:00:51 -0700884 pw.println(" AC powered: " + mHealthInfo.legacy.chargerAcOnline);
885 pw.println(" USB powered: " + mHealthInfo.legacy.chargerUsbOnline);
886 pw.println(" Wireless powered: " + mHealthInfo.legacy.chargerWirelessOnline);
887 pw.println(" Max charging current: " + mHealthInfo.legacy.maxChargingCurrent);
888 pw.println(" Max charging voltage: " + mHealthInfo.legacy.maxChargingVoltage);
889 pw.println(" Charge counter: " + mHealthInfo.legacy.batteryChargeCounter);
890 pw.println(" status: " + mHealthInfo.legacy.batteryStatus);
891 pw.println(" health: " + mHealthInfo.legacy.batteryHealth);
892 pw.println(" present: " + mHealthInfo.legacy.batteryPresent);
893 pw.println(" level: " + mHealthInfo.legacy.batteryLevel);
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700894 pw.println(" scale: " + BATTERY_SCALE);
Yifan Hong932190b2017-10-11 11:00:51 -0700895 pw.println(" voltage: " + mHealthInfo.legacy.batteryVoltage);
896 pw.println(" temperature: " + mHealthInfo.legacy.batteryTemperature);
897 pw.println(" technology: " + mHealthInfo.legacy.batteryTechnology);
Dianne Hackbornc428aae2012-10-03 16:38:22 -0700898 } else {
Dianne Hackborn2e441072015-10-28 18:00:57 -0700899 Shell shell = new Shell();
Dianne Hackborn354736e2016-08-22 17:00:05 -0700900 shell.exec(mBinderService, null, fd, null, args, null, new ResultReceiver(null));
Joe Onorato4ca7f1e2010-10-27 15:32:23 -0700901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 }
Joe Onoratode1b3592010-10-25 20:36:47 -0700904
Netta Pe2a3cd82017-01-26 18:03:51 -0800905 private void dumpProto(FileDescriptor fd) {
906 final ProtoOutputStream proto = new ProtoOutputStream(fd);
907
908 synchronized (mLock) {
909 proto.write(BatteryServiceDumpProto.ARE_UPDATES_STOPPED, mUpdatesStopped);
910 int batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_NONE;
Yifan Hong932190b2017-10-11 11:00:51 -0700911 if (mHealthInfo.legacy.chargerAcOnline) {
Netta Pe2a3cd82017-01-26 18:03:51 -0800912 batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_AC;
Yifan Hong932190b2017-10-11 11:00:51 -0700913 } else if (mHealthInfo.legacy.chargerUsbOnline) {
Netta Pe2a3cd82017-01-26 18:03:51 -0800914 batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_USB;
Yifan Hong932190b2017-10-11 11:00:51 -0700915 } else if (mHealthInfo.legacy.chargerWirelessOnline) {
Netta Pe2a3cd82017-01-26 18:03:51 -0800916 batteryPluggedValue = BatteryServiceDumpProto.BATTERY_PLUGGED_WIRELESS;
917 }
918 proto.write(BatteryServiceDumpProto.PLUGGED, batteryPluggedValue);
Yifan Hong932190b2017-10-11 11:00:51 -0700919 proto.write(BatteryServiceDumpProto.MAX_CHARGING_CURRENT, mHealthInfo.legacy.maxChargingCurrent);
920 proto.write(BatteryServiceDumpProto.MAX_CHARGING_VOLTAGE, mHealthInfo.legacy.maxChargingVoltage);
921 proto.write(BatteryServiceDumpProto.CHARGE_COUNTER, mHealthInfo.legacy.batteryChargeCounter);
922 proto.write(BatteryServiceDumpProto.STATUS, mHealthInfo.legacy.batteryStatus);
923 proto.write(BatteryServiceDumpProto.HEALTH, mHealthInfo.legacy.batteryHealth);
924 proto.write(BatteryServiceDumpProto.IS_PRESENT, mHealthInfo.legacy.batteryPresent);
925 proto.write(BatteryServiceDumpProto.LEVEL, mHealthInfo.legacy.batteryLevel);
Netta Pe2a3cd82017-01-26 18:03:51 -0800926 proto.write(BatteryServiceDumpProto.SCALE, BATTERY_SCALE);
Yifan Hong932190b2017-10-11 11:00:51 -0700927 proto.write(BatteryServiceDumpProto.VOLTAGE, mHealthInfo.legacy.batteryVoltage);
928 proto.write(BatteryServiceDumpProto.TEMPERATURE, mHealthInfo.legacy.batteryTemperature);
929 proto.write(BatteryServiceDumpProto.TECHNOLOGY, mHealthInfo.legacy.batteryTechnology);
Netta Pe2a3cd82017-01-26 18:03:51 -0800930 }
931 proto.flush();
932 }
933
Jeff Browna4d82042012-10-02 19:11:19 -0700934 private final class Led {
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800935 private final Light mBatteryLight;
Joe Onoratode1b3592010-10-25 20:36:47 -0700936
Jeff Browna4d82042012-10-02 19:11:19 -0700937 private final int mBatteryLowARGB;
938 private final int mBatteryMediumARGB;
939 private final int mBatteryFullARGB;
940 private final int mBatteryLedOn;
941 private final int mBatteryLedOff;
942
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800943 public Led(Context context, LightsManager lights) {
944 mBatteryLight = lights.getLight(LightsManager.LIGHT_ID_BATTERY);
Joe Onoratode1b3592010-10-25 20:36:47 -0700945
Jeff Browna4d82042012-10-02 19:11:19 -0700946 mBatteryLowARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700947 com.android.internal.R.integer.config_notificationsBatteryLowARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700948 mBatteryMediumARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700949 com.android.internal.R.integer.config_notificationsBatteryMediumARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700950 mBatteryFullARGB = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700951 com.android.internal.R.integer.config_notificationsBatteryFullARGB);
Jeff Browna4d82042012-10-02 19:11:19 -0700952 mBatteryLedOn = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700953 com.android.internal.R.integer.config_notificationsBatteryLedOn);
Jeff Browna4d82042012-10-02 19:11:19 -0700954 mBatteryLedOff = context.getResources().getInteger(
Joe Onoratode1b3592010-10-25 20:36:47 -0700955 com.android.internal.R.integer.config_notificationsBatteryLedOff);
956 }
957
958 /**
959 * Synchronize on BatteryService.
960 */
Jeff Browna4d82042012-10-02 19:11:19 -0700961 public void updateLightsLocked() {
Yifan Hong932190b2017-10-11 11:00:51 -0700962 final int level = mHealthInfo.legacy.batteryLevel;
963 final int status = mHealthInfo.legacy.batteryStatus;
Joe Onoratode1b3592010-10-25 20:36:47 -0700964 if (level < mLowBatteryWarningLevel) {
965 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
966 // Solid red when battery is charging
967 mBatteryLight.setColor(mBatteryLowARGB);
968 } else {
969 // Flash red when battery is low and not charging
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800970 mBatteryLight.setFlashing(mBatteryLowARGB, Light.LIGHT_FLASH_TIMED,
Joe Onoratode1b3592010-10-25 20:36:47 -0700971 mBatteryLedOn, mBatteryLedOff);
972 }
973 } else if (status == BatteryManager.BATTERY_STATUS_CHARGING
974 || status == BatteryManager.BATTERY_STATUS_FULL) {
975 if (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90) {
976 // Solid green when full or charging and nearly full
977 mBatteryLight.setColor(mBatteryFullARGB);
978 } else {
979 // Solid orange when charging and halfway full
980 mBatteryLight.setColor(mBatteryMediumARGB);
981 }
982 } else {
983 // No lights if not charging and not low
984 mBatteryLight.turnOff();
985 }
986 }
987 }
Todd Poynor26faecc2013-05-22 18:54:48 -0700988
Yifan Hong89d55c12017-10-11 11:29:01 -0700989 private final class HealthHalCallback extends IHealthInfoCallback.Stub
990 implements HealthServiceWrapper.Callback {
991 @Override public void healthInfoChanged(HealthInfo props) {
992 BatteryService.this.update(props);
993 }
994 // on new service registered
995 @Override public void onRegistration(IHealth oldService, IHealth newService,
996 String instance) {
997 if (newService == null) return;
998
Adam Lesinskief2ea1f2013-12-05 16:48:06 -0800999 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001000 if (oldService != null) {
1001 int r = oldService.unregisterCallback(this);
1002 if (r != Result.SUCCESS) {
1003 Slog.w(TAG, "health: cannot unregister previous callback: " +
1004 Result.toString(r));
1005 }
1006 }
1007 } catch (RemoteException ex) {
1008 Slog.w(TAG, "health: cannot unregister previous callback (transaction error): "
1009 + ex.getMessage());
Adam Lesinskief2ea1f2013-12-05 16:48:06 -08001010 }
Yifan Hong89d55c12017-10-11 11:29:01 -07001011
1012 try {
1013 int r = newService.registerCallback(this);
1014 if (r != Result.SUCCESS) {
1015 Slog.w(TAG, "health: cannot register callback: " + Result.toString(r));
1016 return;
1017 }
1018 // registerCallback does NOT guarantee that update is called
1019 // immediately, so request a manual update here.
1020 newService.update();
1021 } catch (RemoteException ex) {
1022 Slog.e(TAG, "health: cannot register callback (transaction error): "
1023 + ex.getMessage());
1024 }
1025 }
Todd Poynor26faecc2013-05-22 18:54:48 -07001026 }
Jeff Brown21392762014-06-13 19:00:36 -07001027
1028 private final class BinderService extends Binder {
Dianne Hackborn2e441072015-10-28 18:00:57 -07001029 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001030 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown21392762014-06-13 19:00:36 -07001031
Netta Pe2a3cd82017-01-26 18:03:51 -08001032 if (args.length > 0 && "--proto".equals(args[0])) {
1033 dumpProto(fd);
1034 } else {
1035 dumpInternal(fd, pw, args);
1036 }
Dianne Hackborn2e441072015-10-28 18:00:57 -07001037 }
1038
1039 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001040 FileDescriptor err, String[] args, ShellCallback callback,
1041 ResultReceiver resultReceiver) {
1042 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Jeff Brown21392762014-06-13 19:00:36 -07001043 }
1044 }
1045
1046 private final class LocalService extends BatteryManagerInternal {
1047 @Override
1048 public boolean isPowered(int plugTypeSet) {
1049 synchronized (mLock) {
1050 return isPoweredLocked(plugTypeSet);
1051 }
1052 }
1053
1054 @Override
1055 public int getPlugType() {
1056 synchronized (mLock) {
1057 return mPlugType;
1058 }
1059 }
1060
1061 @Override
1062 public int getBatteryLevel() {
1063 synchronized (mLock) {
Yifan Hong932190b2017-10-11 11:00:51 -07001064 return mHealthInfo.legacy.batteryLevel;
Jeff Brown21392762014-06-13 19:00:36 -07001065 }
1066 }
1067
1068 @Override
1069 public boolean getBatteryLevelLow() {
1070 synchronized (mLock) {
1071 return mBatteryLevelLow;
1072 }
1073 }
1074
1075 @Override
1076 public int getInvalidCharger() {
1077 synchronized (mLock) {
1078 return mInvalidCharger;
1079 }
1080 }
1081 }
Yifan Hong98852792017-10-12 11:35:14 -07001082
1083 /**
1084 * HealthServiceWrapper wraps the internal IHealth service and refreshes the service when
1085 * necessary.
1086 *
1087 * On new registration of IHealth service, {@link #onRegistration onRegistration} is called and
1088 * the internal service is refreshed.
1089 * On death of an existing IHealth service, the internal service is NOT cleared to avoid
1090 * race condition between death notification and new service notification. Hence,
1091 * a caller must check for transaction errors when calling into the service.
1092 *
1093 * @hide Should only be used internally.
1094 */
1095 @VisibleForTesting
1096 static final class HealthServiceWrapper {
1097 private static final String TAG = "HealthServiceWrapper";
1098 public static final String INSTANCE_HEALTHD = "backup";
1099 public static final String INSTANCE_VENDOR = "default";
1100 // All interesting instances, sorted by priority high -> low.
1101 private static final List<String> sAllInstances =
1102 Arrays.asList(INSTANCE_VENDOR, INSTANCE_HEALTHD);
1103
1104 private final IServiceNotification mNotification = new Notification();
1105 private Callback mCallback;
1106 private IHealthSupplier mHealthSupplier;
1107
Yifan Hong89d55c12017-10-11 11:29:01 -07001108 private final Object mLastServiceSetLock = new Object();
1109 // Last IHealth service received.
1110 // set must be also be guarded with mLastServiceSetLock to ensure ordering.
1111 private final AtomicReference<IHealth> mLastService = new AtomicReference<>();
1112
Yifan Hong98852792017-10-12 11:35:14 -07001113 /**
1114 * init should be called after constructor. For testing purposes, init is not called by
1115 * constructor.
1116 */
1117 HealthServiceWrapper() {
1118 }
1119
1120 /**
1121 * Start monitoring registration of new IHealth services. Only instances that are in
1122 * {@code sAllInstances} and in device / framework manifest are used. This function should
1123 * only be called once.
1124 * @throws RemoteException transaction error when talking to IServiceManager
1125 * @throws NoSuchElementException if one of the following cases:
1126 * - No service manager;
1127 * - none of {@code sAllInstances} are in manifests (i.e. not
1128 * available on this device), or none of these instances are available to current
1129 * process.
1130 * @throws NullPointerException when callback is null or supplier is null
1131 */
1132 void init(Callback callback,
1133 IServiceManagerSupplier managerSupplier,
1134 IHealthSupplier healthSupplier)
1135 throws RemoteException, NoSuchElementException, NullPointerException {
1136 if (callback == null || managerSupplier == null || healthSupplier == null)
1137 throw new NullPointerException();
1138
1139 mCallback = callback;
1140 mHealthSupplier = healthSupplier;
1141
1142 IServiceManager manager = managerSupplier.get();
1143 for (String name : sAllInstances) {
1144 if (manager.getTransport(IHealth.kInterfaceName, name) ==
1145 IServiceManager.Transport.EMPTY) {
1146 continue;
1147 }
1148
1149 manager.registerForNotifications(IHealth.kInterfaceName, name, mNotification);
1150 Slog.i(TAG, "health: HealthServiceWrapper listening to instance " + name);
1151 return;
1152 }
1153
1154 throw new NoSuchElementException(String.format(
1155 "No IHealth service instance among %s is available. Perhaps no permission?",
1156 sAllInstances.toString()));
1157 }
1158
1159 interface Callback {
1160 /**
1161 * This function is invoked asynchronously when a new and related IServiceNotification
1162 * is received.
1163 * @param service the recently retrieved service from IServiceManager.
1164 * Can be a dead service before service notification of a new service is delivered.
1165 * Implementation must handle cases for {@link RemoteException}s when calling
1166 * into service.
1167 * @param instance instance name.
1168 */
Yifan Hong89d55c12017-10-11 11:29:01 -07001169 void onRegistration(IHealth oldService, IHealth newService, String instance);
Yifan Hong98852792017-10-12 11:35:14 -07001170 }
1171
1172 /**
1173 * Supplier of services.
1174 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1175 */
1176 interface IServiceManagerSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001177 default IServiceManager get() throws NoSuchElementException, RemoteException {
1178 return IServiceManager.getService();
1179 }
Yifan Hong98852792017-10-12 11:35:14 -07001180 }
1181 /**
1182 * Supplier of services.
1183 * Must not return null; throw {@link NoSuchElementException} if a service is not available.
1184 */
1185 interface IHealthSupplier {
Yifan Hong89d55c12017-10-11 11:29:01 -07001186 default IHealth get(String name) throws NoSuchElementException, RemoteException {
1187 return IHealth.getService(name);
1188 }
Yifan Hong98852792017-10-12 11:35:14 -07001189 }
1190
1191 private class Notification extends IServiceNotification.Stub {
1192 @Override
1193 public final void onRegistration(String interfaceName, String instanceName,
1194 boolean preexisting) {
1195 if (!IHealth.kInterfaceName.equals(interfaceName)) return;
1196 if (!sAllInstances.contains(instanceName)) return;
1197 try {
Yifan Hong89d55c12017-10-11 11:29:01 -07001198 // ensures the order of multiple onRegistration on different threads.
1199 synchronized (mLastServiceSetLock) {
1200 IHealth newService = mHealthSupplier.get(instanceName);
1201 IHealth oldService = mLastService.getAndSet(newService);
1202 Slog.i(TAG, "health: new instance registered " + instanceName);
1203 mCallback.onRegistration(oldService, newService, instanceName);
1204 }
Yifan Hong98852792017-10-12 11:35:14 -07001205 } catch (NoSuchElementException | RemoteException ex) {
1206 Slog.e(TAG, "health: Cannot get instance '" + instanceName + "': " +
1207 ex.getMessage() + ". Perhaps no permission?");
1208 }
1209 }
1210 }
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212}