blob: 52a4218238e7be0b069523d86b6892e9ede28296 [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.
2740 scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
2741 EventLogTags.writeDeviceIdle(mState, "no activity");
2742 } else if (mState == STATE_ACTIVE) {
2743 mState = STATE_INACTIVE;
2744 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2745 resetIdleManagementLocked();
2746 long delay = mInactiveTimeout;
2747 if (shouldUseIdleTimeoutFactorLocked()) {
2748 delay = (long) (mPreIdleFactor * delay);
2749 }
2750 scheduleAlarmLocked(delay, false);
2751 EventLogTags.writeDeviceIdle(mState, "no activity");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002752 }
Kweku Adamsb7ce1902019-01-30 10:55:34 -08002753 }
2754 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
2755 mLightState = LIGHT_STATE_INACTIVE;
2756 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2757 resetLightIdleManagementLocked();
2758 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
2759 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002760 }
2761 }
2762
Kweku Adams00e3a372018-09-28 16:57:09 -07002763 private void resetIdleManagementLocked() {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002764 mNextIdlePendingDelay = 0;
2765 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002766 mNextLightIdleDelay = 0;
Denny cy Leec5a7c292019-01-01 17:37:55 +08002767 mIdleStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002768 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002769 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002770 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002771 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002772 mAnyMotionDetector.stop();
Robin Lee876b88542018-11-13 17:22:24 +01002773 updateActiveConstraintsLocked();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002774 }
2775
Kweku Adams00e3a372018-09-28 16:57:09 -07002776 private void resetLightIdleManagementLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002777 cancelLightAlarmLocked();
2778 }
2779
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002780 void exitForceIdleLocked() {
2781 if (mForceIdle) {
2782 mForceIdle = false;
2783 if (mScreenOn || mCharging) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002784 mActiveReason = ACTIVE_REASON_FORCED;
Dianne Hackborn88c41352016-04-07 15:18:58 -07002785 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002786 }
2787 }
2788 }
2789
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002790 /**
2791 * Must only be used in tests.
2792 *
2793 * This sets the state value directly and thus doesn't trigger any behavioral changes.
2794 */
2795 @VisibleForTesting
2796 void setLightStateForTest(int lightState) {
Kweku Adams799858b2018-10-08 17:19:08 -07002797 synchronized (this) {
2798 mLightState = lightState;
2799 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002800 }
2801
Kweku Adams00e3a372018-09-28 16:57:09 -07002802 @VisibleForTesting
2803 int getLightState() {
2804 return mLightState;
2805 }
2806
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002807 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002808 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002809 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002810 // there is nothing left to do for light mode.
2811 return;
2812 }
2813
2814 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2815 EventLogTags.writeDeviceIdleLightStep();
2816
2817 switch (mLightState) {
2818 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002819 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002820 // Reset the upcoming idle delays.
2821 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002822 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002823 if (!isOpsInactiveLocked()) {
2824 // We have some active ops going on... give them a chance to finish
2825 // before going in to our first idle.
2826 mLightState = LIGHT_STATE_PRE_IDLE;
2827 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2828 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2829 break;
2830 }
2831 // Nothing active, fall through to immediately idle.
2832 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002833 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002834 if (mMaintenanceStartTime != 0) {
2835 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2836 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2837 // We didn't use up all of our minimum budget; add this to the reserve.
2838 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2839 } else {
2840 // We used more than our minimum budget; this comes out of the reserve.
2841 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2842 }
2843 }
2844 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002845 scheduleLightAlarmLocked(mNextLightIdleDelay);
2846 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2847 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2848 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2849 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2850 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002851 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2852 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002853 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002854 addEvent(EVENT_LIGHT_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002855 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002856 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2857 break;
2858 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002859 case LIGHT_STATE_WAITING_FOR_NETWORK:
2860 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2861 // We have been idling long enough, now it is time to do some work.
2862 mActiveIdleOpCount = 1;
2863 mActiveIdleWakeLock.acquire();
2864 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2865 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2866 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2867 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2868 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2869 }
2870 scheduleLightAlarmLocked(mCurIdleBudget);
2871 if (DEBUG) Slog.d(TAG,
2872 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2873 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2874 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002875 addEvent(EVENT_LIGHT_MAINTENANCE, null);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002876 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2877 } else {
2878 // We'd like to do maintenance, but currently don't have network
2879 // connectivity... let's try to wait until the network comes back.
2880 // We'll only wait for another full idle period, however, and then give up.
2881 scheduleLightAlarmLocked(mNextLightIdleDelay);
2882 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2883 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2884 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002885 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002886 break;
2887 }
2888 }
2889
Kweku Adams00e3a372018-09-28 16:57:09 -07002890 @VisibleForTesting
2891 int getState() {
2892 return mState;
2893 }
2894
2895 @VisibleForTesting
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002896 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002897 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002898 EventLogTags.writeDeviceIdleStep();
2899
2900 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002901 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002902 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2903 if (mState != STATE_ACTIVE) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08002904 mActiveReason = ACTIVE_REASON_ALARM;
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002905 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002906 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002907 }
2908 return;
2909 }
2910
Robin Lee876b88542018-11-13 17:22:24 +01002911 if (mNumBlockingConstraints != 0 && !mForceIdle) {
2912 // We have some constraints from other parts of the system server preventing
2913 // us from moving to the next state.
2914 if (DEBUG) {
2915 Slog.i(TAG, "Cannot step idle state. Blocked by: " + mConstraints.values().stream()
2916 .filter(x -> x.active)
2917 .map(x -> x.name)
2918 .collect(Collectors.joining(",")));
2919 }
2920 return;
2921 }
2922
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002923 switch (mState) {
2924 case STATE_INACTIVE:
2925 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002926 // for motion and sleep some more while doing so.
2927 startMonitoringMotionLocked();
Denny cy Leec5a7c292019-01-01 17:37:55 +08002928 long delay = mConstants.IDLE_AFTER_INACTIVE_TIMEOUT;
2929 if (shouldUseIdleTimeoutFactorLocked()) {
2930 delay = (long) (mPreIdleFactor * delay);
2931 }
2932 scheduleAlarmLocked(delay, false);
Robin Lee876b88542018-11-13 17:22:24 +01002933 moveToStateLocked(STATE_IDLE_PENDING, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002934 break;
2935 case STATE_IDLE_PENDING:
Robin Lee876b88542018-11-13 17:22:24 +01002936 moveToStateLocked(STATE_SENSING, reason);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002937 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002938 mLocated = false;
2939 mLastGenericLocation = null;
2940 mLastGpsLocation = null;
Robin Lee876b88542018-11-13 17:22:24 +01002941 updateActiveConstraintsLocked();
Robin Leec4d424c2018-12-07 15:09:13 +01002942
Robin Lee876b88542018-11-13 17:22:24 +01002943 // Wait for open constraints and an accelerometer reading before moving on.
Robin Leec4d424c2018-12-07 15:09:13 +01002944 if (mUseMotionSensor && mAnyMotionDetector.hasSensor()) {
2945 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
2946 mNotMoving = false;
2947 mAnyMotionDetector.checkForAnyMotion();
2948 break;
Robin Lee876b88542018-11-13 17:22:24 +01002949 } else if (mNumBlockingConstraints != 0) {
2950 cancelAlarmLocked();
2951 break;
Robin Leec4d424c2018-12-07 15:09:13 +01002952 }
2953
2954 mNotMoving = true;
2955 // Otherwise, fall through and check this off the list of requirements.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002956 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002957 cancelSensingTimeoutAlarmLocked();
Robin Lee876b88542018-11-13 17:22:24 +01002958 moveToStateLocked(STATE_LOCATING, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002959 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Kweku Adams799858b2018-10-08 17:19:08 -07002960 LocationManager locationManager = mInjector.getLocationManager();
2961 if (locationManager != null
2962 && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2963 locationManager.requestLocationUpdates(mLocationRequest,
Joe LaPenna23d681b2015-08-27 15:12:11 -07002964 mGenericLocationListener, mHandler.getLooper());
2965 mLocating = true;
2966 } else {
2967 mHasNetworkLocation = false;
2968 }
Kweku Adams799858b2018-10-08 17:19:08 -07002969 if (locationManager != null
2970 && locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002971 mHasGps = true;
Kweku Adams799858b2018-10-08 17:19:08 -07002972 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002973 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002974 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002975 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002976 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002977 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002978 // If we have a location provider, we're all set, the listeners will move state
2979 // forward.
2980 if (mLocating) {
2981 break;
2982 }
2983
2984 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002985 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002986 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002987 cancelLocatingLocked();
2988 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002989
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002990 // Intentional fallthrough -- time to go into IDLE state.
2991 case STATE_QUICK_DOZE_DELAY:
2992 // Reset the upcoming idle delays.
2993 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2994 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2995
2996 // Everything is in place to go into IDLE state.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002997 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002998 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002999 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
3000 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07003001 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003002 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Denny cy Leec5a7c292019-01-01 17:37:55 +08003003 mIdleStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07003004 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07003005 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
3006 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
3007 }
Robin Lee876b88542018-11-13 17:22:24 +01003008 moveToStateLocked(STATE_IDLE, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003009 if (mLightState != LIGHT_STATE_OVERRIDE) {
3010 mLightState = LIGHT_STATE_OVERRIDE;
3011 cancelLightAlarmLocked();
3012 }
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003013 addEvent(EVENT_DEEP_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08003014 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003015 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
3016 break;
3017 case STATE_IDLE:
3018 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003019 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003020 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003021 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003022 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
3023 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003024 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07003025 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
3026 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07003027 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
3028 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
3029 }
Robin Lee876b88542018-11-13 17:22:24 +01003030 moveToStateLocked(STATE_IDLE_MAINTENANCE, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003031 addEvent(EVENT_DEEP_MAINTENANCE, null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003032 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
3033 break;
3034 }
3035 }
3036
Robin Lee876b88542018-11-13 17:22:24 +01003037 private void moveToStateLocked(int state, String reason) {
3038 final int oldState = mState;
3039 mState = state;
3040 if (DEBUG) {
3041 Slog.d(TAG, String.format("Moved from STATE_%s to STATE_%s.",
3042 stateToString(oldState), stateToString(mState)));
3043 }
3044 EventLogTags.writeDeviceIdle(mState, reason);
3045 updateActiveConstraintsLocked();
3046 }
3047
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003048 void incActiveIdleOps() {
3049 synchronized (this) {
3050 mActiveIdleOpCount++;
3051 }
3052 }
3053
3054 void decActiveIdleOps() {
3055 synchronized (this) {
3056 mActiveIdleOpCount--;
3057 if (mActiveIdleOpCount <= 0) {
3058 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003059 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003060 }
3061 }
3062 }
3063
Kweku Adamsa457f4e2018-10-03 15:56:06 -07003064 /** Must only be used in tests. */
3065 @VisibleForTesting
3066 void setActiveIdleOpsForTest(int count) {
Kweku Adams799858b2018-10-08 17:19:08 -07003067 synchronized (this) {
3068 mActiveIdleOpCount = count;
3069 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07003070 }
3071
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003072 void setJobsActive(boolean active) {
3073 synchronized (this) {
3074 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08003075 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003076 if (!active) {
3077 exitMaintenanceEarlyIfNeededLocked();
3078 }
3079 }
3080 }
3081
3082 void setAlarmsActive(boolean active) {
3083 synchronized (this) {
3084 mAlarmsActive = active;
3085 if (!active) {
3086 exitMaintenanceEarlyIfNeededLocked();
3087 }
3088 }
3089 }
3090
Yao Chenca5edbb2016-01-13 14:44:36 -08003091 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
3092 synchronized (this) {
3093 mMaintenanceActivityListeners.register(listener);
3094 return mReportedMaintenanceActivity;
3095 }
3096 }
3097
3098 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
3099 synchronized (this) {
3100 mMaintenanceActivityListeners.unregister(listener);
3101 }
3102 }
3103
Denny cy Leec5a7c292019-01-01 17:37:55 +08003104 @VisibleForTesting
3105 int setPreIdleTimeoutMode(int mode) {
3106 return setPreIdleTimeoutFactor(getPreIdleTimeoutByMode(mode));
3107 }
3108
3109 @VisibleForTesting
3110 float getPreIdleTimeoutByMode(int mode) {
3111 switch (mode) {
3112 case PowerManager.PRE_IDLE_TIMEOUT_MODE_LONG: {
3113 return mConstants.PRE_IDLE_FACTOR_LONG;
3114 }
3115 case PowerManager.PRE_IDLE_TIMEOUT_MODE_SHORT: {
3116 return mConstants.PRE_IDLE_FACTOR_SHORT;
3117 }
3118 case PowerManager.PRE_IDLE_TIMEOUT_MODE_NORMAL: {
3119 return 1.0f;
3120 }
3121 default: {
3122 Slog.w(TAG, "Invalid time out factor mode: " + mode);
3123 return 1.0f;
3124 }
3125 }
3126 }
3127
3128 @VisibleForTesting
3129 float getPreIdleTimeoutFactor() {
3130 return mPreIdleFactor;
3131 }
3132
3133 @VisibleForTesting
3134 int setPreIdleTimeoutFactor(float ratio) {
3135 if (!mDeepEnabled) {
3136 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: Deep Idle disable");
3137 return SET_IDLE_FACTOR_RESULT_NOT_SUPPORT;
3138 } else if (ratio <= MIN_PRE_IDLE_FACTOR_CHANGE) {
3139 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: Invalid input");
3140 return SET_IDLE_FACTOR_RESULT_INVALID;
3141 } else if (Math.abs(ratio - mPreIdleFactor) < MIN_PRE_IDLE_FACTOR_CHANGE) {
3142 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: New factor same as previous factor");
3143 return SET_IDLE_FACTOR_RESULT_IGNORED;
3144 }
3145 synchronized (this) {
3146 mLastPreIdleFactor = mPreIdleFactor;
3147 mPreIdleFactor = ratio;
3148 }
3149 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: " + ratio);
3150 postUpdatePreIdleFactor();
3151 return SET_IDLE_FACTOR_RESULT_OK;
3152 }
3153
3154 @VisibleForTesting
3155 void resetPreIdleTimeoutMode() {
3156 synchronized (this) {
3157 mLastPreIdleFactor = mPreIdleFactor;
3158 mPreIdleFactor = 1.0f;
3159 }
3160 if (DEBUG) Slog.d(TAG, "resetPreIdleTimeoutMode to 1.0");
3161 postResetPreIdleTimeoutFactor();
3162 }
3163
3164 private void postUpdatePreIdleFactor() {
3165 mHandler.sendEmptyMessage(MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR);
3166 }
3167
3168 private void postResetPreIdleTimeoutFactor() {
3169 mHandler.sendEmptyMessage(MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR);
3170 }
3171
3172 @VisibleForTesting
3173 void updatePreIdleFactor() {
3174 synchronized (this) {
3175 if (!shouldUseIdleTimeoutFactorLocked()) {
3176 return;
3177 }
3178 if (mState == STATE_INACTIVE || mState == STATE_IDLE_PENDING) {
3179 if (mNextAlarmTime == 0) {
3180 return;
3181 }
3182 long delay = mNextAlarmTime - SystemClock.elapsedRealtime();
3183 if (delay < MIN_STATE_STEP_ALARM_CHANGE) {
3184 return;
3185 }
3186 long newDelay = (long) (delay / mLastPreIdleFactor * mPreIdleFactor);
3187 if (Math.abs(delay - newDelay) < MIN_STATE_STEP_ALARM_CHANGE) {
3188 return;
3189 }
3190 scheduleAlarmLocked(newDelay, false);
3191 }
3192 }
3193 }
3194
3195 @VisibleForTesting
3196 void maybeDoImmediateMaintenance() {
3197 synchronized (this) {
3198 if (mState == STATE_IDLE) {
3199 long duration = SystemClock.elapsedRealtime() - mIdleStartTime;
3200 /* Let's trgger a immediate maintenance,
3201 * if it has been idle for a long time */
3202 if (duration > mConstants.IDLE_TIMEOUT) {
3203 scheduleAlarmLocked(0, false);
3204 }
3205 }
3206 }
3207 }
3208
3209 private boolean shouldUseIdleTimeoutFactorLocked() {
3210 // exclude ACTIVE_REASON_MOTION, for exclude device in pocket case
3211 if (mActiveReason == ACTIVE_REASON_MOTION) {
3212 return false;
3213 }
3214 return true;
3215 }
3216
3217 /** Must only be used in tests. */
3218 @VisibleForTesting
3219 void setIdleStartTimeForTest(long idleStartTime) {
3220 synchronized (this) {
3221 mIdleStartTime = idleStartTime;
3222 }
3223 }
3224
Yao Chenca5edbb2016-01-13 14:44:36 -08003225 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07003226 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08003227 if (active == mReportedMaintenanceActivity) {
3228 return;
3229 }
3230 mReportedMaintenanceActivity = active;
3231 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
3232 mReportedMaintenanceActivity ? 1 : 0, 0);
3233 mHandler.sendMessage(msg);
3234 }
3235
Denny cy Leec5a7c292019-01-01 17:37:55 +08003236 @VisibleForTesting
3237 long getNextAlarmTime() {
3238 return mNextAlarmTime;
3239 }
3240
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003241 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07003242 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003243 }
3244
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003245 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003246 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
3247 || mLightState == LIGHT_STATE_PRE_IDLE) {
3248 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003249 final long now = SystemClock.elapsedRealtime();
3250 if (DEBUG) {
3251 StringBuilder sb = new StringBuilder();
3252 sb.append("Exit: start=");
3253 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
3254 sb.append(" now=");
3255 TimeUtils.formatDuration(now, sb);
3256 Slog.d(TAG, sb.toString());
3257 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003258 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003259 stepIdleStateLocked("s:early");
3260 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
3261 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003262 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07003263 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003264 }
3265 }
3266 }
3267 }
3268
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003269 void motionLocked() {
3270 if (DEBUG) Slog.d(TAG, "motionLocked()");
3271 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003272 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
3273 }
3274
3275 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003276 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003277 // state to wait again for no motion. Note that we only monitor for motion
3278 // after moving out of the inactive state, so no need to worry about that.
Kweku Adamsb7ce1902019-01-30 10:55:34 -08003279 final boolean becomeInactive = mState != STATE_ACTIVE
3280 || mLightState == LIGHT_STATE_OVERRIDE;
3281 // We only want to change the IDLE state if it's OVERRIDE.
3282 becomeActiveLocked(type, Process.myUid(), timeout, mLightState == LIGHT_STATE_OVERRIDE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003283 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003284 becomeInactiveIfAppropriateLocked();
3285 }
3286 }
3287
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003288 void receivedGenericLocationLocked(Location location) {
3289 if (mState != STATE_LOCATING) {
3290 cancelLocatingLocked();
3291 return;
3292 }
3293 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
3294 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003295 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003296 return;
3297 }
3298 mLocated = true;
3299 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003300 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003301 }
3302 }
3303
3304 void receivedGpsLocationLocked(Location location) {
3305 if (mState != STATE_LOCATING) {
3306 cancelLocatingLocked();
3307 return;
3308 }
3309 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
3310 mLastGpsLocation = new Location(location);
3311 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
3312 return;
3313 }
3314 mLocated = true;
3315 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003316 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003317 }
3318 }
3319
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003320 void startMonitoringMotionLocked() {
3321 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
3322 if (mMotionSensor != null && !mMotionListener.active) {
3323 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003324 }
3325 }
3326
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003327 void stopMonitoringMotionLocked() {
3328 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
3329 if (mMotionSensor != null && mMotionListener.active) {
3330 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003331 }
3332 }
3333
3334 void cancelAlarmLocked() {
3335 if (mNextAlarmTime != 0) {
3336 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003337 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003338 }
3339 }
3340
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003341 void cancelLightAlarmLocked() {
3342 if (mNextLightAlarmTime != 0) {
3343 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003344 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003345 }
3346 }
3347
3348 void cancelLocatingLocked() {
3349 if (mLocating) {
Kweku Adams799858b2018-10-08 17:19:08 -07003350 LocationManager locationManager = mInjector.getLocationManager();
3351 locationManager.removeUpdates(mGenericLocationListener);
3352 locationManager.removeUpdates(mGpsLocationListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003353 mLocating = false;
3354 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003355 }
3356
Kevin Gabayan92f15e62016-04-04 17:52:22 -07003357 void cancelSensingTimeoutAlarmLocked() {
3358 if (mNextSensingTimeoutAlarmTime != 0) {
3359 mNextSensingTimeoutAlarmTime = 0;
3360 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
3361 }
3362 }
3363
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003364 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003365 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Robin Leec4d424c2018-12-07 15:09:13 +01003366
3367 if (mUseMotionSensor && mMotionSensor == null
3368 && mState != STATE_QUICK_DOZE_DELAY
3369 && mState != STATE_IDLE
3370 && mState != STATE_IDLE_MAINTENANCE) {
3371 // 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 -07003372 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07003373 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003374 // manually poke it by pretending like the alarm is going off.
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003375 // STATE_QUICK_DOZE_DELAY skips the motion sensing so if the state is past the motion
3376 // sensing stage (ie, is QUICK_DOZE_DELAY, IDLE, or IDLE_MAINTENANCE), then idling
3377 // can continue until the user interacts with the device.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003378 return;
3379 }
3380 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
3381 if (idleUntil) {
3382 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003383 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003384 } else {
3385 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003386 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003387 }
3388 }
3389
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003390 void scheduleLightAlarmLocked(long delay) {
3391 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003392 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003393 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003394 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07003395 }
3396
Kevin Gabayan92f15e62016-04-04 17:52:22 -07003397 void scheduleSensingTimeoutAlarmLocked(long delay) {
3398 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
3399 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
3400 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
3401 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
3402 }
3403
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003404 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
3405 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
3406 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003407 if (systemApps != null) {
3408 for (int i = 0; i < systemApps.size(); i++) {
3409 outAppIds.put(systemApps.valueAt(i), true);
3410 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003411 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003412 if (userApps != null) {
3413 for (int i = 0; i < userApps.size(); i++) {
3414 outAppIds.put(userApps.valueAt(i), true);
3415 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003416 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003417 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003418 int[] appids = new int[size];
3419 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003420 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003421 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003422 return appids;
3423 }
3424
3425 private void updateWhitelistAppIdsLocked() {
3426 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
3427 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
3428 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
3429 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003430 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
3431 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003432 if (mLocalActivityManager != null) {
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07003433 mLocalActivityManager.setDeviceIdleWhitelist(
3434 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003435 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003436 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003437 if (DEBUG) {
3438 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003439 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003440 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003441 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003442 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003443 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003444 }
3445
Dianne Hackborn85e35642017-01-12 15:10:57 -08003446 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003447 final int size = mTempWhitelistAppIdEndTimes.size();
3448 if (mTempWhitelistAppIdArray.length != size) {
3449 mTempWhitelistAppIdArray = new int[size];
3450 }
3451 for (int i = 0; i < size; i++) {
3452 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
3453 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08003454 if (mLocalActivityManager != null) {
3455 if (DEBUG) {
3456 Slog.d(TAG, "Setting activity manager temp whitelist to "
3457 + Arrays.toString(mTempWhitelistAppIdArray));
3458 }
3459 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
3460 adding);
3461 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003462 if (mLocalPowerManager != null) {
3463 if (DEBUG) {
3464 Slog.d(TAG, "Setting wakelock temp whitelist to "
3465 + Arrays.toString(mTempWhitelistAppIdArray));
3466 }
3467 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
3468 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003469 passWhiteListsToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003470 }
3471
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003472 private void reportPowerSaveWhitelistChangedLocked() {
3473 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
3474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003475 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003476 }
3477
3478 private void reportTempWhitelistChangedLocked() {
3479 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
3480 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003481 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003482 }
3483
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003484 private void passWhiteListsToForceAppStandbyTrackerLocked() {
Makoto Onukie4918212018-02-06 11:30:15 -08003485 mAppStateTracker.setPowerSaveWhitelistAppIds(
Makoto Onuki71755c92018-01-16 14:15:44 -08003486 mPowerSaveWhitelistExceptIdleAppIdArray,
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003487 mPowerSaveWhitelistUserAppIdArray,
Makoto Onuki2206af32017-11-21 16:25:35 -08003488 mTempWhitelistAppIdArray);
3489 }
3490
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003491 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003492 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003493 mPowerSaveWhitelistUserApps.clear();
3494 FileInputStream stream;
3495 try {
3496 stream = mConfigFile.openRead();
3497 } catch (FileNotFoundException e) {
3498 return;
3499 }
3500 try {
3501 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003502 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003503 readConfigFileLocked(parser);
3504 } catch (XmlPullParserException e) {
3505 } finally {
3506 try {
3507 stream.close();
3508 } catch (IOException e) {
3509 }
3510 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003511 }
3512
3513 private void readConfigFileLocked(XmlPullParser parser) {
3514 final PackageManager pm = getContext().getPackageManager();
3515
3516 try {
3517 int type;
3518 while ((type = parser.next()) != XmlPullParser.START_TAG
3519 && type != XmlPullParser.END_DOCUMENT) {
3520 ;
3521 }
3522
3523 if (type != XmlPullParser.START_TAG) {
3524 throw new IllegalStateException("no start tag found");
3525 }
3526
3527 int outerDepth = parser.getDepth();
3528 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3529 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3530 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3531 continue;
3532 }
3533
3534 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07003535 switch (tagName) {
3536 case "wl":
3537 String name = parser.getAttributeValue(null, "n");
3538 if (name != null) {
3539 try {
3540 ApplicationInfo ai = pm.getApplicationInfo(name,
3541 PackageManager.MATCH_ANY_USER);
3542 mPowerSaveWhitelistUserApps.put(ai.packageName,
3543 UserHandle.getAppId(ai.uid));
3544 } catch (PackageManager.NameNotFoundException e) {
3545 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003546 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003547 break;
3548 case "un-wl":
3549 final String packageName = parser.getAttributeValue(null, "n");
3550 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
3551 mRemovedFromSystemWhitelistApps.put(packageName,
3552 mPowerSaveWhitelistApps.remove(packageName));
3553 }
3554 break;
3555 default:
3556 Slog.w(TAG, "Unknown element under <config>: "
3557 + parser.getName());
3558 XmlUtils.skipCurrentTag(parser);
3559 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003560 }
3561 }
3562
3563 } catch (IllegalStateException e) {
3564 Slog.w(TAG, "Failed parsing config " + e);
3565 } catch (NullPointerException e) {
3566 Slog.w(TAG, "Failed parsing config " + e);
3567 } catch (NumberFormatException e) {
3568 Slog.w(TAG, "Failed parsing config " + e);
3569 } catch (XmlPullParserException e) {
3570 Slog.w(TAG, "Failed parsing config " + e);
3571 } catch (IOException e) {
3572 Slog.w(TAG, "Failed parsing config " + e);
3573 } catch (IndexOutOfBoundsException e) {
3574 Slog.w(TAG, "Failed parsing config " + e);
3575 }
3576 }
3577
3578 void writeConfigFileLocked() {
3579 mHandler.removeMessages(MSG_WRITE_CONFIG);
3580 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
3581 }
3582
3583 void handleWriteConfigFile() {
3584 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
3585
3586 try {
3587 synchronized (this) {
3588 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003589 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003590 writeConfigFileLocked(out);
3591 }
3592 } catch (IOException e) {
3593 }
3594
3595 synchronized (mConfigFile) {
3596 FileOutputStream stream = null;
3597 try {
3598 stream = mConfigFile.startWrite();
3599 memStream.writeTo(stream);
3600 stream.flush();
3601 FileUtils.sync(stream);
3602 stream.close();
3603 mConfigFile.finishWrite(stream);
3604 } catch (IOException e) {
3605 Slog.w(TAG, "Error writing config file", e);
3606 mConfigFile.failWrite(stream);
3607 }
3608 }
3609 }
3610
3611 void writeConfigFileLocked(XmlSerializer out) throws IOException {
3612 out.startDocument(null, true);
3613 out.startTag(null, "config");
3614 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
3615 String name = mPowerSaveWhitelistUserApps.keyAt(i);
3616 out.startTag(null, "wl");
3617 out.attribute(null, "n", name);
3618 out.endTag(null, "wl");
3619 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003620 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
3621 out.startTag(null, "un-wl");
3622 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
3623 out.endTag(null, "un-wl");
3624 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003625 out.endTag(null, "config");
3626 out.endDocument();
3627 }
3628
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003629 static void dumpHelp(PrintWriter pw) {
3630 pw.println("Device idle controller (deviceidle) commands:");
3631 pw.println(" help");
3632 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003633 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003634 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003635 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003636 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003637 pw.println(" force-inactive");
3638 pw.println(" Force to be inactive, ready to freely step idle states.");
3639 pw.println(" unforce");
3640 pw.println(" Resume normal functioning after force-idle or force-inactive.");
3641 pw.println(" get [light|deep|force|screen|charging|network]");
3642 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003643 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003644 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003645 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003646 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003647 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07003648 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07003649 pw.println(" whitelist");
3650 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07003651 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003652 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07003653 pw.println(" sys-whitelist [package ...|reset]");
3654 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
3655 + " to put it back in the system whitelist.");
3656 pw.println(" Note that only packages that were"
3657 + " earlier removed from the system whitelist can be added back.");
3658 pw.println(" reset will reset the whitelist to the original state");
3659 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003660 pw.println(" except-idle-whitelist [package ...|reset]");
3661 pw.println(" Prefix the package with '+' to add it to whitelist or "
3662 + "'=' to check if it is already whitelisted");
3663 pw.println(" [reset] will reset the whitelist to it's original state");
3664 pw.println(" Note that unlike <whitelist> cmd, "
3665 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003666 pw.println(" tempwhitelist");
3667 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003668 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
3669 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08003670 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003671 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
3672 + "and any [-d] is ignored");
Amith Yamasani4cb42572018-04-27 10:02:57 -07003673 pw.println(" motion");
3674 pw.println(" Simulate a motion event to bring the device out of deep doze");
Denny cy Leec5a7c292019-01-01 17:37:55 +08003675 pw.println(" pre-idle-factor [0|1|2]");
3676 pw.println(" Set a new factor to idle time before step to idle"
3677 + "(inactive_to and idle_after_inactive_to)");
3678 pw.println(" reset-pre-idle-factor");
3679 pw.println(" Reset factor to idle time to default");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003680 }
3681
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003682 class Shell extends ShellCommand {
3683 int userId = UserHandle.USER_SYSTEM;
3684
3685 @Override
3686 public int onCommand(String cmd) {
3687 return onShellCommand(this, cmd);
3688 }
3689
3690 @Override
3691 public void onHelp() {
3692 PrintWriter pw = getOutPrintWriter();
3693 dumpHelp(pw);
3694 }
3695 }
3696
3697 int onShellCommand(Shell shell, String cmd) {
3698 PrintWriter pw = shell.getOutPrintWriter();
3699 if ("step".equals(cmd)) {
3700 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3701 null);
3702 synchronized (this) {
3703 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003704 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003705 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003706 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003707 stepIdleStateLocked("s:shell");
3708 pw.print("Stepped to deep: ");
3709 pw.println(stateToString(mState));
3710 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003711 stepLightIdleStateLocked("s:shell");
3712 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
3713 } else {
3714 pw.println("Unknown idle mode: " + arg);
3715 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003716 } finally {
3717 Binder.restoreCallingIdentity(token);
3718 }
3719 }
3720 } else if ("force-idle".equals(cmd)) {
3721 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3722 null);
3723 synchronized (this) {
3724 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07003725 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003726 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07003727 if (arg == null || "deep".equals(arg)) {
3728 if (!mDeepEnabled) {
3729 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003730 return -1;
3731 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003732 mForceIdle = true;
3733 becomeInactiveIfAppropriateLocked();
3734 int curState = mState;
3735 while (curState != STATE_IDLE) {
3736 stepIdleStateLocked("s:shell");
3737 if (curState == mState) {
3738 pw.print("Unable to go deep idle; stopped at ");
3739 pw.println(stateToString(mState));
3740 exitForceIdleLocked();
3741 return -1;
3742 }
3743 curState = mState;
3744 }
3745 pw.println("Now forced in to deep idle mode");
3746 } else if ("light".equals(arg)) {
3747 mForceIdle = true;
3748 becomeInactiveIfAppropriateLocked();
3749 int curLightState = mLightState;
3750 while (curLightState != LIGHT_STATE_IDLE) {
Tej Singh93cf3e32017-12-07 13:05:38 -08003751 stepLightIdleStateLocked("s:shell");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003752 if (curLightState == mLightState) {
3753 pw.print("Unable to go light idle; stopped at ");
3754 pw.println(lightStateToString(mLightState));
3755 exitForceIdleLocked();
3756 return -1;
3757 }
3758 curLightState = mLightState;
3759 }
3760 pw.println("Now forced in to light idle mode");
3761 } else {
3762 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003763 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003764 } finally {
3765 Binder.restoreCallingIdentity(token);
3766 }
3767 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003768 } else if ("force-inactive".equals(cmd)) {
3769 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3770 null);
3771 synchronized (this) {
3772 long token = Binder.clearCallingIdentity();
3773 try {
3774 mForceIdle = true;
3775 becomeInactiveIfAppropriateLocked();
3776 pw.print("Light state: ");
3777 pw.print(lightStateToString(mLightState));
3778 pw.print(", deep state: ");
3779 pw.println(stateToString(mState));
3780 } finally {
3781 Binder.restoreCallingIdentity(token);
3782 }
3783 }
3784 } else if ("unforce".equals(cmd)) {
3785 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3786 null);
3787 synchronized (this) {
3788 long token = Binder.clearCallingIdentity();
3789 try {
3790 exitForceIdleLocked();
3791 pw.print("Light state: ");
3792 pw.print(lightStateToString(mLightState));
3793 pw.print(", deep state: ");
3794 pw.println(stateToString(mState));
3795 } finally {
3796 Binder.restoreCallingIdentity(token);
3797 }
3798 }
3799 } else if ("get".equals(cmd)) {
3800 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3801 null);
3802 synchronized (this) {
3803 String arg = shell.getNextArg();
3804 if (arg != null) {
3805 long token = Binder.clearCallingIdentity();
3806 try {
3807 switch (arg) {
3808 case "light": pw.println(lightStateToString(mLightState)); break;
3809 case "deep": pw.println(stateToString(mState)); break;
3810 case "force": pw.println(mForceIdle); break;
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003811 case "quick": pw.println(mQuickDozeActivated); break;
Dianne Hackborn88c41352016-04-07 15:18:58 -07003812 case "screen": pw.println(mScreenOn); break;
3813 case "charging": pw.println(mCharging); break;
3814 case "network": pw.println(mNetworkConnected); break;
3815 default: pw.println("Unknown get option: " + arg); break;
3816 }
3817 } finally {
3818 Binder.restoreCallingIdentity(token);
3819 }
3820 } else {
3821 pw.println("Argument required");
3822 }
3823 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003824 } else if ("disable".equals(cmd)) {
3825 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3826 null);
3827 synchronized (this) {
3828 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003829 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003830 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003831 boolean becomeActive = false;
3832 boolean valid = false;
3833 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3834 valid = true;
3835 if (mDeepEnabled) {
3836 mDeepEnabled = false;
3837 becomeActive = true;
3838 pw.println("Deep idle mode disabled");
3839 }
3840 }
3841 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3842 valid = true;
3843 if (mLightEnabled) {
3844 mLightEnabled = false;
3845 becomeActive = true;
3846 pw.println("Light idle mode disabled");
3847 }
3848 }
3849 if (becomeActive) {
Denny cy Leec5a7c292019-01-01 17:37:55 +08003850 mActiveReason = ACTIVE_REASON_FORCED;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003851 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
3852 Process.myUid());
3853 }
3854 if (!valid) {
3855 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003856 }
3857 } finally {
3858 Binder.restoreCallingIdentity(token);
3859 }
3860 }
3861 } else if ("enable".equals(cmd)) {
3862 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3863 null);
3864 synchronized (this) {
3865 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003866 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003867 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003868 boolean becomeInactive = false;
3869 boolean valid = false;
3870 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3871 valid = true;
3872 if (!mDeepEnabled) {
3873 mDeepEnabled = true;
3874 becomeInactive = true;
3875 pw.println("Deep idle mode enabled");
3876 }
3877 }
3878 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3879 valid = true;
3880 if (!mLightEnabled) {
3881 mLightEnabled = true;
3882 becomeInactive = true;
3883 pw.println("Light idle mode enable");
3884 }
3885 }
3886 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003887 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003888 }
3889 if (!valid) {
3890 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003891 }
3892 } finally {
3893 Binder.restoreCallingIdentity(token);
3894 }
3895 }
3896 } else if ("enabled".equals(cmd)) {
3897 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003898 String arg = shell.getNextArg();
3899 if (arg == null || "all".equals(arg)) {
3900 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
3901 } else if ("deep".equals(arg)) {
3902 pw.println(mDeepEnabled ? "1" : 0);
3903 } else if ("light".equals(arg)) {
3904 pw.println(mLightEnabled ? "1" : 0);
3905 } else {
3906 pw.println("Unknown idle mode: " + arg);
3907 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003908 }
3909 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07003910 String arg = shell.getNextArg();
3911 if (arg != null) {
3912 getContext().enforceCallingOrSelfPermission(
3913 android.Manifest.permission.DEVICE_POWER, null);
3914 long token = Binder.clearCallingIdentity();
3915 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003916 do {
3917 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08003918 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3919 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003920 return -1;
3921 }
3922 char op = arg.charAt(0);
3923 String pkg = arg.substring(1);
3924 if (op == '+') {
3925 if (addPowerSaveWhitelistAppInternal(pkg)) {
3926 pw.println("Added: " + pkg);
3927 } else {
3928 pw.println("Unknown package: " + pkg);
3929 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003930 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003931 if (removePowerSaveWhitelistAppInternal(pkg)) {
3932 pw.println("Removed: " + pkg);
3933 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003934 } else {
3935 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003936 }
3937 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003938 } finally {
3939 Binder.restoreCallingIdentity(token);
3940 }
3941 } else {
3942 synchronized (this) {
3943 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3944 pw.print("system-excidle,");
3945 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3946 pw.print(",");
3947 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3948 }
3949 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3950 pw.print("system,");
3951 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3952 pw.print(",");
3953 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3954 }
3955 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3956 pw.print("user,");
3957 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3958 pw.print(",");
3959 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003960 }
3961 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003962 }
3963 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003964 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003965 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003966 String opt;
3967 while ((opt=shell.getNextOption()) != null) {
3968 if ("-u".equals(opt)) {
3969 opt = shell.getNextArg();
3970 if (opt == null) {
3971 pw.println("-u requires a user number");
3972 return -1;
3973 }
3974 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003975 } else if ("-d".equals(opt)) {
3976 opt = shell.getNextArg();
3977 if (opt == null) {
3978 pw.println("-d requires a duration");
3979 return -1;
3980 }
3981 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003982 } else if ("-r".equals(opt)) {
3983 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003984 }
3985 }
3986 String arg = shell.getNextArg();
3987 if (arg != null) {
3988 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003989 if (removePkg) {
3990 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3991 } else {
3992 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
3993 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07003994 } catch (Exception e) {
3995 pw.println("Failed: " + e);
3996 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003997 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08003998 } else if (removePkg) {
3999 pw.println("[-r] requires a package name");
4000 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004001 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004002 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004003 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07004004 } else if ("except-idle-whitelist".equals(cmd)) {
4005 getContext().enforceCallingOrSelfPermission(
4006 android.Manifest.permission.DEVICE_POWER, null);
4007 final long token = Binder.clearCallingIdentity();
4008 try {
4009 String arg = shell.getNextArg();
4010 if (arg == null) {
4011 pw.println("No arguments given");
4012 return -1;
4013 } else if ("reset".equals(arg)) {
4014 resetPowerSaveWhitelistExceptIdleInternal();
4015 } else {
4016 do {
4017 if (arg.length() < 1 || (arg.charAt(0) != '-'
4018 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
4019 pw.println("Package must be prefixed with +, -, or =: " + arg);
4020 return -1;
4021 }
4022 char op = arg.charAt(0);
4023 String pkg = arg.substring(1);
4024 if (op == '+') {
4025 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
4026 pw.println("Added: " + pkg);
4027 } else {
4028 pw.println("Unknown package: " + pkg);
4029 }
4030 } else if (op == '=') {
4031 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
4032 } else {
4033 pw.println("Unknown argument: " + arg);
4034 return -1;
4035 }
4036 } while ((arg = shell.getNextArg()) != null);
4037 }
4038 } finally {
4039 Binder.restoreCallingIdentity(token);
4040 }
Suprabh Shukla08105642017-09-26 14:45:30 -07004041 } else if ("sys-whitelist".equals(cmd)) {
4042 String arg = shell.getNextArg();
4043 if (arg != null) {
4044 getContext().enforceCallingOrSelfPermission(
4045 android.Manifest.permission.DEVICE_POWER, null);
4046 final long token = Binder.clearCallingIdentity();
4047 try {
4048 if ("reset".equals(arg)) {
4049 resetSystemPowerWhitelistInternal();
4050 } else {
4051 do {
4052 if (arg.length() < 1
4053 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
4054 pw.println("Package must be prefixed with + or - " + arg);
4055 return -1;
4056 }
4057 final char op = arg.charAt(0);
4058 final String pkg = arg.substring(1);
4059 switch (op) {
4060 case '+':
4061 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
4062 pw.println("Restored " + pkg);
4063 }
4064 break;
4065 case '-':
4066 if (removeSystemPowerWhitelistAppInternal(pkg)) {
4067 pw.println("Removed " + pkg);
4068 }
4069 break;
4070 }
4071 } while ((arg = shell.getNextArg()) != null);
4072 }
4073 } finally {
4074 Binder.restoreCallingIdentity(token);
4075 }
4076 } else {
4077 synchronized (this) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07004078 for (int j = 0; j < mPowerSaveWhitelistApps.size(); j++) {
Suprabh Shukla08105642017-09-26 14:45:30 -07004079 pw.print(mPowerSaveWhitelistApps.keyAt(j));
4080 pw.print(",");
4081 pw.println(mPowerSaveWhitelistApps.valueAt(j));
4082 }
4083 }
4084 }
Amith Yamasani4cb42572018-04-27 10:02:57 -07004085 } else if ("motion".equals(cmd)) {
4086 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4087 null);
4088 synchronized (this) {
4089 long token = Binder.clearCallingIdentity();
4090 try {
4091 motionLocked();
4092 pw.print("Light state: ");
4093 pw.print(lightStateToString(mLightState));
4094 pw.print(", deep state: ");
4095 pw.println(stateToString(mState));
4096 } finally {
4097 Binder.restoreCallingIdentity(token);
4098 }
4099 }
Denny cy Leec5a7c292019-01-01 17:37:55 +08004100 } else if ("pre-idle-factor".equals(cmd)) {
4101 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4102 null);
4103 synchronized (this) {
4104 long token = Binder.clearCallingIdentity();
4105 int ret = SET_IDLE_FACTOR_RESULT_UNINIT;
4106 try {
4107 String arg = shell.getNextArg();
4108 boolean valid = false;
4109 int mode = 0;
4110 if (arg != null) {
4111 mode = Integer.parseInt(arg);
4112 ret = setPreIdleTimeoutMode(mode);
4113 if (ret == SET_IDLE_FACTOR_RESULT_OK) {
4114 pw.println("pre-idle-factor: " + mode);
4115 valid = true;
4116 } else if (ret == SET_IDLE_FACTOR_RESULT_NOT_SUPPORT) {
4117 valid = true;
4118 pw.println("Deep idle not supported");
4119 } else if (ret == SET_IDLE_FACTOR_RESULT_IGNORED) {
4120 valid = true;
4121 pw.println("Idle timeout factor not changed");
4122 }
4123 }
4124 if (!valid) {
4125 pw.println("Unknown idle timeout factor: " + arg
4126 + ",(error code: " + ret + ")");
4127 }
4128 } catch (NumberFormatException e) {
4129 pw.println("Unknown idle timeout factor"
4130 + ",(error code: " + ret + ")");
4131 } finally {
4132 Binder.restoreCallingIdentity(token);
4133 }
4134 }
4135 } else if ("reset-pre-idle-factor".equals(cmd)) {
4136 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4137 null);
4138 synchronized (this) {
4139 long token = Binder.clearCallingIdentity();
4140 try {
4141 resetPreIdleTimeoutMode();
4142 } finally {
4143 Binder.restoreCallingIdentity(token);
4144 }
4145 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004146 } else {
4147 return shell.handleDefaultCommands(cmd);
4148 }
4149 return 0;
4150 }
4151
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004152 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004153 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004154
4155 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07004156 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004157 for (int i=0; i<args.length; i++) {
4158 String arg = args[i];
4159 if ("-h".equals(arg)) {
4160 dumpHelp(pw);
4161 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004162 } else if ("-u".equals(arg)) {
4163 i++;
4164 if (i < args.length) {
4165 arg = args[i];
4166 userId = Integer.parseInt(arg);
4167 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004168 } else if ("-a".equals(arg)) {
4169 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004170 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
4171 pw.println("Unknown option: " + arg);
4172 return;
4173 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07004174 Shell shell = new Shell();
4175 shell.userId = userId;
4176 String[] newArgs = new String[args.length-i];
4177 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07004178 shell.exec(mBinderService, null, fd, null, newArgs, null,
4179 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004180 return;
4181 }
4182 }
4183 }
4184
4185 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07004186 mConstants.dump(pw);
4187
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004188 if (mEventCmds[0] != EVENT_NULL) {
4189 pw.println(" Idling history:");
4190 long now = SystemClock.elapsedRealtime();
4191 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
4192 int cmd = mEventCmds[i];
4193 if (cmd == EVENT_NULL) {
4194 continue;
4195 }
4196 String label;
4197 switch (mEventCmds[i]) {
4198 case EVENT_NORMAL: label = " normal"; break;
4199 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
4200 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08004201 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
4202 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004203 default: label = " ??"; break;
4204 }
4205 pw.print(" ");
4206 pw.print(label);
4207 pw.print(": ");
Amith Yamasaniac6517a2018-04-23 12:19:34 -07004208 TimeUtils.formatDuration(mEventTimes[i], now, pw);
4209 if (mEventReasons[i] != null) {
4210 pw.print(" (");
4211 pw.print(mEventReasons[i]);
4212 pw.print(")");
4213 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004214 pw.println();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07004215
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004216 }
4217 }
4218
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004219 int size = mPowerSaveWhitelistAppsExceptIdle.size();
4220 if (size > 0) {
4221 pw.println(" Whitelist (except idle) system apps:");
4222 for (int i = 0; i < size; i++) {
4223 pw.print(" ");
4224 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
4225 }
4226 }
4227 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004228 if (size > 0) {
4229 pw.println(" Whitelist system apps:");
4230 for (int i = 0; i < size; i++) {
4231 pw.print(" ");
4232 pw.println(mPowerSaveWhitelistApps.keyAt(i));
4233 }
4234 }
Suprabh Shukla08105642017-09-26 14:45:30 -07004235 size = mRemovedFromSystemWhitelistApps.size();
4236 if (size > 0) {
4237 pw.println(" Removed from whitelist system apps:");
4238 for (int i = 0; i < size; i++) {
4239 pw.print(" ");
4240 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
4241 }
4242 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004243 size = mPowerSaveWhitelistUserApps.size();
4244 if (size > 0) {
4245 pw.println(" Whitelist user apps:");
4246 for (int i = 0; i < size; i++) {
4247 pw.print(" ");
4248 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
4249 }
4250 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004251 size = mPowerSaveWhitelistExceptIdleAppIds.size();
4252 if (size > 0) {
4253 pw.println(" Whitelist (except idle) all app ids:");
4254 for (int i = 0; i < size; i++) {
4255 pw.print(" ");
4256 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
4257 pw.println();
4258 }
4259 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08004260 size = mPowerSaveWhitelistUserAppIds.size();
4261 if (size > 0) {
4262 pw.println(" Whitelist user app ids:");
4263 for (int i = 0; i < size; i++) {
4264 pw.print(" ");
4265 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
4266 pw.println();
4267 }
4268 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07004269 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004270 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07004271 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004272 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07004273 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07004274 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004275 pw.println();
4276 }
4277 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004278 dumpTempWhitelistSchedule(pw, true);
4279
Dianne Hackborna750a632015-06-16 17:18:23 -07004280 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
4281 if (size > 0) {
4282 pw.println(" Temp whitelist app ids:");
4283 for (int i = 0; i < size; i++) {
4284 pw.print(" ");
4285 pw.print(mTempWhitelistAppIdArray[i]);
4286 pw.println();
4287 }
4288 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07004289
Dianne Hackbornb6843652016-02-22 12:20:13 -08004290 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004291 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004292 pw.print(" mForceIdle="); pw.println(mForceIdle);
Robin Leec4d424c2018-12-07 15:09:13 +01004293 pw.print(" mUseMotionSensor="); pw.print(mUseMotionSensor);
4294 if (mUseMotionSensor) {
4295 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
4296 } else {
4297 pw.println();
4298 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004299 pw.print(" mScreenOn="); pw.println(mScreenOn);
Amith Yamasani396a10c2018-01-19 10:58:07 -08004300 pw.print(" mScreenLocked="); pw.println(mScreenLocked);
Dianne Hackborn88c41352016-04-07 15:18:58 -07004301 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004302 pw.print(" mCharging="); pw.println(mCharging);
Robin Lee876b88542018-11-13 17:22:24 +01004303 if (mConstraints.size() != 0) {
4304 pw.println(" mConstraints={");
4305 for (int i = 0; i < mConstraints.size(); i++) {
4306 final DeviceIdleConstraintTracker tracker = mConstraints.valueAt(i);
4307 pw.print(" \""); pw.print(tracker.name); pw.print("\"=");
4308 if (tracker.minState == mState) {
4309 pw.println(tracker.active);
4310 } else {
4311 pw.print("ignored <mMinState="); pw.print(stateToString(tracker.minState));
4312 pw.println(">");
4313 }
4314 }
4315 pw.println(" }");
4316 }
Robin Leec4d424c2018-12-07 15:09:13 +01004317 if (mUseMotionSensor) {
Robin Lee876b88542018-11-13 17:22:24 +01004318 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Robin Leec4d424c2018-12-07 15:09:13 +01004319 pw.print(" mNotMoving="); pw.println(mNotMoving);
4320 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07004321 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
4322 pw.print(mHasGps); pw.print(" mHasNetwork=");
4323 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07004324 if (mLastGenericLocation != null) {
4325 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
4326 }
4327 if (mLastGpsLocation != null) {
4328 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
4329 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004330 pw.print(" mState="); pw.print(stateToString(mState));
4331 pw.print(" mLightState=");
4332 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004333 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
4334 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004335 if (mActiveIdleOpCount != 0) {
4336 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
4337 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004338 if (mNextAlarmTime != 0) {
4339 pw.print(" mNextAlarmTime=");
4340 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
4341 pw.println();
4342 }
4343 if (mNextIdlePendingDelay != 0) {
4344 pw.print(" mNextIdlePendingDelay=");
4345 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
4346 pw.println();
4347 }
4348 if (mNextIdleDelay != 0) {
4349 pw.print(" mNextIdleDelay=");
4350 TimeUtils.formatDuration(mNextIdleDelay, pw);
4351 pw.println();
4352 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07004353 if (mNextLightIdleDelay != 0) {
4354 pw.print(" mNextIdleDelay=");
4355 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
4356 pw.println();
4357 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004358 if (mNextLightAlarmTime != 0) {
4359 pw.print(" mNextLightAlarmTime=");
4360 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
4361 pw.println();
4362 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08004363 if (mCurIdleBudget != 0) {
4364 pw.print(" mCurIdleBudget=");
4365 TimeUtils.formatDuration(mCurIdleBudget, pw);
4366 pw.println();
4367 }
4368 if (mMaintenanceStartTime != 0) {
4369 pw.print(" mMaintenanceStartTime=");
4370 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
4371 pw.println();
4372 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004373 if (mJobsActive) {
4374 pw.print(" mJobsActive="); pw.println(mJobsActive);
4375 }
4376 if (mAlarmsActive) {
4377 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
4378 }
Denny cy Leec5a7c292019-01-01 17:37:55 +08004379 if (Math.abs(mPreIdleFactor - 1.0f) > MIN_PRE_IDLE_FACTOR_CHANGE) {
4380 pw.print(" mPreIdleFactor="); pw.println(mPreIdleFactor);
4381 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07004382 }
4383 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07004384
4385 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
4386 final int size = mTempWhitelistAppIdEndTimes.size();
4387 if (size > 0) {
4388 String prefix = "";
4389 if (printTitle) {
4390 pw.println(" Temp whitelist schedule:");
4391 prefix = " ";
4392 }
4393 final long timeNow = SystemClock.elapsedRealtime();
4394 for (int i = 0; i < size; i++) {
4395 pw.print(prefix);
4396 pw.print("UID=");
4397 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
4398 pw.print(": ");
4399 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
4400 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
4401 pw.print(" - ");
4402 pw.println(entry.second);
4403 }
4404 }
4405 }
4406 }