blob: 2ab46e65e77fa02b479a123dcd663341a9a29574 [file] [log] [blame]
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001/*
2 * Copyright (C) 2015 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
Amith Yamasaniaf575b92015-05-29 15:35:26 -070019import android.Manifest;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080020import android.app.ActivityManager;
Dianne Hackborn85e35642017-01-12 15:10:57 -080021import android.app.ActivityManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070022import android.app.AlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070023import android.content.BroadcastReceiver;
Adam Lesinski31c05d12015-06-09 17:34:04 -070024import android.content.ContentResolver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070030import android.content.pm.PackageManager.NameNotFoundException;
Adam Lesinski31c05d12015-06-09 17:34:04 -070031import android.database.ContentObserver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070032import android.hardware.Sensor;
Nick Vaccaro20feaea2015-09-17 17:22:44 -070033import android.hardware.SensorEvent;
34import android.hardware.SensorEventListener;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070035import android.hardware.SensorManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070036import android.hardware.TriggerEvent;
37import android.hardware.TriggerEventListener;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070038import android.location.Location;
39import android.location.LocationListener;
40import android.location.LocationManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070041import android.location.LocationRequest;
Dianne Hackborn88c41352016-04-07 15:18:58 -070042import android.net.ConnectivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070043import android.net.INetworkPolicyManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070044import android.net.NetworkInfo;
Adam Lesinski31c05d12015-06-09 17:34:04 -070045import android.net.Uri;
Robin Lee204cb222018-12-07 15:17:44 +010046import android.os.BatteryManager;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070047import android.os.BatteryStats;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070048import android.os.Binder;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070049import android.os.Bundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070050import android.os.Environment;
51import android.os.FileUtils;
52import android.os.Handler;
53import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080054import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070055import android.os.Looper;
56import android.os.Message;
57import android.os.PowerManager;
Kweku Adamsb396ccf2018-09-17 16:37:15 -070058import android.os.PowerManager.ServiceType;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070059import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070060import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080061import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070062import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070063import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070066import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070067import android.os.SystemClock;
68import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070069import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070070import android.util.ArrayMap;
71import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070072import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070073import android.util.MutableLong;
74import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070075import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070076import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070077import android.util.SparseBooleanArray;
78import android.util.TimeUtils;
79import android.util.Xml;
Amith Yamasani520d8f22015-05-08 16:36:21 -070080
Sudheer Shanka326b3112017-11-27 14:40:57 -080081import com.android.internal.annotations.GuardedBy;
Kweku Adams00e3a372018-09-28 16:57:09 -070082import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070083import com.android.internal.app.IBatteryStats;
84import com.android.internal.os.AtomicFile;
85import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060086import com.android.internal.util.DumpUtils;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070087import com.android.internal.util.FastXmlSerializer;
88import com.android.internal.util.XmlUtils;
89import com.android.server.am.BatteryStatsService;
Robin Lee876b88542018-11-13 17:22:24 +010090import com.android.server.deviceidle.ConstraintController;
91import com.android.server.deviceidle.DeviceIdleConstraintTracker;
92import com.android.server.deviceidle.IDeviceIdleConstraint;
93import com.android.server.deviceidle.TvConstraintController;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -070094import com.android.server.net.NetworkPolicyManagerInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070095import com.android.server.wm.ActivityTaskManagerInternal;
Amith Yamasani520d8f22015-05-08 16:36:21 -070096
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070097import org.xmlpull.v1.XmlPullParser;
98import org.xmlpull.v1.XmlPullParserException;
99import org.xmlpull.v1.XmlSerializer;
100
101import java.io.ByteArrayOutputStream;
102import java.io.File;
103import java.io.FileDescriptor;
104import java.io.FileInputStream;
105import java.io.FileNotFoundException;
106import java.io.FileOutputStream;
107import java.io.IOException;
108import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100109import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700110import java.util.Arrays;
Robin Lee876b88542018-11-13 17:22:24 +0100111import java.util.stream.Collectors;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700112
113/**
114 * Keeps track of device idleness and drives low power mode based on that.
Kweku Adams00e3a372018-09-28 16:57:09 -0700115 *
116 * Test: atest com.android.server.DeviceIdleControllerTest
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700117 *
Kweku Adams3ba574f2019-03-19 12:45:55 -0700118 * Current idling state machine (as of Android Q). This can be visualized using Graphviz:
119 <pre>
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700120
121 digraph {
122 subgraph deep {
123 label="deep";
124
125 STATE_ACTIVE [label="STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon"]
126 STATE_INACTIVE [label="STATE_INACTIVE\nScreen off AND Not charging"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700127 STATE_QUICK_DOZE_DELAY [
128 label="STATE_QUICK_DOZE_DELAY\n"
129 + "Screen off AND Not charging\n"
130 + "Location, motion detection, and significant motion monitoring turned off"
131 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700132 STATE_IDLE_PENDING [
133 label="STATE_IDLE_PENDING\nSignificant motion monitoring turned on"
134 ]
135 STATE_SENSING [label="STATE_SENSING\nMonitoring for ANY motion"]
136 STATE_LOCATING [
137 label="STATE_LOCATING\nRequesting location, motion monitoring still on"
138 ]
139 STATE_IDLE [
140 label="STATE_IDLE\nLocation and motion detection turned off\n"
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700141 + "Significant motion monitoring state unchanged"
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700142 ]
143 STATE_IDLE_MAINTENANCE [label="STATE_IDLE_MAINTENANCE\n"]
144
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700145 STATE_ACTIVE -> STATE_INACTIVE [
146 label="becomeInactiveIfAppropriateLocked() AND Quick Doze not enabled"
147 ]
148 STATE_ACTIVE -> STATE_QUICK_DOZE_DELAY [
149 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
150 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700151
152 STATE_INACTIVE -> STATE_ACTIVE [
153 label="handleMotionDetectedLocked(), becomeActiveLocked()"
154 ]
155 STATE_INACTIVE -> STATE_IDLE_PENDING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700156 STATE_INACTIVE -> STATE_QUICK_DOZE_DELAY [
157 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
158 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700159
160 STATE_IDLE_PENDING -> STATE_ACTIVE [
161 label="handleMotionDetectedLocked(), becomeActiveLocked()"
162 ]
163 STATE_IDLE_PENDING -> STATE_SENSING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700164 STATE_IDLE_PENDING -> STATE_QUICK_DOZE_DELAY [
165 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
166 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700167
168 STATE_SENSING -> STATE_ACTIVE [
169 label="handleMotionDetectedLocked(), becomeActiveLocked()"
170 ]
171 STATE_SENSING -> STATE_LOCATING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700172 STATE_SENSING -> STATE_QUICK_DOZE_DELAY [
173 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
174 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700175 STATE_SENSING -> STATE_IDLE [
176 label="stepIdleStateLocked()\n"
177 + "No Location Manager OR (no Network provider AND no GPS provider)"
178 ]
179
180 STATE_LOCATING -> STATE_ACTIVE [
181 label="handleMotionDetectedLocked(), becomeActiveLocked()"
182 ]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700183 STATE_LOCATING -> STATE_QUICK_DOZE_DELAY [
184 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
185 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700186 STATE_LOCATING -> STATE_IDLE [label="stepIdleStateLocked()"]
187
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700188 STATE_QUICK_DOZE_DELAY -> STATE_ACTIVE [
189 label="handleMotionDetectedLocked(), becomeActiveLocked()"
190 ]
191 STATE_QUICK_DOZE_DELAY -> STATE_IDLE [label="stepIdleStateLocked()"]
192
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700193 STATE_IDLE -> STATE_ACTIVE [label="handleMotionDetectedLocked(), becomeActiveLocked()"]
194 STATE_IDLE -> STATE_IDLE_MAINTENANCE [label="stepIdleStateLocked()"]
195
196 STATE_IDLE_MAINTENANCE -> STATE_ACTIVE [
197 label="handleMotionDetectedLocked(), becomeActiveLocked()"
198 ]
199 STATE_IDLE_MAINTENANCE -> STATE_IDLE [
200 label="stepIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
201 ]
202 }
203
204 subgraph light {
205 label="light"
206
207 LIGHT_STATE_ACTIVE [
208 label="LIGHT_STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon"
209 ]
210 LIGHT_STATE_INACTIVE [label="LIGHT_STATE_INACTIVE\nScreen off AND Not charging"]
211 LIGHT_STATE_PRE_IDLE [
212 label="LIGHT_STATE_PRE_IDLE\n"
213 + "Delay going into LIGHT_STATE_IDLE due to some running jobs or alarms"
214 ]
215 LIGHT_STATE_IDLE [label="LIGHT_STATE_IDLE\n"]
216 LIGHT_STATE_WAITING_FOR_NETWORK [
217 label="LIGHT_STATE_WAITING_FOR_NETWORK\n"
218 + "Coming out of LIGHT_STATE_IDLE, waiting for network"
219 ]
220 LIGHT_STATE_IDLE_MAINTENANCE [label="LIGHT_STATE_IDLE_MAINTENANCE\n"]
221 LIGHT_STATE_OVERRIDE [
222 label="LIGHT_STATE_OVERRIDE\nDevice in deep doze, light no longer changing states"
223 ]
224
225 LIGHT_STATE_ACTIVE -> LIGHT_STATE_INACTIVE [
226 label="becomeInactiveIfAppropriateLocked()"
227 ]
228 LIGHT_STATE_ACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
229
230 LIGHT_STATE_INACTIVE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
231 LIGHT_STATE_INACTIVE -> LIGHT_STATE_PRE_IDLE [label="active jobs"]
232 LIGHT_STATE_INACTIVE -> LIGHT_STATE_IDLE [label="no active jobs"]
233 LIGHT_STATE_INACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
234
235 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
236 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_IDLE [
237 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
238 ]
239 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
240
241 LIGHT_STATE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
242 LIGHT_STATE_IDLE -> LIGHT_STATE_WAITING_FOR_NETWORK [label="no network"]
243 LIGHT_STATE_IDLE -> LIGHT_STATE_IDLE_MAINTENANCE
244 LIGHT_STATE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
245
246 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
247 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_IDLE_MAINTENANCE
248 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_OVERRIDE [
249 label="deep goes to STATE_IDLE"
250 ]
251
252 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
253 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_IDLE [
254 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
255 ]
256 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
257
258 LIGHT_STATE_OVERRIDE -> LIGHT_STATE_ACTIVE [
259 label="handleMotionDetectedLocked(), becomeActiveLocked()"
260 ]
261 }
262 }
Kweku Adams3ba574f2019-03-19 12:45:55 -0700263 </pre>
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700264 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700265public class DeviceIdleController extends SystemService
266 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700267 private static final String TAG = "DeviceIdleController";
268
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700269 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700270
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700271 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700272
Dianne Hackborn953fc942016-03-29 15:36:24 -0700273 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800274
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700275 private AlarmManager mAlarmManager;
Kweku Adamsb7ce1902019-01-30 10:55:34 -0800276 private AlarmManagerInternal mLocalAlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700277 private IBatteryStats mBatteryStats;
Dianne Hackborn85e35642017-01-12 15:10:57 -0800278 private ActivityManagerInternal mLocalActivityManager;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700279 private ActivityTaskManagerInternal mLocalActivityTaskManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700280 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700281 private PowerManager mPowerManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700282 private INetworkPolicyManager mNetworkPolicyManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700283 private SensorManager mSensorManager;
Robin Leec4d424c2018-12-07 15:09:13 +0100284 private final boolean mUseMotionSensor;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700285 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700286 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700287 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700288 private Intent mLightIdleIntent;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700289 private AnyMotionDetector mAnyMotionDetector;
Makoto Onukie4918212018-02-06 11:30:15 -0800290 private final AppStateTracker mAppStateTracker;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800291 private boolean mLightEnabled;
292 private boolean mDeepEnabled;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700293 private boolean mQuickDozeActivated;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700294 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700295 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700296 private boolean mScreenOn;
297 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700298 private boolean mNotMoving;
299 private boolean mLocating;
300 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700301 private boolean mHasGps;
302 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700303 private Location mLastGenericLocation;
304 private Location mLastGpsLocation;
Amith Yamasani396a10c2018-01-19 10:58:07 -0800305 // Current locked state of the screen
306 private boolean mScreenLocked;
Robin Lee876b88542018-11-13 17:22:24 +0100307 private int mNumBlockingConstraints = 0;
308
309 /**
310 * Constraints are the "handbrakes" that stop the device from moving into a lower state until
311 * every one is released at the same time.
312 *
313 * @see #registerDeviceIdleConstraintInternal(IDeviceIdleConstraint, String, int)
314 */
315 private final ArrayMap<IDeviceIdleConstraint, DeviceIdleConstraintTracker>
316 mConstraints = new ArrayMap<>();
317 private ConstraintController mConstraintController;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700318
319 /** Device is currently active. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700320 @VisibleForTesting
321 static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700322 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700323 @VisibleForTesting
324 static final int STATE_INACTIVE = 1;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700325 /** Device is past the initial inactive period, and waiting for the next idle period. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700326 @VisibleForTesting
327 static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700328 /** Device is currently sensing motion. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700329 @VisibleForTesting
330 static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700331 /** Device is currently finding location (and may still be sensing). */
Kweku Adams00e3a372018-09-28 16:57:09 -0700332 @VisibleForTesting
333 static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700334 /** Device is in the idle state, trying to stay asleep as much as possible. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700335 @VisibleForTesting
336 static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700337 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700338 @VisibleForTesting
339 static final int STATE_IDLE_MAINTENANCE = 6;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700340 /**
341 * Device is inactive and should go straight into idle (foregoing motion and location
342 * monitoring), but allow some time for current work to complete first.
343 */
344 @VisibleForTesting
345 static final int STATE_QUICK_DOZE_DELAY = 7;
Amith Yamasani396a10c2018-01-19 10:58:07 -0800346
Denny cy Leec5a7c292019-01-01 17:37:55 +0800347 private static final int ACTIVE_REASON_UNKNOWN = 0;
348 private static final int ACTIVE_REASON_MOTION = 1;
349 private static final int ACTIVE_REASON_SCREEN = 2;
350 private static final int ACTIVE_REASON_CHARGING = 3;
351 private static final int ACTIVE_REASON_UNLOCKED = 4;
352 private static final int ACTIVE_REASON_FROM_BINDER_CALL = 5;
353 private static final int ACTIVE_REASON_FORCED = 6;
354 private static final int ACTIVE_REASON_ALARM = 7;
355 @VisibleForTesting
356 static final int SET_IDLE_FACTOR_RESULT_UNINIT = -1;
357 @VisibleForTesting
358 static final int SET_IDLE_FACTOR_RESULT_IGNORED = 0;
359 @VisibleForTesting
360 static final int SET_IDLE_FACTOR_RESULT_OK = 1;
361 @VisibleForTesting
362 static final int SET_IDLE_FACTOR_RESULT_NOT_SUPPORT = 2;
363 @VisibleForTesting
364 static final int SET_IDLE_FACTOR_RESULT_INVALID = 3;
365 @VisibleForTesting
366 static final long MIN_STATE_STEP_ALARM_CHANGE = 60 * 1000;
367 @VisibleForTesting
368 static final float MIN_PRE_IDLE_FACTOR_CHANGE = 0.05f;
369
Kweku Adams00e3a372018-09-28 16:57:09 -0700370 @VisibleForTesting
371 static String stateToString(int state) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700372 switch (state) {
373 case STATE_ACTIVE: return "ACTIVE";
374 case STATE_INACTIVE: return "INACTIVE";
375 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700376 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700377 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700378 case STATE_IDLE: return "IDLE";
379 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700380 case STATE_QUICK_DOZE_DELAY: return "QUICK_DOZE_DELAY";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700381 default: return Integer.toString(state);
382 }
383 }
384
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700385 /** Device is currently active. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700386 @VisibleForTesting
387 static final int LIGHT_STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700388 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700389 @VisibleForTesting
390 static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700391 /** Device is about to go idle for the first time, wait for current work to complete. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700392 @VisibleForTesting
393 static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700394 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700395 @VisibleForTesting
396 static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700397 /** Device is in the light idle state, we want to go in to idle maintenance but are
398 * waiting for network connectivity before doing so. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700399 @VisibleForTesting
400 static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700401 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700402 @VisibleForTesting
403 static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800404 /** Device light idle state is overriden, now applying deep doze state. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700405 @VisibleForTesting
406 static final int LIGHT_STATE_OVERRIDE = 7;
407
408 @VisibleForTesting
409 static String lightStateToString(int state) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700410 switch (state) {
411 case LIGHT_STATE_ACTIVE: return "ACTIVE";
412 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700413 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700414 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700415 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700416 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
417 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
418 default: return Integer.toString(state);
419 }
420 }
421
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700422 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700423 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700424
425 private long mInactiveTimeout;
426 private long mNextAlarmTime;
427 private long mNextIdlePendingDelay;
428 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700429 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700430 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700431 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800432 private long mCurIdleBudget;
433 private long mMaintenanceStartTime;
Denny cy Leec5a7c292019-01-01 17:37:55 +0800434 private long mIdleStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700435
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800436 private int mActiveIdleOpCount;
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800437 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
438 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
439 // (especially NetworkPolicyManager) can shut
440 // down.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800441 private boolean mJobsActive;
442 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800443 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800444
Denny cy Leec5a7c292019-01-01 17:37:55 +0800445 /* Factor to apply to INACTIVE_TIMEOUT and IDLE_AFTER_INACTIVE_TIMEOUT in order to enter
446 * STATE_IDLE faster or slower. Don't apply this to SENSING_TIMEOUT or LOCATING_TIMEOUT because:
447 * - Both of them are shorter
448 * - Device sensor might take time be to become be stabilized
449 * Also don't apply the factor if the device is in motion because device motion provides a
450 * stronger signal than a prediction algorithm.
451 */
452 private float mPreIdleFactor;
453 private float mLastPreIdleFactor;
454 private int mActiveReason;
455
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700456 public final AtomicFile mConfigFile;
457
Yao Chenca5edbb2016-01-13 14:44:36 -0800458 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
459 new RemoteCallbackList<IMaintenanceActivityListener>();
460
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700461 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700462 * Package names the system has white-listed to opt out of power save restrictions,
463 * except for device idle mode.
464 */
465 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
466
467 /**
Sudheer Shanka3f4d7702017-04-28 17:38:03 -0700468 * Package names the user has white-listed using commandline option to opt out of
469 * power save restrictions, except for device idle mode.
470 */
471 private final ArraySet<String> mPowerSaveWhitelistUserAppsExceptIdle = new ArraySet<>();
472
473 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700474 * Package names the system has white-listed to opt out of power save restrictions for
475 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700476 */
477 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
478
479 /**
480 * Package names the user has white-listed to opt out of power save restrictions.
481 */
482 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
483
484 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700485 * App IDs of built-in system apps that have been white-listed except for idle modes.
486 */
487 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
488 = new SparseBooleanArray();
489
490 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700491 * App IDs of built-in system apps that have been white-listed.
492 */
493 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
494
495 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700496 * App IDs that have been white-listed to opt out of power save restrictions, except
497 * for device idle modes.
498 */
499 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
500
501 /**
502 * Current app IDs that are in the complete power save white list, but shouldn't be
503 * excluded from idle modes. This array can be shared with others because it will not be
504 * modified once set.
505 */
506 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
507
508 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700509 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700510 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700511 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700512
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700513 /**
514 * Current app IDs that are in the complete power save white list. This array can
515 * be shared with others because it will not be modified once set.
516 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700517 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700518
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700519 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800520 * App IDs that have been white-listed by the user to opt out of power save restrictions.
521 */
522 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
523
524 /**
525 * Current app IDs that are in the user power save white list. This array can
526 * be shared with others because it will not be modified once set.
527 */
528 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
529
530 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700531 * List of end times for UIDs that are temporarily marked as being allowed to access
532 * the network and acquire wakelocks. Times are in milliseconds.
533 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700534 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
535 = new SparseArray<>();
536
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -0700537 private NetworkPolicyManagerInternal mNetworkPolicyManagerInternal;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700538
539 /**
540 * Current app IDs of temporarily whitelist apps for high-priority messages.
541 */
542 private int[] mTempWhitelistAppIdArray = new int[0];
543
Suprabh Shukla08105642017-09-26 14:45:30 -0700544 /**
545 * Apps in the system whitelist that have been taken out (probably because the user wanted to).
546 * They can be restored back by calling restoreAppToSystemWhitelist(String).
547 */
548 private ArrayMap<String, Integer> mRemovedFromSystemWhitelistApps = new ArrayMap<>();
549
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800550 private static final int EVENT_NULL = 0;
551 private static final int EVENT_NORMAL = 1;
552 private static final int EVENT_LIGHT_IDLE = 2;
553 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800554 private static final int EVENT_DEEP_IDLE = 4;
555 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800556
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700557 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
558 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700559 private final String[] mEventReasons = new String[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800560
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700561 private void addEvent(int cmd, String reason) {
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800562 if (mEventCmds[0] != cmd) {
563 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
564 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700565 System.arraycopy(mEventReasons, 0, mEventReasons, 1, EVENT_BUFFER_SIZE - 1);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800566 mEventCmds[0] = cmd;
567 mEventTimes[0] = SystemClock.elapsedRealtime();
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700568 mEventReasons[0] = reason;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800569 }
570 }
571
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700572 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
573 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700574 switch (intent.getAction()) {
575 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700576 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700577 } break;
578 case Intent.ACTION_BATTERY_CHANGED: {
Robin Lee204cb222018-12-07 15:17:44 +0100579 boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
580 boolean plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700581 synchronized (DeviceIdleController.this) {
Robin Lee204cb222018-12-07 15:17:44 +0100582 updateChargingLocked(present && plugged);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700583 }
584 } break;
585 case Intent.ACTION_PACKAGE_REMOVED: {
586 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
587 Uri data = intent.getData();
588 String ssp;
589 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
590 removePowerSaveWhitelistAppInternal(ssp);
591 }
592 }
593 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700594 }
595 }
596 };
597
598 private final AlarmManager.OnAlarmListener mLightAlarmListener
599 = new AlarmManager.OnAlarmListener() {
600 @Override
601 public void onAlarm() {
602 synchronized (DeviceIdleController.this) {
603 stepLightIdleStateLocked("s:alarm");
604 }
605 }
606 };
607
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700608 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
609 = new AlarmManager.OnAlarmListener() {
610 @Override
611 public void onAlarm() {
612 if (mState == STATE_SENSING) {
613 synchronized (DeviceIdleController.this) {
Kweku Adams00e3a372018-09-28 16:57:09 -0700614 // Restart the device idle progression in case the device moved but the screen
615 // didn't turn on.
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700616 becomeInactiveIfAppropriateLocked();
617 }
618 }
619 }
620 };
621
Kweku Adamsb7ce1902019-01-30 10:55:34 -0800622 @VisibleForTesting
623 final AlarmManager.OnAlarmListener mDeepAlarmListener
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700624 = new AlarmManager.OnAlarmListener() {
625 @Override
626 public void onAlarm() {
627 synchronized (DeviceIdleController.this) {
628 stepIdleStateLocked("s:alarm");
629 }
630 }
631 };
632
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800633 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
634 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700635 // When coming out of a deep idle, we will add in some delay before we allow
636 // the system to settle down and finish the maintenance window. This is
637 // to give a chance for any pending work to be scheduled.
638 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
639 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
640 mConstants.MIN_DEEP_MAINTENANCE_TIME);
641 } else {
642 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
643 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
644 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800645 }
646 };
647
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -0700648 private final BroadcastReceiver mInteractivityReceiver = new BroadcastReceiver() {
649 @Override
650 public void onReceive(Context context, Intent intent) {
Dianne Hackborn9b5ebc92017-09-08 13:45:35 -0700651 synchronized (DeviceIdleController.this) {
652 updateInteractivityLocked();
653 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700654 }
655 };
656
Kweku Adams00e3a372018-09-28 16:57:09 -0700657 @VisibleForTesting
658 final class MotionListener extends TriggerEventListener
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700659 implements SensorEventListener {
660
661 boolean active = false;
662
Kweku Adams00e3a372018-09-28 16:57:09 -0700663 public boolean isActive() {
664 return active;
665 }
666
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700667 @Override
668 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700669 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700670 active = false;
671 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700672 }
673 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700674
675 @Override
676 public void onSensorChanged(SensorEvent event) {
677 synchronized (DeviceIdleController.this) {
678 mSensorManager.unregisterListener(this, mMotionSensor);
679 active = false;
680 motionLocked();
681 }
682 }
683
684 @Override
685 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
686
687 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700688 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700689 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
690 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
691 } else {
692 success = mSensorManager.registerListener(
693 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
694 }
695 if (success) {
696 active = true;
697 } else {
698 Slog.e(TAG, "Unable to register for " + mMotionSensor);
699 }
700 return success;
701 }
702
703 public void unregisterLocked() {
704 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
705 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
706 } else {
707 mSensorManager.unregisterListener(mMotionListener);
708 }
709 active = false;
710 }
711 }
Kweku Adams00e3a372018-09-28 16:57:09 -0700712 @VisibleForTesting final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700713
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700714 private final LocationListener mGenericLocationListener = new LocationListener() {
715 @Override
716 public void onLocationChanged(Location location) {
717 synchronized (DeviceIdleController.this) {
718 receivedGenericLocationLocked(location);
719 }
720 }
721
722 @Override
723 public void onStatusChanged(String provider, int status, Bundle extras) {
724 }
725
726 @Override
727 public void onProviderEnabled(String provider) {
728 }
729
730 @Override
731 public void onProviderDisabled(String provider) {
732 }
733 };
734
735 private final LocationListener mGpsLocationListener = new LocationListener() {
736 @Override
737 public void onLocationChanged(Location location) {
738 synchronized (DeviceIdleController.this) {
739 receivedGpsLocationLocked(location);
740 }
741 }
742
743 @Override
744 public void onStatusChanged(String provider, int status, Bundle extras) {
745 }
746
747 @Override
748 public void onProviderEnabled(String provider) {
749 }
750
751 @Override
752 public void onProviderDisabled(String provider) {
753 }
754 };
755
Adam Lesinski31c05d12015-06-09 17:34:04 -0700756 /**
757 * All times are in milliseconds. These constants are kept synchronized with the system
758 * global Settings. Any access to this class or its fields should be done while
759 * holding the DeviceIdleController lock.
760 */
Robin Lee876b88542018-11-13 17:22:24 +0100761 public final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700762 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700763 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
764 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700765 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700766 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700767 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
768 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800769 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
770 = "light_idle_maintenance_min_budget";
771 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
772 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700773 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
774 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700775 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
776 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700777 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
778 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700779 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
780 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
781 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
782 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
783 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700784 private static final String KEY_QUICK_DOZE_DELAY_TIMEOUT = "quick_doze_delay_to";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700785 private static final String KEY_IDLE_TIMEOUT = "idle_to";
786 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
787 private static final String KEY_IDLE_FACTOR = "idle_factor";
788 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
789 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
790 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700791 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
792 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700793 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
794 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700795 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
796 "notification_whitelist_duration";
Amith Yamasani396a10c2018-01-19 10:58:07 -0800797 /**
798 * Whether to wait for the user to unlock the device before causing screen-on to
799 * exit doze. Default = true
800 */
801 private static final String KEY_WAIT_FOR_UNLOCK = "wait_for_unlock";
Denny cy Leec5a7c292019-01-01 17:37:55 +0800802 private static final String KEY_PRE_IDLE_FACTOR_LONG =
803 "pre_idle_factor_long";
804 private static final String KEY_PRE_IDLE_FACTOR_SHORT =
805 "pre_idle_factor_short";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700806
807 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700808 * This is the time, after becoming inactive, that we go in to the first
809 * light-weight idle mode.
810 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
811 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
812 */
813 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
814
815 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700816 * This is amount of time we will wait from the point where we decide we would
817 * like to go idle until we actually do, while waiting for jobs and other current
818 * activity to finish.
819 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
820 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
821 */
822 public long LIGHT_PRE_IDLE_TIMEOUT;
823
824 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700825 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700826 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
827 * @see #KEY_LIGHT_IDLE_TIMEOUT
828 */
829 public long LIGHT_IDLE_TIMEOUT;
830
831 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700832 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
833 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
834 * @see #KEY_LIGHT_IDLE_FACTOR
835 */
836 public float LIGHT_IDLE_FACTOR;
837
838 /**
Kweku Adams00e3a372018-09-28 16:57:09 -0700839 * This is the maximum time we will run in idle maintenance mode.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700840 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
841 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
842 */
843 public long LIGHT_MAX_IDLE_TIMEOUT;
844
845 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800846 * This is the minimum amount of time we want to make available for maintenance mode
847 * when lightly idling. That is, we will always have at least this amount of time
848 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700849 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800850 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700851 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800852 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
853
854 /**
855 * This is the maximum amount of time we want to make available for maintenance mode
856 * when lightly idling. That is, if the system isn't using up its minimum maintenance
857 * budget and this time is being added to the budget reserve, this is the maximum
858 * reserve size we will allow to grow and thus the maximum amount of time we will
859 * allow for the maintenance window.
860 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
861 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
862 */
863 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700864
865 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700866 * This is the minimum amount of time that we will stay in maintenance mode after
867 * a light doze. We have this minimum to allow various things to respond to switching
868 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700869 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700870 * mode immediately.
871 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
872 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
873 */
874 public long MIN_LIGHT_MAINTENANCE_TIME;
875
876 /**
877 * This is the minimum amount of time that we will stay in maintenance mode after
878 * a full doze. We have this minimum to allow various things to respond to switching
879 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700880 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700881 * mode immediately.
882 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
883 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
884 */
885 public long MIN_DEEP_MAINTENANCE_TIME;
886
887 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700888 * This is the time, after becoming inactive, at which we start looking at the
889 * motion sensor to determine if the device is being left alone. We don't do this
890 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700891 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700892 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
893 * @see #KEY_INACTIVE_TIMEOUT
894 */
895 public long INACTIVE_TIMEOUT;
896
897 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700898 * If we don't receive a callback from AnyMotion in this amount of time +
899 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700900 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
901 * will be ignored.
902 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
903 * @see #KEY_SENSING_TIMEOUT
904 */
905 public long SENSING_TIMEOUT;
906
907 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700908 * This is how long we will wait to try to get a good location fix before going in to
909 * idle mode.
910 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
911 * @see #KEY_LOCATING_TIMEOUT
912 */
913 public long LOCATING_TIMEOUT;
914
915 /**
916 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
917 * on to idle. We will be trying to get an accuracy fix at least this good or until
918 * {@link #LOCATING_TIMEOUT} expires.
919 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
920 * @see #KEY_LOCATION_ACCURACY
921 */
922 public float LOCATION_ACCURACY;
923
924 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700925 * This is the time, after seeing motion, that we wait after becoming inactive from
926 * that until we start looking for motion again.
927 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
928 * @see #KEY_MOTION_INACTIVE_TIMEOUT
929 */
930 public long MOTION_INACTIVE_TIMEOUT;
931
932 /**
933 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700934 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700935 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
936 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
937 */
938 public long IDLE_AFTER_INACTIVE_TIMEOUT;
939
940 /**
941 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700942 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
943 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700944 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
945 * @see #KEY_IDLE_PENDING_TIMEOUT
946 */
947 public long IDLE_PENDING_TIMEOUT;
948
949 /**
950 * Maximum pending idle timeout (time spent running) we will be allowed to use.
951 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
952 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
953 */
954 public long MAX_IDLE_PENDING_TIMEOUT;
955
956 /**
957 * Scaling factor to apply to current pending idle timeout each time we cycle through
958 * that state.
959 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
960 * @see #KEY_IDLE_PENDING_FACTOR
961 */
962 public float IDLE_PENDING_FACTOR;
963
964 /**
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700965 * This is amount of time we will wait from the point where we go into
966 * STATE_QUICK_DOZE_DELAY until we actually go into STATE_IDLE, while waiting for jobs
967 * and other current activity to finish.
968 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
969 * @see #KEY_QUICK_DOZE_DELAY_TIMEOUT
970 */
971 public long QUICK_DOZE_DELAY_TIMEOUT;
972
973 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700974 * This is the initial time that we want to sit in the idle state before waking up
975 * again to return to pending idle and allowing normal work to run.
976 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
977 * @see #KEY_IDLE_TIMEOUT
978 */
979 public long IDLE_TIMEOUT;
980
981 /**
982 * Maximum idle duration we will be allowed to use.
983 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
984 * @see #KEY_MAX_IDLE_TIMEOUT
985 */
986 public long MAX_IDLE_TIMEOUT;
987
988 /**
989 * Scaling factor to apply to current idle timeout each time we cycle through that state.
990 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
991 * @see #KEY_IDLE_FACTOR
992 */
993 public float IDLE_FACTOR;
994
995 /**
996 * This is the minimum time we will allow until the next upcoming alarm for us to
997 * actually go in to idle mode.
998 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
999 * @see #KEY_MIN_TIME_TO_ALARM
1000 */
1001 public long MIN_TIME_TO_ALARM;
1002
1003 /**
1004 * Max amount of time to temporarily whitelist an app when it receives a high priority
1005 * tickle.
1006 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
1007 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
1008 */
1009 public long MAX_TEMP_APP_WHITELIST_DURATION;
1010
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001011 /**
1012 * Amount of time we would like to whitelist an app that is receiving an MMS.
1013 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
1014 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
1015 */
1016 public long MMS_TEMP_APP_WHITELIST_DURATION;
1017
Dianne Hackborn451c3462015-07-21 17:39:46 -07001018 /**
1019 * Amount of time we would like to whitelist an app that is receiving an SMS.
1020 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
1021 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
1022 */
1023 public long SMS_TEMP_APP_WHITELIST_DURATION;
1024
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001025 /**
1026 * Amount of time we would like to whitelist an app that is handling a
1027 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
1028 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
1029 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
1030 */
1031 public long NOTIFICATION_WHITELIST_DURATION;
1032
Denny cy Leec5a7c292019-01-01 17:37:55 +08001033 /**
1034 * Pre idle time factor use to make idle delay longer
1035 */
1036 public float PRE_IDLE_FACTOR_LONG;
1037
1038 /**
1039 * Pre idle time factor use to make idle delay shorter
1040 */
1041 public float PRE_IDLE_FACTOR_SHORT;
1042
Amith Yamasani396a10c2018-01-19 10:58:07 -08001043 public boolean WAIT_FOR_UNLOCK;
1044
Adam Lesinski31c05d12015-06-09 17:34:04 -07001045 private final ContentResolver mResolver;
shreerag597da8a2017-07-21 14:24:14 -07001046 private final boolean mSmallBatteryDevice;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001047 private final KeyValueListParser mParser = new KeyValueListParser(',');
1048
1049 public Constants(Handler handler, ContentResolver resolver) {
1050 super(handler);
1051 mResolver = resolver;
shreerag597da8a2017-07-21 14:24:14 -07001052 mSmallBatteryDevice = ActivityManager.isSmallBatteryDevice();
1053 mResolver.registerContentObserver(
1054 Settings.Global.getUriFor(Settings.Global.DEVICE_IDLE_CONSTANTS),
Joe LaPennaf33b5bf2016-03-23 15:19:47 -07001055 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001056 updateConstants();
1057 }
1058
1059 @Override
1060 public void onChange(boolean selfChange, Uri uri) {
1061 updateConstants();
1062 }
1063
1064 private void updateConstants() {
1065 synchronized (DeviceIdleController.this) {
1066 try {
1067 mParser.setString(Settings.Global.getString(mResolver,
shreerag597da8a2017-07-21 14:24:14 -07001068 Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -07001069 } catch (IllegalArgumentException e) {
1070 // Failed to parse the settings string, log this and move on
1071 // with defaults.
1072 Slog.e(TAG, "Bad device idle settings", e);
1073 }
1074
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001075 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
Dianne Hackborn953fc942016-03-29 15:36:24 -07001076 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
Suprabh Shukla85fff7d2018-05-08 17:39:24 -07001077 !COMPRESS_TIME ? 3 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001078 LIGHT_PRE_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_PRE_IDLE_TIMEOUT,
Suprabh Shukla85fff7d2018-05-08 17:39:24 -07001079 !COMPRESS_TIME ? 3 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001080 LIGHT_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -07001081 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
1082 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
1083 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001084 LIGHT_MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001085 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001086 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001087 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001088 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001089 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001090 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
1091 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001092 MIN_LIGHT_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001093 KEY_MIN_LIGHT_MAINTENANCE_TIME,
1094 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001095 MIN_DEEP_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001096 KEY_MIN_DEEP_MAINTENANCE_TIME,
1097 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -07001098 long inactiveTimeoutDefault = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001099 INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -07001100 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001101 SENSING_TIMEOUT = mParser.getDurationMillis(KEY_SENSING_TIMEOUT,
Kweku Adams9da2bb92018-12-20 06:34:39 -08001102 !COMPRESS_TIME ? 4 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001103 LOCATING_TIMEOUT = mParser.getDurationMillis(KEY_LOCATING_TIMEOUT,
Kweku Adams9da2bb92018-12-20 06:34:39 -08001104 !COMPRESS_TIME ? 30 * 1000L : 15 * 1000L);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001105 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001106 MOTION_INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_MOTION_INACTIVE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001107 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -07001108 long idleAfterInactiveTimeout = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001109 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
1110 KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -07001111 !COMPRESS_TIME ? idleAfterInactiveTimeout
1112 : (idleAfterInactiveTimeout / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001113 IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001114 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001115 MAX_IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001116 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
1117 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
1118 2f);
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001119 QUICK_DOZE_DELAY_TIMEOUT = mParser.getDurationMillis(
1120 KEY_QUICK_DOZE_DELAY_TIMEOUT, !COMPRESS_TIME ? 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001121 IDLE_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001122 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001123 MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001124 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
1125 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
1126 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001127 MIN_TIME_TO_ALARM = mParser.getDurationMillis(KEY_MIN_TIME_TO_ALARM,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001128 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001129 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001130 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001131 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -07001132 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001133 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn451c3462015-07-21 17:39:46 -07001134 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001135 NOTIFICATION_WHITELIST_DURATION = mParser.getDurationMillis(
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001136 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Kweku Adams43fabba2019-03-07 15:47:37 -08001137 WAIT_FOR_UNLOCK = mParser.getBoolean(KEY_WAIT_FOR_UNLOCK, true);
Denny cy Leec5a7c292019-01-01 17:37:55 +08001138 PRE_IDLE_FACTOR_LONG = mParser.getFloat(KEY_PRE_IDLE_FACTOR_LONG, 1.67f);
1139 PRE_IDLE_FACTOR_SHORT = mParser.getFloat(KEY_PRE_IDLE_FACTOR_SHORT, 0.33f);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001140 }
1141 }
1142
1143 void dump(PrintWriter pw) {
1144 pw.println(" Settings:");
1145
Dianne Hackborn953fc942016-03-29 15:36:24 -07001146 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
1147 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1148 pw.println();
1149
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001150 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
1151 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
1152 pw.println();
1153
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001154 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
1155 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
1156 pw.println();
1157
Dianne Hackborn953fc942016-03-29 15:36:24 -07001158 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
1159 pw.print(LIGHT_IDLE_FACTOR);
1160 pw.println();
1161
1162 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
1163 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
1164 pw.println();
1165
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001166 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
1167 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
1168 pw.println();
1169
1170 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
1171 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001172 pw.println();
1173
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001174 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
1175 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
1176 pw.println();
1177
1178 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
1179 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
1180 pw.println();
1181
Dianne Hackborna750a632015-06-16 17:18:23 -07001182 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001183 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
1184 pw.println();
1185
Dianne Hackborna750a632015-06-16 17:18:23 -07001186 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001187 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
1188 pw.println();
1189
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001190 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
1191 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
1192 pw.println();
1193
1194 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
1195 pw.print(LOCATION_ACCURACY); pw.print("m");
1196 pw.println();
1197
Dianne Hackborna750a632015-06-16 17:18:23 -07001198 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001199 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
1200 pw.println();
1201
Dianne Hackborna750a632015-06-16 17:18:23 -07001202 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001203 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1204 pw.println();
1205
Dianne Hackborna750a632015-06-16 17:18:23 -07001206 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001207 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
1208 pw.println();
1209
Dianne Hackborna750a632015-06-16 17:18:23 -07001210 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001211 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
1212 pw.println();
1213
Dianne Hackborna750a632015-06-16 17:18:23 -07001214 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001215 pw.println(IDLE_PENDING_FACTOR);
1216
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001217 pw.print(" "); pw.print(KEY_QUICK_DOZE_DELAY_TIMEOUT); pw.print("=");
1218 TimeUtils.formatDuration(QUICK_DOZE_DELAY_TIMEOUT, pw);
1219 pw.println();
1220
Dianne Hackborna750a632015-06-16 17:18:23 -07001221 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001222 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
1223 pw.println();
1224
Dianne Hackborna750a632015-06-16 17:18:23 -07001225 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001226 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
1227 pw.println();
1228
Dianne Hackborna750a632015-06-16 17:18:23 -07001229 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001230 pw.println(IDLE_FACTOR);
1231
Dianne Hackborna750a632015-06-16 17:18:23 -07001232 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001233 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
1234 pw.println();
1235
Dianne Hackborna750a632015-06-16 17:18:23 -07001236 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001237 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
1238 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001239
1240 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
1241 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
1242 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -07001243
1244 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
1245 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
1246 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001247
1248 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
1249 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
1250 pw.println();
Amith Yamasani396a10c2018-01-19 10:58:07 -08001251
1252 pw.print(" "); pw.print(KEY_WAIT_FOR_UNLOCK); pw.print("=");
1253 pw.println(WAIT_FOR_UNLOCK);
Denny cy Leec5a7c292019-01-01 17:37:55 +08001254
1255 pw.print(" "); pw.print(KEY_PRE_IDLE_FACTOR_LONG); pw.print("=");
1256 pw.println(PRE_IDLE_FACTOR_LONG);
1257
1258 pw.print(" "); pw.print(KEY_PRE_IDLE_FACTOR_SHORT); pw.print("=");
1259 pw.println(PRE_IDLE_FACTOR_SHORT);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001260 }
1261 }
1262
1263 private Constants mConstants;
1264
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001265 @Override
1266 public void onAnyMotionResult(int result) {
1267 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001268 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
1269 synchronized (this) {
1270 cancelSensingTimeoutAlarmLocked();
1271 }
1272 }
Kevin Gabayandcf47012016-07-08 10:41:24 -07001273 if ((result == AnyMotionDetector.RESULT_MOVED) ||
1274 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001275 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -07001276 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001277 }
1278 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001279 if (mState == STATE_SENSING) {
1280 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001281 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001282 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001283 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001284 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001285 } else if (mState == STATE_LOCATING) {
1286 // If we are currently locating, note that we are not moving and step
1287 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001288 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001289 mNotMoving = true;
1290 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001291 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001292 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001293 }
1294 }
1295 }
1296 }
1297
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001298 private static final int MSG_WRITE_CONFIG = 1;
1299 private static final int MSG_REPORT_IDLE_ON = 2;
1300 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1301 private static final int MSG_REPORT_IDLE_OFF = 4;
1302 private static final int MSG_REPORT_ACTIVE = 5;
1303 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1304 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1305 private static final int MSG_FINISH_IDLE_OP = 8;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001306 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 9;
Robin Lee876b88542018-11-13 17:22:24 +01001307 private static final int MSG_SEND_CONSTRAINT_MONITORING = 10;
Denny cy Leec5a7c292019-01-01 17:37:55 +08001308 private static final int MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR = 11;
1309 private static final int MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR = 12;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001310
1311 final class MyHandler extends Handler {
1312 MyHandler(Looper looper) {
1313 super(looper);
1314 }
1315
1316 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001317 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001318 switch (msg.what) {
1319 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001320 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001321 handleWriteConfigFile();
1322 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001323 case MSG_REPORT_IDLE_ON:
1324 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001325 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001326 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001327 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001328 final boolean lightChanged;
1329 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001330 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001331 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1332 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001333 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001334 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1335 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001336 try {
1337 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001338 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001339 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001340 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001341 } catch (RemoteException e) {
1342 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001343 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001344 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1345 }
1346 if (lightChanged) {
1347 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1348 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001349 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001350 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001351 } break;
1352 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001353 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001354 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001355 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001356 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001357 try {
1358 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001359 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1360 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001361 } catch (RemoteException e) {
1362 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001363 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001364 incActiveIdleOps();
1365 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1366 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001367 }
1368 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001369 incActiveIdleOps();
1370 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1371 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001372 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001373 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001374 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001375 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001376 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001377 } break;
1378 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001379 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001380 String activeReason = (String)msg.obj;
1381 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001382 EventLogTags.writeDeviceIdleOffStart(
1383 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001384 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001385 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001386 try {
1387 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001388 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1389 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001390 } catch (RemoteException e) {
1391 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001392 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001393 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1394 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001395 if (lightChanged) {
1396 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1397 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001398 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001399 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001400 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001401 // TODO: What is keeping the device awake at this point? Does it need to be?
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07001402 int appId = msg.arg1;
1403 checkTempAppWhitelistTimeout(appId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001404 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001405 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001406 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001407 boolean active = (msg.arg1 == 1);
1408 final int size = mMaintenanceActivityListeners.beginBroadcast();
1409 try {
1410 for (int i = 0; i < size; i++) {
1411 try {
1412 mMaintenanceActivityListeners.getBroadcastItem(i)
1413 .onMaintenanceActivityChanged(active);
1414 } catch (RemoteException ignored) {
1415 }
1416 }
1417 } finally {
1418 mMaintenanceActivityListeners.finishBroadcast();
1419 }
1420 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001421 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001422 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001423 decActiveIdleOps();
1424 } break;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001425 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1426 final int appId = msg.arg1;
1427 final boolean added = (msg.arg2 == 1);
1428 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, added);
1429 } break;
Robin Lee876b88542018-11-13 17:22:24 +01001430 case MSG_SEND_CONSTRAINT_MONITORING: {
1431 final IDeviceIdleConstraint constraint = (IDeviceIdleConstraint) msg.obj;
1432 final boolean monitoring = (msg.arg1 == 1);
1433 if (monitoring) {
1434 constraint.startMonitoring();
1435 } else {
1436 constraint.stopMonitoring();
1437 }
1438 } break;
Denny cy Leec5a7c292019-01-01 17:37:55 +08001439 case MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR: {
1440 updatePreIdleFactor();
1441 } break;
1442 case MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR: {
1443 updatePreIdleFactor();
1444 maybeDoImmediateMaintenance();
1445 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001446 }
1447 }
1448 }
1449
1450 final MyHandler mHandler;
1451
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001452 BinderService mBinderService;
1453
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001454 private final class BinderService extends IDeviceIdleController.Stub {
1455 @Override public void addPowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001456 if (DEBUG) {
1457 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1458 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001459 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1460 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001461 long ident = Binder.clearCallingIdentity();
1462 try {
1463 addPowerSaveWhitelistAppInternal(name);
1464 } finally {
1465 Binder.restoreCallingIdentity(ident);
1466 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001467 }
1468
1469 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001470 if (DEBUG) {
1471 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1472 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001473 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1474 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001475 long ident = Binder.clearCallingIdentity();
1476 try {
1477 removePowerSaveWhitelistAppInternal(name);
1478 } finally {
1479 Binder.restoreCallingIdentity(ident);
1480 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001481 }
1482
Suprabh Shukla08105642017-09-26 14:45:30 -07001483 @Override public void removeSystemPowerWhitelistApp(String name) {
1484 if (DEBUG) {
1485 Slog.d(TAG, "removeAppFromSystemWhitelist(name = " + name + ")");
1486 }
1487 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1488 null);
1489 long ident = Binder.clearCallingIdentity();
1490 try {
1491 removeSystemPowerWhitelistAppInternal(name);
1492 } finally {
1493 Binder.restoreCallingIdentity(ident);
1494 }
1495 }
1496
1497 @Override public void restoreSystemPowerWhitelistApp(String name) {
1498 if (DEBUG) {
1499 Slog.d(TAG, "restoreAppToSystemWhitelist(name = " + name + ")");
1500 }
1501 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1502 null);
1503 long ident = Binder.clearCallingIdentity();
1504 try {
1505 restoreSystemPowerWhitelistAppInternal(name);
1506 } finally {
1507 Binder.restoreCallingIdentity(ident);
1508 }
1509 }
1510
1511 public String[] getRemovedSystemPowerWhitelistApps() {
1512 return getRemovedSystemPowerWhitelistAppsInternal();
1513 }
1514
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001515 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1516 return getSystemPowerWhitelistExceptIdleInternal();
1517 }
1518
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001519 @Override public String[] getSystemPowerWhitelist() {
1520 return getSystemPowerWhitelistInternal();
1521 }
1522
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001523 @Override public String[] getUserPowerWhitelist() {
1524 return getUserPowerWhitelistInternal();
1525 }
1526
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001527 @Override public String[] getFullPowerWhitelistExceptIdle() {
1528 return getFullPowerWhitelistExceptIdleInternal();
1529 }
1530
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001531 @Override public String[] getFullPowerWhitelist() {
1532 return getFullPowerWhitelistInternal();
1533 }
1534
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001535 @Override public int[] getAppIdWhitelistExceptIdle() {
1536 return getAppIdWhitelistExceptIdleInternal();
1537 }
1538
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001539 @Override public int[] getAppIdWhitelist() {
1540 return getAppIdWhitelistInternal();
1541 }
1542
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001543 @Override public int[] getAppIdUserWhitelist() {
1544 return getAppIdUserWhitelistInternal();
1545 }
1546
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001547 @Override public int[] getAppIdTempWhitelist() {
1548 return getAppIdTempWhitelistInternal();
1549 }
1550
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001551 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1552 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1553 }
1554
Amith Yamasani06bf8242015-05-08 16:36:21 -07001555 @Override public boolean isPowerSaveWhitelistApp(String name) {
1556 return isPowerSaveWhitelistAppInternal(name);
1557 }
1558
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001559 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001560 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001561 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001562 }
1563
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001564 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1565 int userId, String reason) throws RemoteException {
1566 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001567 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001568 return duration;
1569 }
1570
Dianne Hackborn451c3462015-07-21 17:39:46 -07001571 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1572 int userId, String reason) throws RemoteException {
1573 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001574 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001575 return duration;
1576 }
1577
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001578 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001579 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001580 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001581 long ident = Binder.clearCallingIdentity();
1582 try {
1583 exitIdleInternal(reason);
1584 } finally {
1585 Binder.restoreCallingIdentity(ident);
1586 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001587 }
1588
Yao Chenca5edbb2016-01-13 14:44:36 -08001589 @Override public boolean registerMaintenanceActivityListener(
1590 IMaintenanceActivityListener listener) {
1591 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1592 }
1593
1594 @Override public void unregisterMaintenanceActivityListener(
1595 IMaintenanceActivityListener listener) {
1596 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1597 }
1598
Denny cy Leec5a7c292019-01-01 17:37:55 +08001599 @Override public int setPreIdleTimeoutMode(int mode) {
1600 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
1601 null);
1602 long ident = Binder.clearCallingIdentity();
1603 try {
1604 return DeviceIdleController.this.setPreIdleTimeoutMode(mode);
1605 } finally {
1606 Binder.restoreCallingIdentity(ident);
1607 }
1608 }
1609
1610 @Override public void resetPreIdleTimeoutMode() {
1611 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
1612 null);
1613 long ident = Binder.clearCallingIdentity();
1614 try {
1615 DeviceIdleController.this.resetPreIdleTimeoutMode();
1616 } finally {
1617 Binder.restoreCallingIdentity(ident);
1618 }
1619 }
1620
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001621 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1622 DeviceIdleController.this.dump(fd, pw, args);
1623 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001624
1625 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001626 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1627 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001628 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001629 }
1630
Felipe Lemeef134662016-08-10 14:46:39 -07001631 public class LocalService {
Robin Lee876b88542018-11-13 17:22:24 +01001632 public void onConstraintStateChanged(IDeviceIdleConstraint constraint, boolean active) {
1633 synchronized (DeviceIdleController.this) {
1634 onConstraintStateChangedLocked(constraint, active);
1635 }
1636 }
1637
1638 public void registerDeviceIdleConstraint(IDeviceIdleConstraint constraint, String name,
1639 @IDeviceIdleConstraint.MinimumState int minState) {
1640 registerDeviceIdleConstraintInternal(constraint, name, minState);
1641 }
1642
1643 public void unregisterDeviceIdleConstraint(IDeviceIdleConstraint constraint) {
1644 unregisterDeviceIdleConstraintInternal(constraint);
1645 }
1646
1647 public void exitIdle(String reason) {
1648 exitIdleInternal(reason);
1649 }
1650
Christopher Tatee0be7e82017-02-08 17:38:20 -08001651 // duration in milliseconds
1652 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1653 long duration, int userId, boolean sync, String reason) {
1654 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1655 userId, sync, reason);
1656 }
1657
1658 // duration in milliseconds
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07001659 public void addPowerSaveTempWhitelistAppDirect(int uid, long duration, boolean sync,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001660 String reason) {
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07001661 addPowerSaveTempWhitelistAppDirectInternal(0, uid, duration, sync, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001662 }
1663
Christopher Tatee0be7e82017-02-08 17:38:20 -08001664 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001665 public long getNotificationWhitelistDuration() {
1666 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1667 }
1668
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001669 public void setJobsActive(boolean active) {
1670 DeviceIdleController.this.setJobsActive(active);
1671 }
1672
1673 // Up-call from alarm manager.
1674 public void setAlarmsActive(boolean active) {
1675 DeviceIdleController.this.setAlarmsActive(active);
1676 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001677
Christopher Tate42a386b2016-11-07 12:21:21 -08001678 /** Is the app on any of the power save whitelists, whether system or user? */
1679 public boolean isAppOnWhitelist(int appid) {
1680 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1681 }
1682
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001683 /**
1684 * Returns the array of app ids whitelisted by user. Take care not to
1685 * modify this, as it is a reference to the original copy. But the reference
1686 * can change when the list changes, so it needs to be re-acquired when
1687 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1688 */
1689 public int[] getPowerSaveWhitelistUserAppIds() {
1690 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1691 }
Suprabh Shuklaa78acfd2017-10-13 19:29:36 -07001692
1693 public int[] getPowerSaveTempWhitelistAppIds() {
1694 return DeviceIdleController.this.getAppIdTempWhitelistInternal();
1695 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001696 }
1697
Kweku Adams00e3a372018-09-28 16:57:09 -07001698 static class Injector {
1699 private final Context mContext;
Kweku Adams799858b2018-10-08 17:19:08 -07001700 private ConnectivityService mConnectivityService;
Kweku Adams9da2bb92018-12-20 06:34:39 -08001701 private Constants mConstants;
Kweku Adams799858b2018-10-08 17:19:08 -07001702 private LocationManager mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001703
1704 Injector(Context ctx) {
1705 mContext = ctx;
1706 }
1707
1708 AlarmManager getAlarmManager() {
1709 return mContext.getSystemService(AlarmManager.class);
1710 }
1711
1712 AnyMotionDetector getAnyMotionDetector(Handler handler, SensorManager sm,
1713 AnyMotionDetector.DeviceIdleCallback callback, float angleThreshold) {
1714 return new AnyMotionDetector(getPowerManager(), handler, sm, callback, angleThreshold);
1715 }
1716
1717 AppStateTracker getAppStateTracker(Context ctx, Looper looper) {
1718 return new AppStateTracker(ctx, looper);
1719 }
1720
1721 ConnectivityService getConnectivityService() {
Kweku Adams799858b2018-10-08 17:19:08 -07001722 if (mConnectivityService == null) {
1723 mConnectivityService = (ConnectivityService) ServiceManager.getService(
1724 Context.CONNECTIVITY_SERVICE);
1725 }
1726 return mConnectivityService;
Kweku Adams00e3a372018-09-28 16:57:09 -07001727 }
1728
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001729 Constants getConstants(DeviceIdleController controller, Handler handler,
1730 ContentResolver resolver) {
Kweku Adams9da2bb92018-12-20 06:34:39 -08001731 if (mConstants == null) {
1732 mConstants = controller.new Constants(handler, resolver);
1733 }
1734 return mConstants;
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001735 }
1736
Kweku Adams00e3a372018-09-28 16:57:09 -07001737 LocationManager getLocationManager() {
Kweku Adams799858b2018-10-08 17:19:08 -07001738 if (mLocationManager == null) {
1739 mLocationManager = mContext.getSystemService(LocationManager.class);
1740 }
1741 return mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001742 }
1743
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001744 MyHandler getHandler(DeviceIdleController controller) {
1745 return controller.new MyHandler(BackgroundThread.getHandler().getLooper());
Kweku Adams00e3a372018-09-28 16:57:09 -07001746 }
1747
1748 PowerManager getPowerManager() {
1749 return mContext.getSystemService(PowerManager.class);
1750 }
Robin Lee876b88542018-11-13 17:22:24 +01001751
1752 SensorManager getSensorManager() {
1753 return mContext.getSystemService(SensorManager.class);
1754 }
1755
1756 ConstraintController getConstraintController(Handler handler, LocalService localService) {
1757 if (mContext.getPackageManager()
1758 .hasSystemFeature(PackageManager.FEATURE_LEANBACK_ONLY)) {
1759 return new TvConstraintController(mContext, handler);
1760 }
1761 return null;
1762 }
1763
1764 boolean useMotionSensor() {
1765 return mContext.getResources().getBoolean(
1766 com.android.internal.R.bool.config_autoPowerModeUseMotionSensor);
1767 }
Kweku Adams00e3a372018-09-28 16:57:09 -07001768 }
1769
1770 private final Injector mInjector;
1771
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001772 private ActivityTaskManagerInternal.ScreenObserver mScreenObserver =
1773 new ActivityTaskManagerInternal.ScreenObserver() {
Amith Yamasani396a10c2018-01-19 10:58:07 -08001774 @Override
1775 public void onAwakeStateChanged(boolean isAwake) { }
1776
1777 @Override
1778 public void onKeyguardStateChanged(boolean isShowing) {
1779 synchronized (DeviceIdleController.this) {
1780 DeviceIdleController.this.keyguardShowingLocked(isShowing);
1781 }
1782 }
1783 };
1784
Kweku Adams00e3a372018-09-28 16:57:09 -07001785 @VisibleForTesting DeviceIdleController(Context context, Injector injector) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001786 super(context);
Kweku Adams00e3a372018-09-28 16:57:09 -07001787 mInjector = injector;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001788 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
Kweku Adams00e3a372018-09-28 16:57:09 -07001789 mHandler = mInjector.getHandler(this);
1790 mAppStateTracker = mInjector.getAppStateTracker(context, FgThread.get().getLooper());
Makoto Onukie4918212018-02-06 11:30:15 -08001791 LocalServices.addService(AppStateTracker.class, mAppStateTracker);
Robin Lee876b88542018-11-13 17:22:24 +01001792 mUseMotionSensor = mInjector.useMotionSensor();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001793 }
1794
Kweku Adams00e3a372018-09-28 16:57:09 -07001795 public DeviceIdleController(Context context) {
1796 this(context, new Injector(context));
1797 }
1798
Christopher Tate42a386b2016-11-07 12:21:21 -08001799 boolean isAppOnWhitelistInternal(int appid) {
1800 synchronized (this) {
1801 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1802 }
1803 }
1804
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001805 int[] getPowerSaveWhitelistUserAppIds() {
1806 synchronized (this) {
1807 return mPowerSaveWhitelistUserAppIdArray;
1808 }
1809 }
1810
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001811 private static File getSystemDir() {
1812 return new File(Environment.getDataDirectory(), "system");
1813 }
1814
1815 @Override
1816 public void onStart() {
1817 final PackageManager pm = getContext().getPackageManager();
1818
1819 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001820 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001821 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001822 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001823 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1824 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1825 String pkg = allowPowerExceptIdle.valueAt(i);
1826 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001827 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1828 PackageManager.MATCH_SYSTEM_ONLY);
1829 int appid = UserHandle.getAppId(ai.uid);
1830 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1831 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001832 } catch (PackageManager.NameNotFoundException e) {
1833 }
1834 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001835 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1836 for (int i=0; i<allowPower.size(); i++) {
1837 String pkg = allowPower.valueAt(i);
1838 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001839 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1840 PackageManager.MATCH_SYSTEM_ONLY);
1841 int appid = UserHandle.getAppId(ai.uid);
1842 // These apps are on both the whitelist-except-idle as well
1843 // as the full whitelist, so they apply in all cases.
1844 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1845 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1846 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1847 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001848 } catch (PackageManager.NameNotFoundException e) {
1849 }
1850 }
1851
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001852 mConstants = mInjector.getConstants(this, mHandler, getContext().getContentResolver());
Adam Lesinski31c05d12015-06-09 17:34:04 -07001853
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001854 readConfigFileLocked();
1855 updateWhitelistAppIdsLocked();
1856
Dianne Hackborn88c41352016-04-07 15:18:58 -07001857 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001858 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08001859 mScreenLocked = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001860 // Start out assuming we are charging. If we aren't, we will at least get
1861 // a battery update the next time the level drops.
1862 mCharging = true;
Denny cy Leec5a7c292019-01-01 17:37:55 +08001863 mActiveReason = ACTIVE_REASON_UNKNOWN;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001864 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001865 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001866 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Denny cy Leec5a7c292019-01-01 17:37:55 +08001867 mPreIdleFactor = 1.0f;
1868 mLastPreIdleFactor = 1.0f;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001869 }
1870
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001871 mBinderService = new BinderService();
1872 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001873 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001874 }
1875
1876 @Override
1877 public void onBootPhase(int phase) {
1878 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1879 synchronized (this) {
Kweku Adams00e3a372018-09-28 16:57:09 -07001880 mAlarmManager = mInjector.getAlarmManager();
Kweku Adamsb7ce1902019-01-30 10:55:34 -08001881 mLocalAlarmManager = getLocalService(AlarmManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001882 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001883 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001884 mLocalActivityTaskManager = getLocalService(ActivityTaskManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001885 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Kweku Adams00e3a372018-09-28 16:57:09 -07001886 mPowerManager = mInjector.getPowerManager();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001887 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1888 "deviceidle_maint");
1889 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001890 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1891 "deviceidle_going_idle");
1892 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001893 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001894 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001895 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Robin Lee876b88542018-11-13 17:22:24 +01001896 mSensorManager = mInjector.getSensorManager();
Robin Leec4d424c2018-12-07 15:09:13 +01001897
1898 if (mUseMotionSensor) {
1899 int sigMotionSensorId = getContext().getResources().getInteger(
1900 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1901 if (sigMotionSensorId > 0) {
1902 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
1903 }
1904 if (mMotionSensor == null && getContext().getResources().getBoolean(
1905 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
1906 mMotionSensor = mSensorManager.getDefaultSensor(
1907 Sensor.TYPE_WRIST_TILT_GESTURE, true);
1908 }
1909 if (mMotionSensor == null) {
1910 // As a last ditch, fall back to SMD.
1911 mMotionSensor = mSensorManager.getDefaultSensor(
1912 Sensor.TYPE_SIGNIFICANT_MOTION, true);
1913 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001914 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001915
Joe LaPenna23d681b2015-08-27 15:12:11 -07001916 if (getContext().getResources().getBoolean(
1917 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001918 mLocationRequest = new LocationRequest()
1919 .setQuality(LocationRequest.ACCURACY_FINE)
1920 .setInterval(0)
1921 .setFastestInterval(0)
1922 .setNumUpdates(1);
1923 }
1924
Robin Lee876b88542018-11-13 17:22:24 +01001925 mConstraintController = mInjector.getConstraintController(
1926 mHandler, getLocalService(LocalService.class));
1927 if (mConstraintController != null) {
1928 mConstraintController.start();
1929 }
1930
Joe LaPenna23d681b2015-08-27 15:12:11 -07001931 float angleThreshold = getContext().getResources().getInteger(
1932 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kweku Adams00e3a372018-09-28 16:57:09 -07001933 mAnyMotionDetector = mInjector.getAnyMotionDetector(mHandler, mSensorManager, this,
1934 angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001935
Makoto Onukie4918212018-02-06 11:30:15 -08001936 mAppStateTracker.onSystemServicesReady();
1937
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001938 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001939 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1940 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001941 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1942 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1943 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001944
1945 IntentFilter filter = new IntentFilter();
1946 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001947 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001948
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001949 filter = new IntentFilter();
1950 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1951 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001952 getContext().registerReceiver(mReceiver, filter);
1953
Dianne Hackborn88c41352016-04-07 15:18:58 -07001954 filter = new IntentFilter();
1955 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001956 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001957
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001958 filter = new IntentFilter();
1959 filter.addAction(Intent.ACTION_SCREEN_OFF);
1960 filter.addAction(Intent.ACTION_SCREEN_ON);
1961 getContext().registerReceiver(mInteractivityReceiver, filter);
1962
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07001963 mLocalActivityManager.setDeviceIdleWhitelist(
1964 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001965 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001966
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001967 mLocalPowerManager.registerLowPowerModeObserver(ServiceType.QUICK_DOZE,
1968 state -> {
1969 synchronized (DeviceIdleController.this) {
1970 updateQuickDozeFlagLocked(state.batterySaverEnabled);
1971 }
1972 });
1973 updateQuickDozeFlagLocked(
1974 mLocalPowerManager.getLowPowerState(
1975 ServiceType.QUICK_DOZE).batterySaverEnabled);
1976
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001977 mLocalActivityTaskManager.registerScreenObserver(mScreenObserver);
Amith Yamasani396a10c2018-01-19 10:58:07 -08001978
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001979 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001980 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001981 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001982 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001983 }
1984 }
1985
Robin Lee876b88542018-11-13 17:22:24 +01001986 @VisibleForTesting
1987 boolean hasMotionSensor() {
1988 return mUseMotionSensor && mMotionSensor != null;
1989 }
1990
1991 private void registerDeviceIdleConstraintInternal(IDeviceIdleConstraint constraint,
1992 final String name, final int type) {
1993 final int minState;
1994 switch (type) {
1995 case IDeviceIdleConstraint.ACTIVE:
1996 minState = STATE_ACTIVE;
1997 break;
1998 case IDeviceIdleConstraint.SENSING_OR_ABOVE:
1999 minState = STATE_SENSING;
2000 break;
2001 default:
2002 Slog.wtf(TAG, "Registering device-idle constraint with invalid type: " + type);
2003 return;
2004 }
2005 synchronized (this) {
2006 if (mConstraints.containsKey(constraint)) {
2007 Slog.e(TAG, "Re-registering device-idle constraint: " + constraint + ".");
2008 return;
2009 }
2010 DeviceIdleConstraintTracker tracker = new DeviceIdleConstraintTracker(name, minState);
2011 mConstraints.put(constraint, tracker);
2012 updateActiveConstraintsLocked();
2013 }
2014 }
2015
2016 private void unregisterDeviceIdleConstraintInternal(IDeviceIdleConstraint constraint) {
2017 synchronized (this) {
2018 // Artifically force the constraint to inactive to unblock anything waiting for it.
2019 onConstraintStateChangedLocked(constraint, /* active= */ false);
2020
2021 // Let the constraint know that we are not listening to it any more.
2022 setConstraintMonitoringLocked(constraint, /* monitoring= */ false);
2023 mConstraints.remove(constraint);
2024 }
2025 }
2026
2027 @GuardedBy("this")
2028 private void onConstraintStateChangedLocked(IDeviceIdleConstraint constraint, boolean active) {
2029 DeviceIdleConstraintTracker tracker = mConstraints.get(constraint);
2030 if (tracker == null) {
2031 Slog.e(TAG, "device-idle constraint " + constraint + " has not been registered.");
2032 return;
2033 }
2034 if (active != tracker.active && tracker.monitoring) {
2035 tracker.active = active;
2036 mNumBlockingConstraints += (tracker.active ? +1 : -1);
2037 if (mNumBlockingConstraints == 0) {
2038 if (mState == STATE_ACTIVE) {
2039 becomeInactiveIfAppropriateLocked();
2040 } else if (mNextAlarmTime == 0 || mNextAlarmTime < SystemClock.elapsedRealtime()) {
2041 stepIdleStateLocked("s:" + tracker.name);
2042 }
2043 }
2044 }
2045 }
2046
2047 @GuardedBy("this")
2048 private void setConstraintMonitoringLocked(IDeviceIdleConstraint constraint, boolean monitor) {
2049 DeviceIdleConstraintTracker tracker = mConstraints.get(constraint);
2050 if (tracker.monitoring != monitor) {
2051 tracker.monitoring = monitor;
2052 updateActiveConstraintsLocked();
2053 // We send the callback on a separate thread instead of just relying on oneway as
2054 // the client could be in the system server with us and cause re-entry problems.
2055 mHandler.obtainMessage(MSG_SEND_CONSTRAINT_MONITORING,
2056 /* monitoring= */ monitor ? 1 : 0,
2057 /* <not used>= */ -1,
2058 /* constraint= */ constraint).sendToTarget();
2059 }
2060 }
2061
2062 @GuardedBy("this")
2063 private void updateActiveConstraintsLocked() {
2064 mNumBlockingConstraints = 0;
2065 for (int i = 0; i < mConstraints.size(); i++) {
2066 final IDeviceIdleConstraint constraint = mConstraints.keyAt(i);
2067 final DeviceIdleConstraintTracker tracker = mConstraints.valueAt(i);
2068 final boolean monitoring = (tracker.minState == mState);
2069 if (monitoring != tracker.monitoring) {
2070 setConstraintMonitoringLocked(constraint, monitoring);
2071 tracker.active = monitoring;
2072 }
2073 if (tracker.monitoring && tracker.active) {
2074 mNumBlockingConstraints++;
2075 }
2076 }
2077 }
2078
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002079 public boolean addPowerSaveWhitelistAppInternal(String name) {
2080 synchronized (this) {
2081 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002082 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002083 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002084 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
2085 reportPowerSaveWhitelistChangedLocked();
2086 updateWhitelistAppIdsLocked();
2087 writeConfigFileLocked();
2088 }
2089 return true;
2090 } catch (PackageManager.NameNotFoundException e) {
2091 return false;
2092 }
2093 }
2094 }
2095
2096 public boolean removePowerSaveWhitelistAppInternal(String name) {
2097 synchronized (this) {
2098 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
2099 reportPowerSaveWhitelistChangedLocked();
2100 updateWhitelistAppIdsLocked();
2101 writeConfigFileLocked();
2102 return true;
2103 }
2104 }
2105 return false;
2106 }
2107
Felipe Lemef8a46232016-02-10 13:51:54 -08002108 public boolean getPowerSaveWhitelistAppInternal(String name) {
2109 synchronized (this) {
2110 return mPowerSaveWhitelistUserApps.containsKey(name);
2111 }
2112 }
2113
Suprabh Shukla08105642017-09-26 14:45:30 -07002114 void resetSystemPowerWhitelistInternal() {
2115 synchronized (this) {
2116 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
2117 mRemovedFromSystemWhitelistApps.clear();
2118 reportPowerSaveWhitelistChangedLocked();
2119 updateWhitelistAppIdsLocked();
2120 writeConfigFileLocked();
2121 }
2122 }
2123
2124 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
2125 synchronized (this) {
2126 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
2127 return false;
2128 }
2129 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
2130 reportPowerSaveWhitelistChangedLocked();
2131 updateWhitelistAppIdsLocked();
2132 writeConfigFileLocked();
2133 return true;
2134 }
2135 }
2136
2137 public boolean removeSystemPowerWhitelistAppInternal(String name) {
2138 synchronized (this) {
2139 if (!mPowerSaveWhitelistApps.containsKey(name)) {
2140 return false;
2141 }
2142 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
2143 reportPowerSaveWhitelistChangedLocked();
2144 updateWhitelistAppIdsLocked();
2145 writeConfigFileLocked();
2146 return true;
2147 }
2148 }
2149
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002150 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
2151 synchronized (this) {
2152 try {
2153 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
2154 PackageManager.MATCH_ANY_USER);
2155 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
2156 == null) {
2157 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
2158 reportPowerSaveWhitelistChangedLocked();
2159 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
2160 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
2161 mPowerSaveWhitelistExceptIdleAppIds);
Makoto Onuki71755c92018-01-16 14:15:44 -08002162
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002163 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002164 }
2165 return true;
2166 } catch (PackageManager.NameNotFoundException e) {
2167 return false;
2168 }
2169 }
2170 }
2171
2172 public void resetPowerSaveWhitelistExceptIdleInternal() {
2173 synchronized (this) {
2174 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
2175 mPowerSaveWhitelistUserAppsExceptIdle)) {
2176 reportPowerSaveWhitelistChangedLocked();
2177 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
2178 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
2179 mPowerSaveWhitelistExceptIdleAppIds);
2180 mPowerSaveWhitelistUserAppsExceptIdle.clear();
Makoto Onuki71755c92018-01-16 14:15:44 -08002181
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002182 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002183 }
2184 }
2185 }
2186
2187 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
2188 synchronized (this) {
2189 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
2190 }
2191 }
2192
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002193 public String[] getSystemPowerWhitelistExceptIdleInternal() {
2194 synchronized (this) {
2195 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2196 String[] apps = new String[size];
2197 for (int i = 0; i < size; i++) {
2198 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
2199 }
2200 return apps;
2201 }
2202 }
2203
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002204 public String[] getSystemPowerWhitelistInternal() {
2205 synchronized (this) {
2206 int size = mPowerSaveWhitelistApps.size();
2207 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002208 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002209 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
2210 }
2211 return apps;
2212 }
2213 }
2214
Suprabh Shukla08105642017-09-26 14:45:30 -07002215 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
2216 synchronized (this) {
2217 int size = mRemovedFromSystemWhitelistApps.size();
2218 final String[] apps = new String[size];
2219 for (int i = 0; i < size; i++) {
2220 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
2221 }
2222 return apps;
2223 }
2224 }
2225
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002226 public String[] getUserPowerWhitelistInternal() {
2227 synchronized (this) {
2228 int size = mPowerSaveWhitelistUserApps.size();
2229 String[] apps = new String[size];
2230 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2231 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
2232 }
2233 return apps;
2234 }
2235 }
2236
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002237 public String[] getFullPowerWhitelistExceptIdleInternal() {
2238 synchronized (this) {
2239 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
2240 String[] apps = new String[size];
2241 int cur = 0;
2242 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
2243 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
2244 cur++;
2245 }
2246 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2247 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
2248 cur++;
2249 }
2250 return apps;
2251 }
2252 }
2253
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002254 public String[] getFullPowerWhitelistInternal() {
2255 synchronized (this) {
2256 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
2257 String[] apps = new String[size];
2258 int cur = 0;
2259 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
2260 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
2261 cur++;
2262 }
2263 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2264 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
2265 cur++;
2266 }
2267 return apps;
2268 }
2269 }
2270
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002271 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
2272 synchronized (this) {
2273 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
2274 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2275 }
2276 }
2277
Amith Yamasani06bf8242015-05-08 16:36:21 -07002278 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
2279 synchronized (this) {
2280 return mPowerSaveWhitelistApps.containsKey(packageName)
2281 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2282 }
2283 }
2284
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002285 public int[] getAppIdWhitelistExceptIdleInternal() {
2286 synchronized (this) {
2287 return mPowerSaveWhitelistExceptIdleAppIdArray;
2288 }
2289 }
2290
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002291 public int[] getAppIdWhitelistInternal() {
2292 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002293 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002294 }
2295 }
2296
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002297 public int[] getAppIdUserWhitelistInternal() {
2298 synchronized (this) {
2299 return mPowerSaveWhitelistUserAppIdArray;
2300 }
2301 }
2302
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002303 public int[] getAppIdTempWhitelistInternal() {
2304 synchronized (this) {
2305 return mTempWhitelistAppIdArray;
2306 }
2307 }
2308
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002309 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
2310 int userId, String reason) throws RemoteException {
2311 getContext().enforceCallingPermission(
2312 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2313 "No permission to change device idle whitelist");
2314 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002315 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002316 Binder.getCallingPid(),
2317 callingUid,
2318 userId,
2319 /*allowAll=*/ false,
2320 /*requireFull=*/ false,
2321 "addPowerSaveTempWhitelistApp", null);
2322 final long token = Binder.clearCallingIdentity();
2323 try {
2324 addPowerSaveTempWhitelistAppInternal(callingUid,
2325 packageName, duration, userId, true, reason);
2326 } finally {
2327 Binder.restoreCallingIdentity(token);
2328 }
2329 }
2330
Sudheer Shanka326b3112017-11-27 14:40:57 -08002331 void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
2332 throws RemoteException {
2333 getContext().enforceCallingPermission(
2334 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2335 "No permission to change device idle whitelist");
2336 final int callingUid = Binder.getCallingUid();
2337 userId = ActivityManager.getService().handleIncomingUser(
2338 Binder.getCallingPid(),
2339 callingUid,
2340 userId,
2341 /*allowAll=*/ false,
2342 /*requireFull=*/ false,
2343 "removePowerSaveTempWhitelistApp", null);
2344 final long token = Binder.clearCallingIdentity();
2345 try {
2346 removePowerSaveTempWhitelistAppInternal(packageName, userId);
2347 } finally {
2348 Binder.restoreCallingIdentity(token);
2349 }
2350 }
2351
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002352 /**
2353 * Adds an app to the temporary whitelist and resets the endTime for granting the
2354 * app an exemption to access network and acquire wakelocks.
2355 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002356 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002357 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002358 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07002359 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002360 addPowerSaveTempWhitelistAppDirectInternal(callingUid, uid, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002361 } catch (NameNotFoundException e) {
2362 }
2363 }
2364
Dianne Hackborna750a632015-06-16 17:18:23 -07002365 /**
2366 * Adds an app to the temporary whitelist and resets the endTime for granting the
2367 * app an exemption to access network and acquire wakelocks.
2368 */
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002369 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int uid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002370 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002371 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002372 boolean informWhitelistChanged = false;
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002373 int appId = UserHandle.getAppId(uid);
Dianne Hackborna750a632015-06-16 17:18:23 -07002374 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002375 int callingAppId = UserHandle.getAppId(callingUid);
2376 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
2377 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
2378 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
2379 + " is not on whitelist");
2380 }
2381 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002382 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002383 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
2384 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07002385 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002386 if (newEntry) {
2387 entry = new Pair<>(new MutableLong(0), reason);
2388 mTempWhitelistAppIdEndTimes.put(appId, entry);
2389 }
2390 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07002391 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002392 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07002393 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002394 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002395 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002396 try {
2397 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002398 reason, uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002399 } catch (RemoteException e) {
2400 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002401 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002402 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002403 if (sync) {
2404 informWhitelistChanged = true;
2405 } else {
2406 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
2407 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002408 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002409 reportTempWhitelistChangedLocked();
2410 }
2411 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002412 if (informWhitelistChanged) {
2413 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002414 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002415 }
2416
Sudheer Shanka326b3112017-11-27 14:40:57 -08002417 /**
2418 * Removes an app from the temporary whitelist and notifies the observers.
2419 */
2420 private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
2421 try {
2422 final int uid = getContext().getPackageManager().getPackageUidAsUser(
2423 packageName, userId);
2424 final int appId = UserHandle.getAppId(uid);
2425 removePowerSaveTempWhitelistAppDirectInternal(appId);
2426 } catch (NameNotFoundException e) {
2427 }
2428 }
2429
2430 private void removePowerSaveTempWhitelistAppDirectInternal(int appId) {
2431 synchronized (this) {
2432 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
2433 if (idx < 0) {
2434 // Nothing else to do
2435 return;
2436 }
2437 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
2438 mTempWhitelistAppIdEndTimes.removeAt(idx);
2439 onAppRemovedFromTempWhitelistLocked(appId, reason);
2440 }
2441 }
2442
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002443 private void postTempActiveTimeoutMessage(int appId, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002444 if (DEBUG) {
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002445 Slog.d(TAG, "postTempActiveTimeoutMessage: appId=" + appId + ", delay=" + delay);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002446 }
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002447 mHandler.sendMessageDelayed(
2448 mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, appId, 0), delay);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002449 }
2450
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002451 void checkTempAppWhitelistTimeout(int appId) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002452 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002453 if (DEBUG) {
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002454 Slog.d(TAG, "checkTempAppWhitelistTimeout: appId=" + appId + ", timeNow=" + timeNow);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002455 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002456 synchronized (this) {
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002457 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002458 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002459 // Nothing to do
2460 return;
2461 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002462 if (timeNow >= entry.first.value) {
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002463 mTempWhitelistAppIdEndTimes.delete(appId);
2464 onAppRemovedFromTempWhitelistLocked(appId, entry.second);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002465 } else {
2466 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002467 if (DEBUG) {
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002468 Slog.d(TAG, "Time to remove AppId " + appId + ": " + entry.first.value);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002469 }
Nicholas Sauer7d2287b2019-04-11 11:16:34 -07002470 postTempActiveTimeoutMessage(appId, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002471 }
2472 }
2473 }
2474
Sudheer Shanka326b3112017-11-27 14:40:57 -08002475 @GuardedBy("this")
2476 private void onAppRemovedFromTempWhitelistLocked(int appId, String reason) {
2477 if (DEBUG) {
2478 Slog.d(TAG, "Removing appId " + appId + " from temp whitelist");
2479 }
2480 updateTempWhitelistAppIdsLocked(appId, false);
2481 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 0)
2482 .sendToTarget();
2483 reportTempWhitelistChangedLocked();
2484 try {
2485 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
2486 reason, appId);
2487 } catch (RemoteException e) {
2488 }
2489 }
2490
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002491 public void exitIdleInternal(String reason) {
2492 synchronized (this) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002493 mActiveReason = ACTIVE_REASON_FROM_BINDER_CALL;
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002494 becomeActiveLocked(reason, Binder.getCallingUid());
2495 }
2496 }
2497
Kweku Adams799858b2018-10-08 17:19:08 -07002498 @VisibleForTesting
2499 boolean isNetworkConnected() {
2500 synchronized (this) {
2501 return mNetworkConnected;
2502 }
2503 }
2504
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002505 void updateConnectivityState(Intent connIntent) {
2506 ConnectivityService cm;
2507 synchronized (this) {
Kweku Adams799858b2018-10-08 17:19:08 -07002508 cm = mInjector.getConnectivityService();
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002509 }
2510 if (cm == null) {
2511 return;
2512 }
2513 // Note: can't call out to ConnectivityService with our lock held.
2514 NetworkInfo ni = cm.getActiveNetworkInfo();
2515 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002516 boolean conn;
2517 if (ni == null) {
2518 conn = false;
2519 } else {
2520 if (connIntent == null) {
2521 conn = ni.isConnected();
2522 } else {
2523 final int networkType =
2524 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
2525 ConnectivityManager.TYPE_NONE);
2526 if (ni.getType() != networkType) {
2527 return;
2528 }
2529 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
2530 false);
2531 }
2532 }
2533 if (conn != mNetworkConnected) {
2534 mNetworkConnected = conn;
2535 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2536 stepLightIdleStateLocked("network");
2537 }
2538 }
2539 }
2540 }
2541
Kweku Adams00e3a372018-09-28 16:57:09 -07002542 @VisibleForTesting
2543 boolean isScreenOn() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002544 synchronized (this) {
2545 return mScreenOn;
2546 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002547 }
2548
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07002549 void updateInteractivityLocked() {
2550 // The interactivity state from the power manager tells us whether the display is
2551 // in a state that we need to keep things running so they will update at a normal
2552 // frequency.
2553 boolean screenOn = mPowerManager.isInteractive();
2554 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002555 if (!screenOn && mScreenOn) {
2556 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002557 if (!mForceIdle) {
2558 becomeInactiveIfAppropriateLocked();
2559 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002560 } else if (screenOn) {
2561 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08002562 if (!mForceIdle && (!mScreenLocked || !mConstants.WAIT_FOR_UNLOCK)) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002563 mActiveReason = ACTIVE_REASON_SCREEN;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002564 becomeActiveLocked("screen", Process.myUid());
2565 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002566 }
2567 }
2568
Kweku Adams00e3a372018-09-28 16:57:09 -07002569 @VisibleForTesting
2570 boolean isCharging() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002571 synchronized (this) {
2572 return mCharging;
2573 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002574 }
2575
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002576 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002577 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002578 if (!charging && mCharging) {
2579 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002580 if (!mForceIdle) {
2581 becomeInactiveIfAppropriateLocked();
2582 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002583 } else if (charging) {
2584 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002585 if (!mForceIdle) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002586 mActiveReason = ACTIVE_REASON_CHARGING;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002587 becomeActiveLocked("charging", Process.myUid());
2588 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002589 }
2590 }
2591
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002592 @VisibleForTesting
2593 boolean isQuickDozeEnabled() {
2594 synchronized (this) {
2595 return mQuickDozeActivated;
2596 }
2597 }
2598
2599 /** Updates the quick doze flag and enters deep doze if appropriate. */
2600 @VisibleForTesting
2601 void updateQuickDozeFlagLocked(boolean enabled) {
2602 if (DEBUG) Slog.i(TAG, "updateQuickDozeFlagLocked: enabled=" + enabled);
2603 mQuickDozeActivated = enabled;
2604 if (enabled) {
2605 // If Quick Doze is enabled, see if we should go straight into it.
2606 becomeInactiveIfAppropriateLocked();
2607 }
2608 // Going from Deep Doze to Light Idle (if quick doze becomes disabled) is tricky and
2609 // probably not worth the overhead, so leave in deep doze if that's the case until the
2610 // next natural time to come out of it.
2611 }
2612
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002613
2614 /** Returns true if the screen is locked. */
2615 @VisibleForTesting
2616 boolean isKeyguardShowing() {
2617 synchronized (this) {
2618 return mScreenLocked;
2619 }
2620 }
2621
2622 @VisibleForTesting
Amith Yamasani396a10c2018-01-19 10:58:07 -08002623 void keyguardShowingLocked(boolean showing) {
2624 if (DEBUG) Slog.i(TAG, "keyguardShowing=" + showing);
2625 if (mScreenLocked != showing) {
2626 mScreenLocked = showing;
2627 if (mScreenOn && !mForceIdle && !mScreenLocked) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002628 mActiveReason = ACTIVE_REASON_UNLOCKED;
Amith Yamasani396a10c2018-01-19 10:58:07 -08002629 becomeActiveLocked("unlocked", Process.myUid());
2630 }
2631 }
2632 }
2633
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002634 @VisibleForTesting
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002635 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002636 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002637 mHandler.sendMessage(msg);
2638 }
2639
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002640 void becomeActiveLocked(String activeReason, int activeUid) {
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002641 becomeActiveLocked(activeReason, activeUid, mConstants.INACTIVE_TIMEOUT, true);
2642 }
2643
2644 private void becomeActiveLocked(String activeReason, int activeUid,
2645 long newInactiveTimeout, boolean changeLightIdle) {
2646 if (DEBUG) {
2647 Slog.i(TAG, "becomeActiveLocked, reason=" + activeReason
2648 + ", changeLightIdle=" + changeLightIdle);
2649 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002650 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002651 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002652 mState = STATE_ACTIVE;
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002653 mInactiveTimeout = newInactiveTimeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002654 mCurIdleBudget = 0;
2655 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002656 resetIdleManagementLocked();
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002657
2658 if (changeLightIdle) {
2659 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
2660 mLightState = LIGHT_STATE_ACTIVE;
2661 resetLightIdleManagementLocked();
2662 // Only report active if light is also ACTIVE.
2663 scheduleReportActiveLocked(activeReason, activeUid);
2664 addEvent(EVENT_NORMAL, activeReason);
2665 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002666 }
2667 }
2668
Kweku Adams00e3a372018-09-28 16:57:09 -07002669 /** Must only be used in tests. */
2670 @VisibleForTesting
2671 void setDeepEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002672 synchronized (this) {
2673 mDeepEnabled = enabled;
2674 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002675 }
2676
2677 /** Must only be used in tests. */
2678 @VisibleForTesting
2679 void setLightEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002680 synchronized (this) {
2681 mLightEnabled = enabled;
2682 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002683 }
2684
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002685 /** Sanity check to make sure DeviceIdleController and AlarmManager are on the same page. */
2686 private void verifyAlarmStateLocked() {
2687 if (mState == STATE_ACTIVE && mNextAlarmTime != 0) {
2688 Slog.wtf(TAG, "mState=ACTIVE but mNextAlarmTime=" + mNextAlarmTime);
2689 }
2690 if (mState != STATE_IDLE && mLocalAlarmManager.isIdling()) {
2691 Slog.wtf(TAG, "mState=" + stateToString(mState) + " but AlarmManager is idling");
2692 }
2693 if (mState == STATE_IDLE && !mLocalAlarmManager.isIdling()) {
2694 Slog.wtf(TAG, "mState=IDLE but AlarmManager is not idling");
2695 }
2696 if (mLightState == LIGHT_STATE_ACTIVE && mNextLightAlarmTime != 0) {
2697 Slog.wtf(TAG, "mLightState=ACTIVE but mNextLightAlarmTime is "
2698 + TimeUtils.formatDuration(mNextLightAlarmTime - SystemClock.elapsedRealtime())
2699 + " from now");
2700 }
2701 }
2702
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002703 void becomeInactiveIfAppropriateLocked() {
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002704 verifyAlarmStateLocked();
2705
2706 final boolean isScreenBlockingInactive =
2707 mScreenOn && (!mConstants.WAIT_FOR_UNLOCK || !mScreenLocked);
2708 if (DEBUG) {
2709 Slog.d(TAG, "becomeInactiveIfAppropriateLocked():"
2710 + " isScreenBlockingInactive=" + isScreenBlockingInactive
2711 + " (mScreenOn=" + mScreenOn
2712 + ", WAIT_FOR_UNLOCK=" + mConstants.WAIT_FOR_UNLOCK
2713 + ", mScreenLocked=" + mScreenLocked + ")"
2714 + " mCharging=" + mCharging
2715 + " mForceIdle=" + mForceIdle
2716 );
2717 }
2718 if (!mForceIdle && (mCharging || isScreenBlockingInactive)) {
2719 return;
2720 }
2721 // Become inactive and determine if we will ultimately go idle.
2722 if (mDeepEnabled) {
2723 if (mQuickDozeActivated) {
2724 if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
2725 || mState == STATE_IDLE_MAINTENANCE) {
2726 // Already "idling". Don't want to restart the process.
2727 // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
2728 // values, so returning here is safe.
2729 return;
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002730 }
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002731 if (DEBUG) {
2732 Slog.d(TAG, "Moved from "
2733 + stateToString(mState) + " to STATE_QUICK_DOZE_DELAY");
2734 }
2735 mState = STATE_QUICK_DOZE_DELAY;
2736 // Make sure any motion sensing or locating is stopped.
2737 resetIdleManagementLocked();
2738 // Wait a small amount of time in case something (eg: background service from
2739 // recently closed app) needs to finish running.
Kweku Adamsbf277862019-07-19 15:20:44 -07002740 // Use a non-wakeup alarm for going into quick doze in case an AlarmClock alarm
2741 // is scheduled soon. The non-wakeup alarm will be delayed by at most 2 minutes.
2742 scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false, false);
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002743 EventLogTags.writeDeviceIdle(mState, "no activity");
2744 } else if (mState == STATE_ACTIVE) {
2745 mState = STATE_INACTIVE;
2746 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2747 resetIdleManagementLocked();
2748 long delay = mInactiveTimeout;
2749 if (shouldUseIdleTimeoutFactorLocked()) {
2750 delay = (long) (mPreIdleFactor * delay);
2751 }
2752 scheduleAlarmLocked(delay, false);
2753 EventLogTags.writeDeviceIdle(mState, "no activity");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002754 }
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002755 }
2756 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
2757 mLightState = LIGHT_STATE_INACTIVE;
2758 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2759 resetLightIdleManagementLocked();
2760 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
2761 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002762 }
2763 }
2764
Kweku Adams00e3a372018-09-28 16:57:09 -07002765 private void resetIdleManagementLocked() {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002766 mNextIdlePendingDelay = 0;
2767 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002768 mNextLightIdleDelay = 0;
Denny cy Leec5a7c292019-01-01 17:37:55 +08002769 mIdleStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002770 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002771 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002772 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002773 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002774 mAnyMotionDetector.stop();
Robin Lee876b88542018-11-13 17:22:24 +01002775 updateActiveConstraintsLocked();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002776 }
2777
Kweku Adams00e3a372018-09-28 16:57:09 -07002778 private void resetLightIdleManagementLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002779 cancelLightAlarmLocked();
2780 }
2781
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002782 void exitForceIdleLocked() {
2783 if (mForceIdle) {
2784 mForceIdle = false;
2785 if (mScreenOn || mCharging) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002786 mActiveReason = ACTIVE_REASON_FORCED;
Dianne Hackborn88c41352016-04-07 15:18:58 -07002787 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002788 }
2789 }
2790 }
2791
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002792 /**
2793 * Must only be used in tests.
2794 *
2795 * This sets the state value directly and thus doesn't trigger any behavioral changes.
2796 */
2797 @VisibleForTesting
2798 void setLightStateForTest(int lightState) {
Kweku Adams799858b2018-10-08 17:19:08 -07002799 synchronized (this) {
2800 mLightState = lightState;
2801 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002802 }
2803
Kweku Adams00e3a372018-09-28 16:57:09 -07002804 @VisibleForTesting
2805 int getLightState() {
2806 return mLightState;
2807 }
2808
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002809 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002810 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002811 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002812 // there is nothing left to do for light mode.
2813 return;
2814 }
2815
2816 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2817 EventLogTags.writeDeviceIdleLightStep();
2818
2819 switch (mLightState) {
2820 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002821 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002822 // Reset the upcoming idle delays.
2823 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002824 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002825 if (!isOpsInactiveLocked()) {
2826 // We have some active ops going on... give them a chance to finish
2827 // before going in to our first idle.
2828 mLightState = LIGHT_STATE_PRE_IDLE;
2829 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2830 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2831 break;
2832 }
2833 // Nothing active, fall through to immediately idle.
2834 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002835 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002836 if (mMaintenanceStartTime != 0) {
2837 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2838 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2839 // We didn't use up all of our minimum budget; add this to the reserve.
2840 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2841 } else {
2842 // We used more than our minimum budget; this comes out of the reserve.
2843 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2844 }
2845 }
2846 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002847 scheduleLightAlarmLocked(mNextLightIdleDelay);
2848 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2849 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2850 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2851 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2852 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002853 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2854 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002855 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002856 addEvent(EVENT_LIGHT_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002857 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002858 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2859 break;
2860 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002861 case LIGHT_STATE_WAITING_FOR_NETWORK:
2862 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2863 // We have been idling long enough, now it is time to do some work.
2864 mActiveIdleOpCount = 1;
2865 mActiveIdleWakeLock.acquire();
2866 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2867 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2868 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2869 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2870 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2871 }
2872 scheduleLightAlarmLocked(mCurIdleBudget);
2873 if (DEBUG) Slog.d(TAG,
2874 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2875 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2876 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002877 addEvent(EVENT_LIGHT_MAINTENANCE, null);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002878 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2879 } else {
2880 // We'd like to do maintenance, but currently don't have network
2881 // connectivity... let's try to wait until the network comes back.
2882 // We'll only wait for another full idle period, however, and then give up.
2883 scheduleLightAlarmLocked(mNextLightIdleDelay);
2884 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2885 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2886 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002887 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002888 break;
2889 }
2890 }
2891
Kweku Adams00e3a372018-09-28 16:57:09 -07002892 @VisibleForTesting
2893 int getState() {
2894 return mState;
2895 }
2896
2897 @VisibleForTesting
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002898 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002899 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002900 EventLogTags.writeDeviceIdleStep();
2901
2902 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002903 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002904 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2905 if (mState != STATE_ACTIVE) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002906 mActiveReason = ACTIVE_REASON_ALARM;
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002907 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002908 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002909 }
2910 return;
2911 }
2912
Robin Lee876b88542018-11-13 17:22:24 +01002913 if (mNumBlockingConstraints != 0 && !mForceIdle) {
2914 // We have some constraints from other parts of the system server preventing
2915 // us from moving to the next state.
2916 if (DEBUG) {
2917 Slog.i(TAG, "Cannot step idle state. Blocked by: " + mConstraints.values().stream()
2918 .filter(x -> x.active)
2919 .map(x -> x.name)
2920 .collect(Collectors.joining(",")));
2921 }
2922 return;
2923 }
2924
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002925 switch (mState) {
2926 case STATE_INACTIVE:
2927 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002928 // for motion and sleep some more while doing so.
2929 startMonitoringMotionLocked();
Denny cy Leec5a7c292019-01-01 17:37:55 +08002930 long delay = mConstants.IDLE_AFTER_INACTIVE_TIMEOUT;
2931 if (shouldUseIdleTimeoutFactorLocked()) {
2932 delay = (long) (mPreIdleFactor * delay);
2933 }
2934 scheduleAlarmLocked(delay, false);
Robin Lee876b88542018-11-13 17:22:24 +01002935 moveToStateLocked(STATE_IDLE_PENDING, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002936 break;
2937 case STATE_IDLE_PENDING:
Robin Lee876b88542018-11-13 17:22:24 +01002938 moveToStateLocked(STATE_SENSING, reason);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002939 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002940 mLocated = false;
2941 mLastGenericLocation = null;
2942 mLastGpsLocation = null;
Robin Lee876b88542018-11-13 17:22:24 +01002943 updateActiveConstraintsLocked();
Robin Leec4d424c2018-12-07 15:09:13 +01002944
Robin Lee876b88542018-11-13 17:22:24 +01002945 // Wait for open constraints and an accelerometer reading before moving on.
Robin Leec4d424c2018-12-07 15:09:13 +01002946 if (mUseMotionSensor && mAnyMotionDetector.hasSensor()) {
2947 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
2948 mNotMoving = false;
2949 mAnyMotionDetector.checkForAnyMotion();
2950 break;
Robin Lee876b88542018-11-13 17:22:24 +01002951 } else if (mNumBlockingConstraints != 0) {
2952 cancelAlarmLocked();
2953 break;
Robin Leec4d424c2018-12-07 15:09:13 +01002954 }
2955
2956 mNotMoving = true;
2957 // Otherwise, fall through and check this off the list of requirements.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002958 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002959 cancelSensingTimeoutAlarmLocked();
Robin Lee876b88542018-11-13 17:22:24 +01002960 moveToStateLocked(STATE_LOCATING, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002961 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Kweku Adams799858b2018-10-08 17:19:08 -07002962 LocationManager locationManager = mInjector.getLocationManager();
2963 if (locationManager != null
2964 && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2965 locationManager.requestLocationUpdates(mLocationRequest,
Joe LaPenna23d681b2015-08-27 15:12:11 -07002966 mGenericLocationListener, mHandler.getLooper());
2967 mLocating = true;
2968 } else {
2969 mHasNetworkLocation = false;
2970 }
Kweku Adams799858b2018-10-08 17:19:08 -07002971 if (locationManager != null
2972 && locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002973 mHasGps = true;
Kweku Adams799858b2018-10-08 17:19:08 -07002974 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002975 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002976 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002977 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002978 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002979 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002980 // If we have a location provider, we're all set, the listeners will move state
2981 // forward.
2982 if (mLocating) {
2983 break;
2984 }
2985
2986 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002987 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002988 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002989 cancelLocatingLocked();
2990 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002991
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002992 // Intentional fallthrough -- time to go into IDLE state.
2993 case STATE_QUICK_DOZE_DELAY:
2994 // Reset the upcoming idle delays.
2995 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2996 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2997
2998 // Everything is in place to go into IDLE state.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002999 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003000 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003001 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
3002 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07003003 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003004 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Denny cy Leec5a7c292019-01-01 17:37:55 +08003005 mIdleStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07003006 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07003007 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
3008 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
3009 }
Robin Lee876b88542018-11-13 17:22:24 +01003010 moveToStateLocked(STATE_IDLE, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003011 if (mLightState != LIGHT_STATE_OVERRIDE) {
3012 mLightState = LIGHT_STATE_OVERRIDE;
3013 cancelLightAlarmLocked();
3014 }
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003015 addEvent(EVENT_DEEP_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08003016 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003017 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
3018 break;
3019 case STATE_IDLE:
3020 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003021 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003022 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003023 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003024 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
3025 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003026 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07003027 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
3028 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07003029 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
3030 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
3031 }
Robin Lee876b88542018-11-13 17:22:24 +01003032 moveToStateLocked(STATE_IDLE_MAINTENANCE, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003033 addEvent(EVENT_DEEP_MAINTENANCE, null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003034 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
3035 break;
3036 }
3037 }
3038
Robin Lee876b88542018-11-13 17:22:24 +01003039 private void moveToStateLocked(int state, String reason) {
3040 final int oldState = mState;
3041 mState = state;
3042 if (DEBUG) {
3043 Slog.d(TAG, String.format("Moved from STATE_%s to STATE_%s.",
3044 stateToString(oldState), stateToString(mState)));
3045 }
3046 EventLogTags.writeDeviceIdle(mState, reason);
3047 updateActiveConstraintsLocked();
3048 }
3049
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003050 void incActiveIdleOps() {
3051 synchronized (this) {
3052 mActiveIdleOpCount++;
3053 }
3054 }
3055
3056 void decActiveIdleOps() {
3057 synchronized (this) {
3058 mActiveIdleOpCount--;
3059 if (mActiveIdleOpCount <= 0) {
3060 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003061 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003062 }
3063 }
3064 }
3065
Kweku Adamsa457f4e2018-10-03 15:56:06 -07003066 /** Must only be used in tests. */
3067 @VisibleForTesting
3068 void setActiveIdleOpsForTest(int count) {
Kweku Adams799858b2018-10-08 17:19:08 -07003069 synchronized (this) {
3070 mActiveIdleOpCount = count;
3071 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07003072 }
3073
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003074 void setJobsActive(boolean active) {
3075 synchronized (this) {
3076 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08003077 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003078 if (!active) {
3079 exitMaintenanceEarlyIfNeededLocked();
3080 }
3081 }
3082 }
3083
3084 void setAlarmsActive(boolean active) {
3085 synchronized (this) {
3086 mAlarmsActive = active;
3087 if (!active) {
3088 exitMaintenanceEarlyIfNeededLocked();
3089 }
3090 }
3091 }
3092
Yao Chenca5edbb2016-01-13 14:44:36 -08003093 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
3094 synchronized (this) {
3095 mMaintenanceActivityListeners.register(listener);
3096 return mReportedMaintenanceActivity;
3097 }
3098 }
3099
3100 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
3101 synchronized (this) {
3102 mMaintenanceActivityListeners.unregister(listener);
3103 }
3104 }
3105
Denny cy Leec5a7c292019-01-01 17:37:55 +08003106 @VisibleForTesting
3107 int setPreIdleTimeoutMode(int mode) {
3108 return setPreIdleTimeoutFactor(getPreIdleTimeoutByMode(mode));
3109 }
3110
3111 @VisibleForTesting
3112 float getPreIdleTimeoutByMode(int mode) {
3113 switch (mode) {
3114 case PowerManager.PRE_IDLE_TIMEOUT_MODE_LONG: {
3115 return mConstants.PRE_IDLE_FACTOR_LONG;
3116 }
3117 case PowerManager.PRE_IDLE_TIMEOUT_MODE_SHORT: {
3118 return mConstants.PRE_IDLE_FACTOR_SHORT;
3119 }
3120 case PowerManager.PRE_IDLE_TIMEOUT_MODE_NORMAL: {
3121 return 1.0f;
3122 }
3123 default: {
3124 Slog.w(TAG, "Invalid time out factor mode: " + mode);
3125 return 1.0f;
3126 }
3127 }
3128 }
3129
3130 @VisibleForTesting
3131 float getPreIdleTimeoutFactor() {
3132 return mPreIdleFactor;
3133 }
3134
3135 @VisibleForTesting
3136 int setPreIdleTimeoutFactor(float ratio) {
3137 if (!mDeepEnabled) {
3138 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: Deep Idle disable");
3139 return SET_IDLE_FACTOR_RESULT_NOT_SUPPORT;
3140 } else if (ratio <= MIN_PRE_IDLE_FACTOR_CHANGE) {
3141 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: Invalid input");
3142 return SET_IDLE_FACTOR_RESULT_INVALID;
3143 } else if (Math.abs(ratio - mPreIdleFactor) < MIN_PRE_IDLE_FACTOR_CHANGE) {
3144 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: New factor same as previous factor");
3145 return SET_IDLE_FACTOR_RESULT_IGNORED;
3146 }
3147 synchronized (this) {
3148 mLastPreIdleFactor = mPreIdleFactor;
3149 mPreIdleFactor = ratio;
3150 }
3151 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: " + ratio);
3152 postUpdatePreIdleFactor();
3153 return SET_IDLE_FACTOR_RESULT_OK;
3154 }
3155
3156 @VisibleForTesting
3157 void resetPreIdleTimeoutMode() {
3158 synchronized (this) {
3159 mLastPreIdleFactor = mPreIdleFactor;
3160 mPreIdleFactor = 1.0f;
3161 }
3162 if (DEBUG) Slog.d(TAG, "resetPreIdleTimeoutMode to 1.0");
3163 postResetPreIdleTimeoutFactor();
3164 }
3165
3166 private void postUpdatePreIdleFactor() {
3167 mHandler.sendEmptyMessage(MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR);
3168 }
3169
3170 private void postResetPreIdleTimeoutFactor() {
3171 mHandler.sendEmptyMessage(MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR);
3172 }
3173
3174 @VisibleForTesting
3175 void updatePreIdleFactor() {
3176 synchronized (this) {
3177 if (!shouldUseIdleTimeoutFactorLocked()) {
3178 return;
3179 }
3180 if (mState == STATE_INACTIVE || mState == STATE_IDLE_PENDING) {
3181 if (mNextAlarmTime == 0) {
3182 return;
3183 }
3184 long delay = mNextAlarmTime - SystemClock.elapsedRealtime();
3185 if (delay < MIN_STATE_STEP_ALARM_CHANGE) {
3186 return;
3187 }
3188 long newDelay = (long) (delay / mLastPreIdleFactor * mPreIdleFactor);
3189 if (Math.abs(delay - newDelay) < MIN_STATE_STEP_ALARM_CHANGE) {
3190 return;
3191 }
3192 scheduleAlarmLocked(newDelay, false);
3193 }
3194 }
3195 }
3196
3197 @VisibleForTesting
3198 void maybeDoImmediateMaintenance() {
3199 synchronized (this) {
3200 if (mState == STATE_IDLE) {
3201 long duration = SystemClock.elapsedRealtime() - mIdleStartTime;
3202 /* Let's trgger a immediate maintenance,
3203 * if it has been idle for a long time */
3204 if (duration > mConstants.IDLE_TIMEOUT) {
3205 scheduleAlarmLocked(0, false);
3206 }
3207 }
3208 }
3209 }
3210
3211 private boolean shouldUseIdleTimeoutFactorLocked() {
3212 // exclude ACTIVE_REASON_MOTION, for exclude device in pocket case
3213 if (mActiveReason == ACTIVE_REASON_MOTION) {
3214 return false;
3215 }
3216 return true;
3217 }
3218
3219 /** Must only be used in tests. */
3220 @VisibleForTesting
3221 void setIdleStartTimeForTest(long idleStartTime) {
3222 synchronized (this) {
3223 mIdleStartTime = idleStartTime;
3224 }
3225 }
3226
Yao Chenca5edbb2016-01-13 14:44:36 -08003227 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07003228 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08003229 if (active == mReportedMaintenanceActivity) {
3230 return;
3231 }
3232 mReportedMaintenanceActivity = active;
3233 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
3234 mReportedMaintenanceActivity ? 1 : 0, 0);
3235 mHandler.sendMessage(msg);
3236 }
3237
Denny cy Leec5a7c292019-01-01 17:37:55 +08003238 @VisibleForTesting
3239 long getNextAlarmTime() {
3240 return mNextAlarmTime;
3241 }
3242
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003243 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07003244 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003245 }
3246
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003247 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003248 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
3249 || mLightState == LIGHT_STATE_PRE_IDLE) {
3250 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003251 final long now = SystemClock.elapsedRealtime();
3252 if (DEBUG) {
3253 StringBuilder sb = new StringBuilder();
3254 sb.append("Exit: start=");
3255 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
3256 sb.append(" now=");
3257 TimeUtils.formatDuration(now, sb);
3258 Slog.d(TAG, sb.toString());
3259 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003260 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003261 stepIdleStateLocked("s:early");
3262 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
3263 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003264 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003265 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003266 }
3267 }
3268 }
3269 }
3270
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003271 void motionLocked() {
3272 if (DEBUG) Slog.d(TAG, "motionLocked()");
3273 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003274 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
3275 }
3276
3277 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003278 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003279 // state to wait again for no motion. Note that we only monitor for motion
3280 // after moving out of the inactive state, so no need to worry about that.
Kweku Adamsb7ce1902019-01-30 10:55:34 -08003281 final boolean becomeInactive = mState != STATE_ACTIVE
3282 || mLightState == LIGHT_STATE_OVERRIDE;
3283 // We only want to change the IDLE state if it's OVERRIDE.
3284 becomeActiveLocked(type, Process.myUid(), timeout, mLightState == LIGHT_STATE_OVERRIDE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003285 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003286 becomeInactiveIfAppropriateLocked();
3287 }
3288 }
3289
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003290 void receivedGenericLocationLocked(Location location) {
3291 if (mState != STATE_LOCATING) {
3292 cancelLocatingLocked();
3293 return;
3294 }
3295 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
3296 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003297 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003298 return;
3299 }
3300 mLocated = true;
3301 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003302 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003303 }
3304 }
3305
3306 void receivedGpsLocationLocked(Location location) {
3307 if (mState != STATE_LOCATING) {
3308 cancelLocatingLocked();
3309 return;
3310 }
3311 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
3312 mLastGpsLocation = new Location(location);
3313 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
3314 return;
3315 }
3316 mLocated = true;
3317 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003318 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003319 }
3320 }
3321
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003322 void startMonitoringMotionLocked() {
3323 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
3324 if (mMotionSensor != null && !mMotionListener.active) {
3325 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003326 }
3327 }
3328
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003329 void stopMonitoringMotionLocked() {
3330 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
3331 if (mMotionSensor != null && mMotionListener.active) {
3332 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003333 }
3334 }
3335
3336 void cancelAlarmLocked() {
3337 if (mNextAlarmTime != 0) {
3338 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003339 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003340 }
3341 }
3342
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003343 void cancelLightAlarmLocked() {
3344 if (mNextLightAlarmTime != 0) {
3345 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003346 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003347 }
3348 }
3349
3350 void cancelLocatingLocked() {
3351 if (mLocating) {
Kweku Adams799858b2018-10-08 17:19:08 -07003352 LocationManager locationManager = mInjector.getLocationManager();
3353 locationManager.removeUpdates(mGenericLocationListener);
3354 locationManager.removeUpdates(mGpsLocationListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003355 mLocating = false;
3356 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003357 }
3358
Kevin Gabayan92f15e62016-04-04 17:52:22 -07003359 void cancelSensingTimeoutAlarmLocked() {
3360 if (mNextSensingTimeoutAlarmTime != 0) {
3361 mNextSensingTimeoutAlarmTime = 0;
3362 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
3363 }
3364 }
3365
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003366 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kweku Adamsbf277862019-07-19 15:20:44 -07003367 scheduleAlarmLocked(delay, idleUntil, true);
3368 }
3369
3370 private void scheduleAlarmLocked(long delay, boolean idleUntil, boolean useWakeupAlarm) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003371 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Robin Leec4d424c2018-12-07 15:09:13 +01003372
3373 if (mUseMotionSensor && mMotionSensor == null
3374 && mState != STATE_QUICK_DOZE_DELAY
3375 && mState != STATE_IDLE
3376 && mState != STATE_IDLE_MAINTENANCE) {
3377 // If there is no motion sensor on this device, but we need one, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003378 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07003379 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003380 // manually poke it by pretending like the alarm is going off.
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003381 // STATE_QUICK_DOZE_DELAY skips the motion sensing so if the state is past the motion
3382 // sensing stage (ie, is QUICK_DOZE_DELAY, IDLE, or IDLE_MAINTENANCE), then idling
3383 // can continue until the user interacts with the device.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003384 return;
3385 }
Kweku Adamsbf277862019-07-19 15:20:44 -07003386 final int alarmType = useWakeupAlarm
3387 ? AlarmManager.ELAPSED_REALTIME_WAKEUP : AlarmManager.ELAPSED_REALTIME;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003388 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
3389 if (idleUntil) {
Kweku Adamsbf277862019-07-19 15:20:44 -07003390 mAlarmManager.setIdleUntil(alarmType,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003391 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003392 } else {
Kweku Adamsbf277862019-07-19 15:20:44 -07003393 mAlarmManager.set(alarmType,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003394 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003395 }
3396 }
3397
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003398 void scheduleLightAlarmLocked(long delay) {
3399 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003400 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003401 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003402 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003403 }
3404
Kevin Gabayan92f15e62016-04-04 17:52:22 -07003405 void scheduleSensingTimeoutAlarmLocked(long delay) {
3406 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
3407 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
3408 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
3409 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
3410 }
3411
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003412 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
3413 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
3414 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003415 if (systemApps != null) {
3416 for (int i = 0; i < systemApps.size(); i++) {
3417 outAppIds.put(systemApps.valueAt(i), true);
3418 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003419 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003420 if (userApps != null) {
3421 for (int i = 0; i < userApps.size(); i++) {
3422 outAppIds.put(userApps.valueAt(i), true);
3423 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003424 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003425 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003426 int[] appids = new int[size];
3427 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003428 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003429 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003430 return appids;
3431 }
3432
3433 private void updateWhitelistAppIdsLocked() {
3434 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
3435 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
3436 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
3437 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003438 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
3439 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003440 if (mLocalActivityManager != null) {
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07003441 mLocalActivityManager.setDeviceIdleWhitelist(
3442 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003443 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003444 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003445 if (DEBUG) {
3446 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003447 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003448 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003449 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003450 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003451 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003452 }
3453
Dianne Hackborn85e35642017-01-12 15:10:57 -08003454 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003455 final int size = mTempWhitelistAppIdEndTimes.size();
3456 if (mTempWhitelistAppIdArray.length != size) {
3457 mTempWhitelistAppIdArray = new int[size];
3458 }
3459 for (int i = 0; i < size; i++) {
3460 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
3461 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08003462 if (mLocalActivityManager != null) {
3463 if (DEBUG) {
3464 Slog.d(TAG, "Setting activity manager temp whitelist to "
3465 + Arrays.toString(mTempWhitelistAppIdArray));
3466 }
3467 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
3468 adding);
3469 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003470 if (mLocalPowerManager != null) {
3471 if (DEBUG) {
3472 Slog.d(TAG, "Setting wakelock temp whitelist to "
3473 + Arrays.toString(mTempWhitelistAppIdArray));
3474 }
3475 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
3476 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003477 passWhiteListsToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003478 }
3479
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003480 private void reportPowerSaveWhitelistChangedLocked() {
3481 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
3482 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003483 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003484 }
3485
3486 private void reportTempWhitelistChangedLocked() {
3487 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
3488 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003489 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003490 }
3491
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003492 private void passWhiteListsToForceAppStandbyTrackerLocked() {
Makoto Onukie4918212018-02-06 11:30:15 -08003493 mAppStateTracker.setPowerSaveWhitelistAppIds(
Makoto Onuki71755c92018-01-16 14:15:44 -08003494 mPowerSaveWhitelistExceptIdleAppIdArray,
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003495 mPowerSaveWhitelistUserAppIdArray,
Makoto Onuki2206af32017-11-21 16:25:35 -08003496 mTempWhitelistAppIdArray);
3497 }
3498
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003499 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003500 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003501 mPowerSaveWhitelistUserApps.clear();
3502 FileInputStream stream;
3503 try {
3504 stream = mConfigFile.openRead();
3505 } catch (FileNotFoundException e) {
3506 return;
3507 }
3508 try {
3509 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003510 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003511 readConfigFileLocked(parser);
3512 } catch (XmlPullParserException e) {
3513 } finally {
3514 try {
3515 stream.close();
3516 } catch (IOException e) {
3517 }
3518 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003519 }
3520
3521 private void readConfigFileLocked(XmlPullParser parser) {
3522 final PackageManager pm = getContext().getPackageManager();
3523
3524 try {
3525 int type;
3526 while ((type = parser.next()) != XmlPullParser.START_TAG
3527 && type != XmlPullParser.END_DOCUMENT) {
3528 ;
3529 }
3530
3531 if (type != XmlPullParser.START_TAG) {
3532 throw new IllegalStateException("no start tag found");
3533 }
3534
3535 int outerDepth = parser.getDepth();
3536 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3537 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3538 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3539 continue;
3540 }
3541
3542 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07003543 switch (tagName) {
3544 case "wl":
3545 String name = parser.getAttributeValue(null, "n");
3546 if (name != null) {
3547 try {
3548 ApplicationInfo ai = pm.getApplicationInfo(name,
3549 PackageManager.MATCH_ANY_USER);
3550 mPowerSaveWhitelistUserApps.put(ai.packageName,
3551 UserHandle.getAppId(ai.uid));
3552 } catch (PackageManager.NameNotFoundException e) {
3553 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003554 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003555 break;
3556 case "un-wl":
3557 final String packageName = parser.getAttributeValue(null, "n");
3558 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
3559 mRemovedFromSystemWhitelistApps.put(packageName,
3560 mPowerSaveWhitelistApps.remove(packageName));
3561 }
3562 break;
3563 default:
3564 Slog.w(TAG, "Unknown element under <config>: "
3565 + parser.getName());
3566 XmlUtils.skipCurrentTag(parser);
3567 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003568 }
3569 }
3570
3571 } catch (IllegalStateException e) {
3572 Slog.w(TAG, "Failed parsing config " + e);
3573 } catch (NullPointerException e) {
3574 Slog.w(TAG, "Failed parsing config " + e);
3575 } catch (NumberFormatException e) {
3576 Slog.w(TAG, "Failed parsing config " + e);
3577 } catch (XmlPullParserException e) {
3578 Slog.w(TAG, "Failed parsing config " + e);
3579 } catch (IOException e) {
3580 Slog.w(TAG, "Failed parsing config " + e);
3581 } catch (IndexOutOfBoundsException e) {
3582 Slog.w(TAG, "Failed parsing config " + e);
3583 }
3584 }
3585
3586 void writeConfigFileLocked() {
3587 mHandler.removeMessages(MSG_WRITE_CONFIG);
3588 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
3589 }
3590
3591 void handleWriteConfigFile() {
3592 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
3593
3594 try {
3595 synchronized (this) {
3596 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003597 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003598 writeConfigFileLocked(out);
3599 }
3600 } catch (IOException e) {
3601 }
3602
3603 synchronized (mConfigFile) {
3604 FileOutputStream stream = null;
3605 try {
3606 stream = mConfigFile.startWrite();
3607 memStream.writeTo(stream);
3608 stream.flush();
3609 FileUtils.sync(stream);
3610 stream.close();
3611 mConfigFile.finishWrite(stream);
3612 } catch (IOException e) {
3613 Slog.w(TAG, "Error writing config file", e);
3614 mConfigFile.failWrite(stream);
3615 }
3616 }
3617 }
3618
3619 void writeConfigFileLocked(XmlSerializer out) throws IOException {
3620 out.startDocument(null, true);
3621 out.startTag(null, "config");
3622 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
3623 String name = mPowerSaveWhitelistUserApps.keyAt(i);
3624 out.startTag(null, "wl");
3625 out.attribute(null, "n", name);
3626 out.endTag(null, "wl");
3627 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003628 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
3629 out.startTag(null, "un-wl");
3630 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
3631 out.endTag(null, "un-wl");
3632 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003633 out.endTag(null, "config");
3634 out.endDocument();
3635 }
3636
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003637 static void dumpHelp(PrintWriter pw) {
3638 pw.println("Device idle controller (deviceidle) commands:");
3639 pw.println(" help");
3640 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003641 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003642 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003643 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003644 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003645 pw.println(" force-inactive");
3646 pw.println(" Force to be inactive, ready to freely step idle states.");
3647 pw.println(" unforce");
3648 pw.println(" Resume normal functioning after force-idle or force-inactive.");
3649 pw.println(" get [light|deep|force|screen|charging|network]");
3650 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003651 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003652 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003653 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003654 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003655 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07003656 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07003657 pw.println(" whitelist");
3658 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07003659 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003660 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07003661 pw.println(" sys-whitelist [package ...|reset]");
3662 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
3663 + " to put it back in the system whitelist.");
3664 pw.println(" Note that only packages that were"
3665 + " earlier removed from the system whitelist can be added back.");
3666 pw.println(" reset will reset the whitelist to the original state");
3667 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003668 pw.println(" except-idle-whitelist [package ...|reset]");
3669 pw.println(" Prefix the package with '+' to add it to whitelist or "
3670 + "'=' to check if it is already whitelisted");
3671 pw.println(" [reset] will reset the whitelist to it's original state");
3672 pw.println(" Note that unlike <whitelist> cmd, "
3673 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003674 pw.println(" tempwhitelist");
3675 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003676 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
3677 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08003678 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003679 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
3680 + "and any [-d] is ignored");
Amith Yamasani4cb42572018-04-27 10:02:57 -07003681 pw.println(" motion");
3682 pw.println(" Simulate a motion event to bring the device out of deep doze");
Denny cy Leec5a7c292019-01-01 17:37:55 +08003683 pw.println(" pre-idle-factor [0|1|2]");
3684 pw.println(" Set a new factor to idle time before step to idle"
3685 + "(inactive_to and idle_after_inactive_to)");
3686 pw.println(" reset-pre-idle-factor");
3687 pw.println(" Reset factor to idle time to default");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003688 }
3689
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003690 class Shell extends ShellCommand {
3691 int userId = UserHandle.USER_SYSTEM;
3692
3693 @Override
3694 public int onCommand(String cmd) {
3695 return onShellCommand(this, cmd);
3696 }
3697
3698 @Override
3699 public void onHelp() {
3700 PrintWriter pw = getOutPrintWriter();
3701 dumpHelp(pw);
3702 }
3703 }
3704
3705 int onShellCommand(Shell shell, String cmd) {
3706 PrintWriter pw = shell.getOutPrintWriter();
3707 if ("step".equals(cmd)) {
3708 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3709 null);
3710 synchronized (this) {
3711 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003712 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003713 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003714 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003715 stepIdleStateLocked("s:shell");
3716 pw.print("Stepped to deep: ");
3717 pw.println(stateToString(mState));
3718 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003719 stepLightIdleStateLocked("s:shell");
3720 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
3721 } else {
3722 pw.println("Unknown idle mode: " + arg);
3723 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003724 } finally {
3725 Binder.restoreCallingIdentity(token);
3726 }
3727 }
3728 } else if ("force-idle".equals(cmd)) {
3729 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3730 null);
3731 synchronized (this) {
3732 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07003733 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003734 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07003735 if (arg == null || "deep".equals(arg)) {
3736 if (!mDeepEnabled) {
3737 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003738 return -1;
3739 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003740 mForceIdle = true;
3741 becomeInactiveIfAppropriateLocked();
3742 int curState = mState;
3743 while (curState != STATE_IDLE) {
3744 stepIdleStateLocked("s:shell");
3745 if (curState == mState) {
3746 pw.print("Unable to go deep idle; stopped at ");
3747 pw.println(stateToString(mState));
3748 exitForceIdleLocked();
3749 return -1;
3750 }
3751 curState = mState;
3752 }
3753 pw.println("Now forced in to deep idle mode");
3754 } else if ("light".equals(arg)) {
3755 mForceIdle = true;
3756 becomeInactiveIfAppropriateLocked();
3757 int curLightState = mLightState;
3758 while (curLightState != LIGHT_STATE_IDLE) {
Tej Singh93cf3e32017-12-07 13:05:38 -08003759 stepLightIdleStateLocked("s:shell");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003760 if (curLightState == mLightState) {
3761 pw.print("Unable to go light idle; stopped at ");
3762 pw.println(lightStateToString(mLightState));
3763 exitForceIdleLocked();
3764 return -1;
3765 }
3766 curLightState = mLightState;
3767 }
3768 pw.println("Now forced in to light idle mode");
3769 } else {
3770 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003771 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003772 } finally {
3773 Binder.restoreCallingIdentity(token);
3774 }
3775 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003776 } else if ("force-inactive".equals(cmd)) {
3777 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3778 null);
3779 synchronized (this) {
3780 long token = Binder.clearCallingIdentity();
3781 try {
3782 mForceIdle = true;
3783 becomeInactiveIfAppropriateLocked();
3784 pw.print("Light state: ");
3785 pw.print(lightStateToString(mLightState));
3786 pw.print(", deep state: ");
3787 pw.println(stateToString(mState));
3788 } finally {
3789 Binder.restoreCallingIdentity(token);
3790 }
3791 }
3792 } else if ("unforce".equals(cmd)) {
3793 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3794 null);
3795 synchronized (this) {
3796 long token = Binder.clearCallingIdentity();
3797 try {
3798 exitForceIdleLocked();
3799 pw.print("Light state: ");
3800 pw.print(lightStateToString(mLightState));
3801 pw.print(", deep state: ");
3802 pw.println(stateToString(mState));
3803 } finally {
3804 Binder.restoreCallingIdentity(token);
3805 }
3806 }
3807 } else if ("get".equals(cmd)) {
3808 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3809 null);
3810 synchronized (this) {
3811 String arg = shell.getNextArg();
3812 if (arg != null) {
3813 long token = Binder.clearCallingIdentity();
3814 try {
3815 switch (arg) {
3816 case "light": pw.println(lightStateToString(mLightState)); break;
3817 case "deep": pw.println(stateToString(mState)); break;
3818 case "force": pw.println(mForceIdle); break;
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003819 case "quick": pw.println(mQuickDozeActivated); break;
Dianne Hackborn88c41352016-04-07 15:18:58 -07003820 case "screen": pw.println(mScreenOn); break;
3821 case "charging": pw.println(mCharging); break;
3822 case "network": pw.println(mNetworkConnected); break;
3823 default: pw.println("Unknown get option: " + arg); break;
3824 }
3825 } finally {
3826 Binder.restoreCallingIdentity(token);
3827 }
3828 } else {
3829 pw.println("Argument required");
3830 }
3831 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003832 } else if ("disable".equals(cmd)) {
3833 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3834 null);
3835 synchronized (this) {
3836 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003837 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003838 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003839 boolean becomeActive = false;
3840 boolean valid = false;
3841 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3842 valid = true;
3843 if (mDeepEnabled) {
3844 mDeepEnabled = false;
3845 becomeActive = true;
3846 pw.println("Deep idle mode disabled");
3847 }
3848 }
3849 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3850 valid = true;
3851 if (mLightEnabled) {
3852 mLightEnabled = false;
3853 becomeActive = true;
3854 pw.println("Light idle mode disabled");
3855 }
3856 }
3857 if (becomeActive) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08003858 mActiveReason = ACTIVE_REASON_FORCED;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003859 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
3860 Process.myUid());
3861 }
3862 if (!valid) {
3863 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003864 }
3865 } finally {
3866 Binder.restoreCallingIdentity(token);
3867 }
3868 }
3869 } else if ("enable".equals(cmd)) {
3870 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3871 null);
3872 synchronized (this) {
3873 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003874 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003875 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003876 boolean becomeInactive = false;
3877 boolean valid = false;
3878 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3879 valid = true;
3880 if (!mDeepEnabled) {
3881 mDeepEnabled = true;
3882 becomeInactive = true;
3883 pw.println("Deep idle mode enabled");
3884 }
3885 }
3886 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3887 valid = true;
3888 if (!mLightEnabled) {
3889 mLightEnabled = true;
3890 becomeInactive = true;
3891 pw.println("Light idle mode enable");
3892 }
3893 }
3894 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003895 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003896 }
3897 if (!valid) {
3898 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003899 }
3900 } finally {
3901 Binder.restoreCallingIdentity(token);
3902 }
3903 }
3904 } else if ("enabled".equals(cmd)) {
3905 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003906 String arg = shell.getNextArg();
3907 if (arg == null || "all".equals(arg)) {
3908 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
3909 } else if ("deep".equals(arg)) {
3910 pw.println(mDeepEnabled ? "1" : 0);
3911 } else if ("light".equals(arg)) {
3912 pw.println(mLightEnabled ? "1" : 0);
3913 } else {
3914 pw.println("Unknown idle mode: " + arg);
3915 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003916 }
3917 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07003918 String arg = shell.getNextArg();
3919 if (arg != null) {
3920 getContext().enforceCallingOrSelfPermission(
3921 android.Manifest.permission.DEVICE_POWER, null);
3922 long token = Binder.clearCallingIdentity();
3923 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003924 do {
3925 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08003926 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3927 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003928 return -1;
3929 }
3930 char op = arg.charAt(0);
3931 String pkg = arg.substring(1);
3932 if (op == '+') {
3933 if (addPowerSaveWhitelistAppInternal(pkg)) {
3934 pw.println("Added: " + pkg);
3935 } else {
3936 pw.println("Unknown package: " + pkg);
3937 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003938 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003939 if (removePowerSaveWhitelistAppInternal(pkg)) {
3940 pw.println("Removed: " + pkg);
3941 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003942 } else {
3943 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003944 }
3945 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003946 } finally {
3947 Binder.restoreCallingIdentity(token);
3948 }
3949 } else {
3950 synchronized (this) {
3951 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3952 pw.print("system-excidle,");
3953 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3954 pw.print(",");
3955 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3956 }
3957 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3958 pw.print("system,");
3959 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3960 pw.print(",");
3961 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3962 }
3963 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3964 pw.print("user,");
3965 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3966 pw.print(",");
3967 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003968 }
3969 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003970 }
3971 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003972 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003973 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003974 String opt;
3975 while ((opt=shell.getNextOption()) != null) {
3976 if ("-u".equals(opt)) {
3977 opt = shell.getNextArg();
3978 if (opt == null) {
3979 pw.println("-u requires a user number");
3980 return -1;
3981 }
3982 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003983 } else if ("-d".equals(opt)) {
3984 opt = shell.getNextArg();
3985 if (opt == null) {
3986 pw.println("-d requires a duration");
3987 return -1;
3988 }
3989 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003990 } else if ("-r".equals(opt)) {
3991 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003992 }
3993 }
3994 String arg = shell.getNextArg();
3995 if (arg != null) {
3996 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003997 if (removePkg) {
3998 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3999 } else {
4000 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
4001 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07004002 } catch (Exception e) {
4003 pw.println("Failed: " + e);
4004 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004005 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08004006 } else if (removePkg) {
4007 pw.println("[-r] requires a package name");
4008 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004009 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004010 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004011 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07004012 } else if ("except-idle-whitelist".equals(cmd)) {
4013 getContext().enforceCallingOrSelfPermission(
4014 android.Manifest.permission.DEVICE_POWER, null);
4015 final long token = Binder.clearCallingIdentity();
4016 try {
4017 String arg = shell.getNextArg();
4018 if (arg == null) {
4019 pw.println("No arguments given");
4020 return -1;
4021 } else if ("reset".equals(arg)) {
4022 resetPowerSaveWhitelistExceptIdleInternal();
4023 } else {
4024 do {
4025 if (arg.length() < 1 || (arg.charAt(0) != '-'
4026 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
4027 pw.println("Package must be prefixed with +, -, or =: " + arg);
4028 return -1;
4029 }
4030 char op = arg.charAt(0);
4031 String pkg = arg.substring(1);
4032 if (op == '+') {
4033 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
4034 pw.println("Added: " + pkg);
4035 } else {
4036 pw.println("Unknown package: " + pkg);
4037 }
4038 } else if (op == '=') {
4039 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
4040 } else {
4041 pw.println("Unknown argument: " + arg);
4042 return -1;
4043 }
4044 } while ((arg = shell.getNextArg()) != null);
4045 }
4046 } finally {
4047 Binder.restoreCallingIdentity(token);
4048 }
Suprabh Shukla08105642017-09-26 14:45:30 -07004049 } else if ("sys-whitelist".equals(cmd)) {
4050 String arg = shell.getNextArg();
4051 if (arg != null) {
4052 getContext().enforceCallingOrSelfPermission(
4053 android.Manifest.permission.DEVICE_POWER, null);
4054 final long token = Binder.clearCallingIdentity();
4055 try {
4056 if ("reset".equals(arg)) {
4057 resetSystemPowerWhitelistInternal();
4058 } else {
4059 do {
4060 if (arg.length() < 1
4061 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
4062 pw.println("Package must be prefixed with + or - " + arg);
4063 return -1;
4064 }
4065 final char op = arg.charAt(0);
4066 final String pkg = arg.substring(1);
4067 switch (op) {
4068 case '+':
4069 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
4070 pw.println("Restored " + pkg);
4071 }
4072 break;
4073 case '-':
4074 if (removeSystemPowerWhitelistAppInternal(pkg)) {
4075 pw.println("Removed " + pkg);
4076 }
4077 break;
4078 }
4079 } while ((arg = shell.getNextArg()) != null);
4080 }
4081 } finally {
4082 Binder.restoreCallingIdentity(token);
4083 }
4084 } else {
4085 synchronized (this) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07004086 for (int j = 0; j < mPowerSaveWhitelistApps.size(); j++) {
Suprabh Shukla08105642017-09-26 14:45:30 -07004087 pw.print(mPowerSaveWhitelistApps.keyAt(j));
4088 pw.print(",");
4089 pw.println(mPowerSaveWhitelistApps.valueAt(j));
4090 }
4091 }
4092 }
Amith Yamasani4cb42572018-04-27 10:02:57 -07004093 } else if ("motion".equals(cmd)) {
4094 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4095 null);
4096 synchronized (this) {
4097 long token = Binder.clearCallingIdentity();
4098 try {
4099 motionLocked();
4100 pw.print("Light state: ");
4101 pw.print(lightStateToString(mLightState));
4102 pw.print(", deep state: ");
4103 pw.println(stateToString(mState));
4104 } finally {
4105 Binder.restoreCallingIdentity(token);
4106 }
4107 }
Denny cy Leec5a7c292019-01-01 17:37:55 +08004108 } else if ("pre-idle-factor".equals(cmd)) {
4109 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4110 null);
4111 synchronized (this) {
4112 long token = Binder.clearCallingIdentity();
4113 int ret = SET_IDLE_FACTOR_RESULT_UNINIT;
4114 try {
4115 String arg = shell.getNextArg();
4116 boolean valid = false;
4117 int mode = 0;
4118 if (arg != null) {
4119 mode = Integer.parseInt(arg);
4120 ret = setPreIdleTimeoutMode(mode);
4121 if (ret == SET_IDLE_FACTOR_RESULT_OK) {
4122 pw.println("pre-idle-factor: " + mode);
4123 valid = true;
4124 } else if (ret == SET_IDLE_FACTOR_RESULT_NOT_SUPPORT) {
4125 valid = true;
4126 pw.println("Deep idle not supported");
4127 } else if (ret == SET_IDLE_FACTOR_RESULT_IGNORED) {
4128 valid = true;
4129 pw.println("Idle timeout factor not changed");
4130 }
4131 }
4132 if (!valid) {
4133 pw.println("Unknown idle timeout factor: " + arg
4134 + ",(error code: " + ret + ")");
4135 }
4136 } catch (NumberFormatException e) {
4137 pw.println("Unknown idle timeout factor"
4138 + ",(error code: " + ret + ")");
4139 } finally {
4140 Binder.restoreCallingIdentity(token);
4141 }
4142 }
4143 } else if ("reset-pre-idle-factor".equals(cmd)) {
4144 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4145 null);
4146 synchronized (this) {
4147 long token = Binder.clearCallingIdentity();
4148 try {
4149 resetPreIdleTimeoutMode();
4150 } finally {
4151 Binder.restoreCallingIdentity(token);
4152 }
4153 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004154 } else {
4155 return shell.handleDefaultCommands(cmd);
4156 }
4157 return 0;
4158 }
4159
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004160 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004161 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004162
4163 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07004164 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004165 for (int i=0; i<args.length; i++) {
4166 String arg = args[i];
4167 if ("-h".equals(arg)) {
4168 dumpHelp(pw);
4169 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004170 } else if ("-u".equals(arg)) {
4171 i++;
4172 if (i < args.length) {
4173 arg = args[i];
4174 userId = Integer.parseInt(arg);
4175 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004176 } else if ("-a".equals(arg)) {
4177 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004178 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
4179 pw.println("Unknown option: " + arg);
4180 return;
4181 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004182 Shell shell = new Shell();
4183 shell.userId = userId;
4184 String[] newArgs = new String[args.length-i];
4185 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07004186 shell.exec(mBinderService, null, fd, null, newArgs, null,
4187 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004188 return;
4189 }
4190 }
4191 }
4192
4193 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07004194 mConstants.dump(pw);
4195
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004196 if (mEventCmds[0] != EVENT_NULL) {
4197 pw.println(" Idling history:");
4198 long now = SystemClock.elapsedRealtime();
4199 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
4200 int cmd = mEventCmds[i];
4201 if (cmd == EVENT_NULL) {
4202 continue;
4203 }
4204 String label;
4205 switch (mEventCmds[i]) {
4206 case EVENT_NORMAL: label = " normal"; break;
4207 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
4208 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08004209 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
4210 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004211 default: label = " ??"; break;
4212 }
4213 pw.print(" ");
4214 pw.print(label);
4215 pw.print(": ");
Amith Yamasaniac6517a2018-04-23 12:19:34 -07004216 TimeUtils.formatDuration(mEventTimes[i], now, pw);
4217 if (mEventReasons[i] != null) {
4218 pw.print(" (");
4219 pw.print(mEventReasons[i]);
4220 pw.print(")");
4221 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004222 pw.println();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07004223
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004224 }
4225 }
4226
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004227 int size = mPowerSaveWhitelistAppsExceptIdle.size();
4228 if (size > 0) {
4229 pw.println(" Whitelist (except idle) system apps:");
4230 for (int i = 0; i < size; i++) {
4231 pw.print(" ");
4232 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
4233 }
4234 }
4235 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004236 if (size > 0) {
4237 pw.println(" Whitelist system apps:");
4238 for (int i = 0; i < size; i++) {
4239 pw.print(" ");
4240 pw.println(mPowerSaveWhitelistApps.keyAt(i));
4241 }
4242 }
Suprabh Shukla08105642017-09-26 14:45:30 -07004243 size = mRemovedFromSystemWhitelistApps.size();
4244 if (size > 0) {
4245 pw.println(" Removed from whitelist system apps:");
4246 for (int i = 0; i < size; i++) {
4247 pw.print(" ");
4248 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
4249 }
4250 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004251 size = mPowerSaveWhitelistUserApps.size();
4252 if (size > 0) {
4253 pw.println(" Whitelist user apps:");
4254 for (int i = 0; i < size; i++) {
4255 pw.print(" ");
4256 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
4257 }
4258 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004259 size = mPowerSaveWhitelistExceptIdleAppIds.size();
4260 if (size > 0) {
4261 pw.println(" Whitelist (except idle) all app ids:");
4262 for (int i = 0; i < size; i++) {
4263 pw.print(" ");
4264 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
4265 pw.println();
4266 }
4267 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08004268 size = mPowerSaveWhitelistUserAppIds.size();
4269 if (size > 0) {
4270 pw.println(" Whitelist user app ids:");
4271 for (int i = 0; i < size; i++) {
4272 pw.print(" ");
4273 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
4274 pw.println();
4275 }
4276 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07004277 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004278 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07004279 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004280 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07004281 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07004282 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004283 pw.println();
4284 }
4285 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004286 dumpTempWhitelistSchedule(pw, true);
4287
Dianne Hackborna750a632015-06-16 17:18:23 -07004288 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
4289 if (size > 0) {
4290 pw.println(" Temp whitelist app ids:");
4291 for (int i = 0; i < size; i++) {
4292 pw.print(" ");
4293 pw.print(mTempWhitelistAppIdArray[i]);
4294 pw.println();
4295 }
4296 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07004297
Dianne Hackbornb6843652016-02-22 12:20:13 -08004298 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004299 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004300 pw.print(" mForceIdle="); pw.println(mForceIdle);
Robin Leec4d424c2018-12-07 15:09:13 +01004301 pw.print(" mUseMotionSensor="); pw.print(mUseMotionSensor);
4302 if (mUseMotionSensor) {
4303 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
4304 } else {
4305 pw.println();
4306 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004307 pw.print(" mScreenOn="); pw.println(mScreenOn);
Amith Yamasani396a10c2018-01-19 10:58:07 -08004308 pw.print(" mScreenLocked="); pw.println(mScreenLocked);
Dianne Hackborn88c41352016-04-07 15:18:58 -07004309 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004310 pw.print(" mCharging="); pw.println(mCharging);
Robin Lee876b88542018-11-13 17:22:24 +01004311 if (mConstraints.size() != 0) {
4312 pw.println(" mConstraints={");
4313 for (int i = 0; i < mConstraints.size(); i++) {
4314 final DeviceIdleConstraintTracker tracker = mConstraints.valueAt(i);
4315 pw.print(" \""); pw.print(tracker.name); pw.print("\"=");
4316 if (tracker.minState == mState) {
4317 pw.println(tracker.active);
4318 } else {
4319 pw.print("ignored <mMinState="); pw.print(stateToString(tracker.minState));
4320 pw.println(">");
4321 }
4322 }
4323 pw.println(" }");
4324 }
Robin Leec4d424c2018-12-07 15:09:13 +01004325 if (mUseMotionSensor) {
Robin Lee876b88542018-11-13 17:22:24 +01004326 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Robin Leec4d424c2018-12-07 15:09:13 +01004327 pw.print(" mNotMoving="); pw.println(mNotMoving);
4328 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07004329 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
4330 pw.print(mHasGps); pw.print(" mHasNetwork=");
4331 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07004332 if (mLastGenericLocation != null) {
4333 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
4334 }
4335 if (mLastGpsLocation != null) {
4336 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
4337 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004338 pw.print(" mState="); pw.print(stateToString(mState));
4339 pw.print(" mLightState=");
4340 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004341 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
4342 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004343 if (mActiveIdleOpCount != 0) {
4344 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
4345 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004346 if (mNextAlarmTime != 0) {
4347 pw.print(" mNextAlarmTime=");
4348 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
4349 pw.println();
4350 }
4351 if (mNextIdlePendingDelay != 0) {
4352 pw.print(" mNextIdlePendingDelay=");
4353 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
4354 pw.println();
4355 }
4356 if (mNextIdleDelay != 0) {
4357 pw.print(" mNextIdleDelay=");
4358 TimeUtils.formatDuration(mNextIdleDelay, pw);
4359 pw.println();
4360 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07004361 if (mNextLightIdleDelay != 0) {
4362 pw.print(" mNextIdleDelay=");
4363 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
4364 pw.println();
4365 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004366 if (mNextLightAlarmTime != 0) {
4367 pw.print(" mNextLightAlarmTime=");
4368 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
4369 pw.println();
4370 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004371 if (mCurIdleBudget != 0) {
4372 pw.print(" mCurIdleBudget=");
4373 TimeUtils.formatDuration(mCurIdleBudget, pw);
4374 pw.println();
4375 }
4376 if (mMaintenanceStartTime != 0) {
4377 pw.print(" mMaintenanceStartTime=");
4378 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
4379 pw.println();
4380 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004381 if (mJobsActive) {
4382 pw.print(" mJobsActive="); pw.println(mJobsActive);
4383 }
4384 if (mAlarmsActive) {
4385 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
4386 }
Denny cy Leec5a7c292019-01-01 17:37:55 +08004387 if (Math.abs(mPreIdleFactor - 1.0f) > MIN_PRE_IDLE_FACTOR_CHANGE) {
4388 pw.print(" mPreIdleFactor="); pw.println(mPreIdleFactor);
4389 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004390 }
4391 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004392
4393 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
4394 final int size = mTempWhitelistAppIdEndTimes.size();
4395 if (size > 0) {
4396 String prefix = "";
4397 if (printTitle) {
4398 pw.println(" Temp whitelist schedule:");
4399 prefix = " ";
4400 }
4401 final long timeNow = SystemClock.elapsedRealtime();
4402 for (int i = 0; i < size; i++) {
4403 pw.print(prefix);
4404 pw.print("UID=");
4405 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
4406 pw.print(": ");
4407 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
4408 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
4409 pw.print(" - ");
4410 pw.println(entry.second);
4411 }
4412 }
4413 }
4414 }