blob: af3c96f736429e03a5d2de61c6a9ccb5564da870 [file] [log] [blame]
Anthony Chenda62fdcd52016-04-06 16:15:14 -07001/*
2 * Copyright (C) 2016 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.systemui.statusbar.policy;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.IntentFilter;
23import android.os.BatteryManager;
Jason Monk98d7c7a2016-04-12 13:08:31 -040024import android.os.Bundle;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070025import android.os.Handler;
26import android.os.PowerManager;
Lucas Dupin92a62e52018-01-30 17:22:20 -080027import android.os.PowerSaveState;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070028import android.util.Log;
Lucas Dupin92a62e52018-01-30 17:22:20 -080029
Evan Lairda5a73c52019-01-11 13:36:32 -050030import androidx.annotation.Nullable;
31
Lucas Dupin92a62e52018-01-30 17:22:20 -080032import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki16a0dd22018-03-20 10:40:37 -070033import com.android.settingslib.fuelgauge.BatterySaverUtils;
Evan Laird4bf21df2018-10-22 14:24:32 -040034import com.android.settingslib.utils.PowerUtil;
Evan Lairda5a73c52019-01-11 13:36:32 -050035import com.android.systemui.Dependency;
Evan Laird4bf21df2018-10-22 14:24:32 -040036import com.android.systemui.power.EnhancedEstimates;
37import com.android.systemui.power.Estimate;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070038
39import java.io.FileDescriptor;
40import java.io.PrintWriter;
Evan Laird4bf21df2018-10-22 14:24:32 -040041import java.text.NumberFormat;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070042import java.util.ArrayList;
43
Jason Monk196d6392018-12-20 13:25:34 -050044import javax.inject.Inject;
45import javax.inject.Singleton;
46
Anthony Chenda62fdcd52016-04-06 16:15:14 -070047/**
48 * Default implementation of a {@link BatteryController}. This controller monitors for battery
49 * level change events that are broadcasted by the system.
50 */
Jason Monk196d6392018-12-20 13:25:34 -050051@Singleton
Anthony Chenda62fdcd52016-04-06 16:15:14 -070052public class BatteryControllerImpl extends BroadcastReceiver implements BatteryController {
53 private static final String TAG = "BatteryController";
54
55 public static final String ACTION_LEVEL_TEST = "com.android.systemui.BATTERY_LEVEL_TEST";
56
57 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Evan Laird4bf21df2018-10-22 14:24:32 -040058 private static final int UPDATE_GRANULARITY_MSEC = 1000 * 60;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070059
Jason Monkde48d5d2018-12-21 14:06:00 -050060 private final EnhancedEstimates mEstimates;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070061 private final ArrayList<BatteryController.BatteryStateChangeCallback> mChangeCallbacks = new ArrayList<>();
Evan Lairda5a73c52019-01-11 13:36:32 -050062 private final ArrayList<EstimateFetchCompletion> mFetchCallbacks = new ArrayList<>();
Anthony Chenda62fdcd52016-04-06 16:15:14 -070063 private final PowerManager mPowerManager;
64 private final Handler mHandler;
Jason Monk98d7c7a2016-04-12 13:08:31 -040065 private final Context mContext;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070066
67 protected int mLevel;
68 protected boolean mPluggedIn;
69 protected boolean mCharging;
70 protected boolean mCharged;
71 protected boolean mPowerSave;
Lucas Dupin92a62e52018-01-30 17:22:20 -080072 protected boolean mAodPowerSave;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070073 private boolean mTestmode = false;
Jason Monk159dfb72016-09-30 09:41:03 -040074 private boolean mHasReceivedBattery = false;
Evan Laird4bf21df2018-10-22 14:24:32 -040075 private Estimate mEstimate;
76 private long mLastEstimateTimestamp = -1;
Evan Lairda5a73c52019-01-11 13:36:32 -050077 private boolean mFetchingEstimate = false;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070078
Jason Monk196d6392018-12-20 13:25:34 -050079 @Inject
Jason Monkde48d5d2018-12-21 14:06:00 -050080 public BatteryControllerImpl(Context context, EnhancedEstimates enhancedEstimates) {
81 this(context, enhancedEstimates, context.getSystemService(PowerManager.class));
Lucas Dupin92a62e52018-01-30 17:22:20 -080082 }
83
84 @VisibleForTesting
Jason Monkde48d5d2018-12-21 14:06:00 -050085 BatteryControllerImpl(Context context, EnhancedEstimates enhancedEstimates,
86 PowerManager powerManager) {
Jason Monk98d7c7a2016-04-12 13:08:31 -040087 mContext = context;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070088 mHandler = new Handler();
Lucas Dupin92a62e52018-01-30 17:22:20 -080089 mPowerManager = powerManager;
Jason Monkde48d5d2018-12-21 14:06:00 -050090 mEstimates = enhancedEstimates;
Anthony Chenda62fdcd52016-04-06 16:15:14 -070091
Jason Monk98d7c7a2016-04-12 13:08:31 -040092 registerReceiver();
93 updatePowerSave();
Evan Laird4bf21df2018-10-22 14:24:32 -040094 updateEstimate();
Jason Monk98d7c7a2016-04-12 13:08:31 -040095 }
96
97 private void registerReceiver() {
Anthony Chenda62fdcd52016-04-06 16:15:14 -070098 IntentFilter filter = new IntentFilter();
99 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
100 filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
101 filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING);
102 filter.addAction(ACTION_LEVEL_TEST);
Jason Monk98d7c7a2016-04-12 13:08:31 -0400103 mContext.registerReceiver(this, filter);
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700104 }
105
106 @Override
107 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
108 pw.println("BatteryController state:");
109 pw.print(" mLevel="); pw.println(mLevel);
110 pw.print(" mPluggedIn="); pw.println(mPluggedIn);
111 pw.print(" mCharging="); pw.println(mCharging);
112 pw.print(" mCharged="); pw.println(mCharged);
113 pw.print(" mPowerSave="); pw.println(mPowerSave);
114 }
115
116 @Override
117 public void setPowerSaveMode(boolean powerSave) {
Makoto Onuki16a0dd22018-03-20 10:40:37 -0700118 BatterySaverUtils.setPowerSaveMode(mContext, powerSave, /*needFirstTimeWarning*/ true);
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700119 }
120
121 @Override
Jason Monk88529052016-11-04 13:29:58 -0400122 public void addCallback(BatteryController.BatteryStateChangeCallback cb) {
Jason Monk324a28f2016-07-12 13:34:12 -0400123 synchronized (mChangeCallbacks) {
124 mChangeCallbacks.add(cb);
125 }
Jason Monk159dfb72016-09-30 09:41:03 -0400126 if (!mHasReceivedBattery) return;
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700127 cb.onBatteryLevelChanged(mLevel, mPluggedIn, mCharging);
128 cb.onPowerSaveChanged(mPowerSave);
129 }
130
131 @Override
Jason Monk88529052016-11-04 13:29:58 -0400132 public void removeCallback(BatteryController.BatteryStateChangeCallback cb) {
Jason Monk324a28f2016-07-12 13:34:12 -0400133 synchronized (mChangeCallbacks) {
134 mChangeCallbacks.remove(cb);
135 }
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700136 }
137
138 @Override
139 public void onReceive(final Context context, Intent intent) {
140 final String action = intent.getAction();
141 if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
142 if (mTestmode && !intent.getBooleanExtra("testmode", false)) return;
Jason Monk159dfb72016-09-30 09:41:03 -0400143 mHasReceivedBattery = true;
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700144 mLevel = (int)(100f
145 * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
146 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100));
147 mPluggedIn = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
148
149 final int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
150 BatteryManager.BATTERY_STATUS_UNKNOWN);
151 mCharged = status == BatteryManager.BATTERY_STATUS_FULL;
152 mCharging = mCharged || status == BatteryManager.BATTERY_STATUS_CHARGING;
153
154 fireBatteryLevelChanged();
155 } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)) {
156 updatePowerSave();
157 } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING)) {
158 setPowerSave(intent.getBooleanExtra(PowerManager.EXTRA_POWER_SAVE_MODE, false));
159 } else if (action.equals(ACTION_LEVEL_TEST)) {
160 mTestmode = true;
161 mHandler.post(new Runnable() {
162 int curLevel = 0;
163 int incr = 1;
164 int saveLevel = mLevel;
165 boolean savePlugged = mPluggedIn;
166 Intent dummy = new Intent(Intent.ACTION_BATTERY_CHANGED);
167 @Override
168 public void run() {
169 if (curLevel < 0) {
170 mTestmode = false;
171 dummy.putExtra("level", saveLevel);
172 dummy.putExtra("plugged", savePlugged);
173 dummy.putExtra("testmode", false);
174 } else {
175 dummy.putExtra("level", curLevel);
176 dummy.putExtra("plugged", incr > 0 ? BatteryManager.BATTERY_PLUGGED_AC
177 : 0);
178 dummy.putExtra("testmode", true);
179 }
180 context.sendBroadcast(dummy);
181
182 if (!mTestmode) return;
183
184 curLevel += incr;
185 if (curLevel == 100) {
186 incr *= -1;
187 }
188 mHandler.postDelayed(this, 200);
189 }
190 });
191 }
192 }
193
194 @Override
195 public boolean isPowerSave() {
196 return mPowerSave;
197 }
198
Lucas Dupin92a62e52018-01-30 17:22:20 -0800199 @Override
200 public boolean isAodPowerSave() {
201 return mAodPowerSave;
202 }
203
Evan Laird4bf21df2018-10-22 14:24:32 -0400204 @Override
Evan Lairda5a73c52019-01-11 13:36:32 -0500205 public void getEstimatedTimeRemainingString(EstimateFetchCompletion completion) {
206 if (mEstimate != null
207 && mLastEstimateTimestamp > System.currentTimeMillis() - UPDATE_GRANULARITY_MSEC) {
208 String percentage = generateTimeRemainingString();
209 completion.onBatteryRemainingEstimateRetrieved(percentage);
210 return;
Evan Laird4bf21df2018-10-22 14:24:32 -0400211 }
Evan Lairda5a73c52019-01-11 13:36:32 -0500212
213 // Need to fetch or refresh the estimate, but it may involve binder calls so offload the
214 // work
215 synchronized (mFetchCallbacks) {
216 mFetchCallbacks.add(completion);
217 }
218 updateEstimateInBackground();
219 }
220
221 @Nullable
222 private String generateTimeRemainingString() {
Evan Laird4bf21df2018-10-22 14:24:32 -0400223 if (mEstimate == null) {
224 return null;
225 }
Evan Lairda5a73c52019-01-11 13:36:32 -0500226
227 String percentage = NumberFormat.getPercentInstance().format((double) mLevel / 100.0);
Evan Laird4bf21df2018-10-22 14:24:32 -0400228 return PowerUtil.getBatteryRemainingShortStringFormatted(
229 mContext, mEstimate.estimateMillis);
230 }
231
Evan Lairda5a73c52019-01-11 13:36:32 -0500232 private void updateEstimateInBackground() {
233 if (mFetchingEstimate) {
234 // Already dispatched a fetch. It will notify all listeners when finished
235 return;
236 }
237
238 mFetchingEstimate = true;
239 Dependency.get(Dependency.BG_HANDLER).post(() -> {
240 mEstimate = mEstimates.getEstimate();
241 mLastEstimateTimestamp = System.currentTimeMillis();
242 mFetchingEstimate = false;
243
244 Dependency.get(Dependency.MAIN_HANDLER).post(this::notifyEstimateFetchCallbacks);
245 });
246 }
247
248 private void notifyEstimateFetchCallbacks() {
249 String estimate = generateTimeRemainingString();
250
251 synchronized (mFetchCallbacks) {
252 for (EstimateFetchCompletion completion : mFetchCallbacks) {
253 completion.onBatteryRemainingEstimateRetrieved(estimate);
254 }
255
256 mFetchCallbacks.clear();
257 }
258 }
259
Evan Laird4bf21df2018-10-22 14:24:32 -0400260 private void updateEstimate() {
261 mEstimate = mEstimates.getEstimate();
262 mLastEstimateTimestamp = System.currentTimeMillis();
263 }
264
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700265 private void updatePowerSave() {
266 setPowerSave(mPowerManager.isPowerSaveMode());
267 }
268
269 private void setPowerSave(boolean powerSave) {
270 if (powerSave == mPowerSave) return;
271 mPowerSave = powerSave;
Lucas Dupin92a62e52018-01-30 17:22:20 -0800272
273 // AOD power saving setting might be different from PowerManager power saving mode.
274 PowerSaveState state = mPowerManager.getPowerSaveState(PowerManager.ServiceType.AOD);
275 mAodPowerSave = state.batterySaverEnabled;
276
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700277 if (DEBUG) Log.d(TAG, "Power save is " + (mPowerSave ? "on" : "off"));
278 firePowerSaveChanged();
279 }
280
281 protected void fireBatteryLevelChanged() {
Jason Monk324a28f2016-07-12 13:34:12 -0400282 synchronized (mChangeCallbacks) {
283 final int N = mChangeCallbacks.size();
284 for (int i = 0; i < N; i++) {
285 mChangeCallbacks.get(i).onBatteryLevelChanged(mLevel, mPluggedIn, mCharging);
286 }
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700287 }
288 }
289
290 private void firePowerSaveChanged() {
Jason Monk324a28f2016-07-12 13:34:12 -0400291 synchronized (mChangeCallbacks) {
292 final int N = mChangeCallbacks.size();
293 for (int i = 0; i < N; i++) {
294 mChangeCallbacks.get(i).onPowerSaveChanged(mPowerSave);
295 }
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700296 }
297 }
Jason Monk98d7c7a2016-04-12 13:08:31 -0400298
299 private boolean mDemoMode;
300
301 @Override
302 public void dispatchDemoCommand(String command, Bundle args) {
303 if (!mDemoMode && command.equals(COMMAND_ENTER)) {
304 mDemoMode = true;
305 mContext.unregisterReceiver(this);
306 } else if (mDemoMode && command.equals(COMMAND_EXIT)) {
307 mDemoMode = false;
308 registerReceiver();
309 updatePowerSave();
310 } else if (mDemoMode && command.equals(COMMAND_BATTERY)) {
Evan Laird706d9682017-05-30 15:03:29 -0400311 String level = args.getString("level");
312 String plugged = args.getString("plugged");
313 String powerSave = args.getString("powersave");
314 if (level != null) {
315 mLevel = Math.min(Math.max(Integer.parseInt(level), 0), 100);
316 }
317 if (plugged != null) {
318 mPluggedIn = Boolean.parseBoolean(plugged);
319 }
320 if (powerSave != null) {
321 mPowerSave = powerSave.equals("true");
322 firePowerSaveChanged();
323 }
Jason Monk98d7c7a2016-04-12 13:08:31 -0400324 fireBatteryLevelChanged();
325 }
326 }
Anthony Chenda62fdcd52016-04-06 16:15:14 -0700327}