Debian Codegraph @

apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java

raw symbols SCIP
1 /*
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
17 package com.android.server;
18
19 import static android.os.PowerExemptionManager.REASON_SHELL;
20 import static android.os.PowerExemptionManager.REASON_UNKNOWN;
21 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
22 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE;
23 import static android.os.Process.INVALID_UID;
24
25 import android.Manifest;
26 import android.annotation.NonNull;
27 import android.annotation.Nullable;
28 import android.annotation.SuppressLint;
29 import android.app.ActivityManager;
30 import android.app.ActivityManagerInternal;
31 import android.app.AlarmManager;
32 import android.content.BroadcastReceiver;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.pm.ApplicationInfo;
37 import android.content.pm.PackageManager;
38 import android.content.pm.PackageManager.NameNotFoundException;
39 import android.content.pm.PackageManagerInternal;
40 import android.content.res.Resources;
41 import android.hardware.Sensor;
42 import android.hardware.SensorEvent;
43 import android.hardware.SensorEventListener;
44 import android.hardware.SensorManager;
45 import android.hardware.TriggerEvent;
46 import android.hardware.TriggerEventListener;
47 import android.location.Location;
48 import android.location.LocationListener;
49 import android.location.LocationManager;
50 import android.location.LocationRequest;
51 import android.net.ConnectivityManager;
52 import android.net.INetworkPolicyManager;
53 import android.net.NetworkInfo;
54 import android.net.Uri;
55 import android.os.BatteryManager;
56 import android.os.BatteryStats;
57 import android.os.Binder;
58 import android.os.Bundle;
59 import android.os.Environment;
60 import android.os.Handler;
61 import android.os.IDeviceIdleController;
62 import android.os.Looper;
63 import android.os.Message;
64 import android.os.PowerExemptionManager;
65 import android.os.PowerExemptionManager.ReasonCode;
66 import android.os.PowerExemptionManager.TempAllowListType;
67 import android.os.PowerManager;
68 import android.os.PowerManager.ServiceType;
69 import android.os.PowerManagerInternal;
70 import android.os.Process;
71 import android.os.RemoteException;
72 import android.os.ResultReceiver;
73 import android.os.ServiceManager;
74 import android.os.ShellCallback;
75 import android.os.ShellCommand;
76 import android.os.SystemClock;
77 import android.os.Trace;
78 import android.os.UserHandle;
79 import android.provider.DeviceConfig;
80 import android.util.ArrayMap;
81 import android.util.ArraySet;
82 import android.util.AtomicFile;
83 import android.util.MutableLong;
84 import android.util.Pair;
85 import android.util.Slog;
86 import android.util.SparseArray;
87 import android.util.SparseBooleanArray;
88 import android.util.TimeUtils;
89 import android.util.Xml;
90
91 import com.android.internal.annotations.GuardedBy;
92 import com.android.internal.annotations.VisibleForTesting;
93 import com.android.internal.app.IBatteryStats;
94 import com.android.internal.util.ArrayUtils;
95 import com.android.internal.util.DumpUtils;
96 import com.android.internal.util.FastXmlSerializer;
97 import com.android.internal.util.XmlUtils;
98 import com.android.server.am.BatteryStatsService;
99 import com.android.server.deviceidle.ConstraintController;
100 import com.android.server.deviceidle.DeviceIdleConstraintTracker;
101 import com.android.server.deviceidle.IDeviceIdleConstraint;
102 import com.android.server.deviceidle.TvConstraintController;
103 import com.android.server.net.NetworkPolicyManagerInternal;
104 import com.android.server.wm.ActivityTaskManagerInternal;
105
106 import org.xmlpull.v1.XmlPullParser;
107 import org.xmlpull.v1.XmlPullParserException;
108 import org.xmlpull.v1.XmlSerializer;
109
110 import java.io.ByteArrayOutputStream;
111 import java.io.File;
112 import java.io.FileDescriptor;
113 import java.io.FileInputStream;
114 import java.io.FileNotFoundException;
115 import java.io.FileOutputStream;
116 import java.io.IOException;
117 import java.io.PrintWriter;
118 import java.nio.charset.StandardCharsets;
119 import java.util.Arrays;
120 import java.util.Collections;
121 import java.util.List;
122 import java.util.stream.Collectors;
123
124 /**
125 * Keeps track of device idleness and drives low power mode based on that.
126 *
127 * Test: atest com.android.server.DeviceIdleControllerTest
128 *
129 * Current idling state machine (as of Android Q). This can be visualized using Graphviz:
130 <pre>
131
132 digraph {
133 subgraph cluster_legend {
134 label="Legend"
135
136 wakeup_alarm [label="Entering this state requires a wakeup alarm",color=red,shape=box]
137 nonwakeup_alarm [
138 label="This state can be entered from a non-wakeup alarm",color=blue,shape=oval
139 ]
140 no_alarm [label="This state doesn't require an alarm",color=black,shape=diamond]
141 }
142
143 subgraph deep {
144 label="deep";
145
146 STATE_ACTIVE [
147 label="STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon",
148 color=black,shape=diamond
149 ]
150 STATE_INACTIVE [
151 label="STATE_INACTIVE\nScreen off AND Not charging",color=black,shape=diamond
152 ]
153 STATE_QUICK_DOZE_DELAY [
154 label="STATE_QUICK_DOZE_DELAY\n"
155 + "Screen off AND Not charging\n"
156 + "Location, motion detection, and significant motion monitoring turned off",
157 color=black,shape=diamond
158 ]
159 STATE_IDLE_PENDING [
160 label="STATE_IDLE_PENDING\nSignificant motion monitoring turned on",
161 color=red,shape=box
162 ]
163 STATE_SENSING [label="STATE_SENSING\nMonitoring for ANY motion",color=red,shape=box]
164 STATE_LOCATING [
165 label="STATE_LOCATING\nRequesting location, motion monitoring still on",
166 color=red,shape=box
167 ]
168 STATE_IDLE [
169 label="STATE_IDLE\nLocation and motion detection turned off\n"
170 + "Significant motion monitoring state unchanged",
171 color=red,shape=box
172 ]
173 STATE_IDLE_MAINTENANCE [label="STATE_IDLE_MAINTENANCE\n",color=red,shape=box]
174
175 STATE_ACTIVE -> STATE_INACTIVE [
176 label="becomeInactiveIfAppropriateLocked() AND Quick Doze not enabled"
177 ]
178 STATE_ACTIVE -> STATE_QUICK_DOZE_DELAY [
179 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
180 ]
181
182 STATE_INACTIVE -> STATE_ACTIVE [
183 label="handleMotionDetectedLocked(), becomeActiveLocked()"
184 ]
185 STATE_INACTIVE -> STATE_IDLE_PENDING [label="stepIdleStateLocked()"]
186 STATE_INACTIVE -> STATE_QUICK_DOZE_DELAY [
187 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
188 ]
189
190 STATE_IDLE_PENDING -> STATE_ACTIVE [
191 label="handleMotionDetectedLocked(), becomeActiveLocked()"
192 ]
193 STATE_IDLE_PENDING -> STATE_SENSING [label="stepIdleStateLocked()"]
194 STATE_IDLE_PENDING -> STATE_QUICK_DOZE_DELAY [
195 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
196 ]
197
198 STATE_SENSING -> STATE_ACTIVE [
199 label="handleMotionDetectedLocked(), becomeActiveLocked()"
200 ]
201 STATE_SENSING -> STATE_LOCATING [label="stepIdleStateLocked()"]
202 STATE_SENSING -> STATE_QUICK_DOZE_DELAY [
203 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
204 ]
205 STATE_SENSING -> STATE_IDLE [
206 label="stepIdleStateLocked()\n"
207 + "No Location Manager OR (no Network provider AND no GPS provider)"
208 ]
209
210 STATE_LOCATING -> STATE_ACTIVE [
211 label="handleMotionDetectedLocked(), becomeActiveLocked()"
212 ]
213 STATE_LOCATING -> STATE_QUICK_DOZE_DELAY [
214 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
215 ]
216 STATE_LOCATING -> STATE_IDLE [label="stepIdleStateLocked()"]
217
218 STATE_QUICK_DOZE_DELAY -> STATE_ACTIVE [
219 label="handleMotionDetectedLocked(), becomeActiveLocked()"
220 ]
221 STATE_QUICK_DOZE_DELAY -> STATE_IDLE [label="stepIdleStateLocked()"]
222
223 STATE_IDLE -> STATE_ACTIVE [label="handleMotionDetectedLocked(), becomeActiveLocked()"]
224 STATE_IDLE -> STATE_IDLE_MAINTENANCE [label="stepIdleStateLocked()"]
225
226 STATE_IDLE_MAINTENANCE -> STATE_ACTIVE [
227 label="handleMotionDetectedLocked(), becomeActiveLocked()"
228 ]
229 STATE_IDLE_MAINTENANCE -> STATE_IDLE [
230 label="stepIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
231 ]
232 }
233
234 subgraph light {
235 label="light"
236
237 LIGHT_STATE_ACTIVE [
238 label="LIGHT_STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon",
239 color=black,shape=diamond
240 ]
241 LIGHT_STATE_INACTIVE [
242 label="LIGHT_STATE_INACTIVE\nScreen off AND Not charging",
243 color=black,shape=diamond
244 ]
245 LIGHT_STATE_IDLE [label="LIGHT_STATE_IDLE\n",color=blue,shape=oval]
246 LIGHT_STATE_WAITING_FOR_NETWORK [
247 label="LIGHT_STATE_WAITING_FOR_NETWORK\n"
248 + "Coming out of LIGHT_STATE_IDLE, waiting for network",
249 color=black,shape=diamond
250 ]
251 LIGHT_STATE_IDLE_MAINTENANCE [
252 label="LIGHT_STATE_IDLE_MAINTENANCE\n",color=red,shape=box
253 ]
254 LIGHT_STATE_OVERRIDE [
255 label="LIGHT_STATE_OVERRIDE\nDevice in deep doze, light no longer changing states"
256 ]
257
258 LIGHT_STATE_ACTIVE -> LIGHT_STATE_INACTIVE [
259 label="becomeInactiveIfAppropriateLocked()"
260 ]
261 LIGHT_STATE_ACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
262
263 LIGHT_STATE_INACTIVE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
264 LIGHT_STATE_INACTIVE -> LIGHT_STATE_IDLE [label="some time transpires"]
265 LIGHT_STATE_INACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
266
267 LIGHT_STATE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
268 LIGHT_STATE_IDLE -> LIGHT_STATE_WAITING_FOR_NETWORK [label="no network"]
269 LIGHT_STATE_IDLE -> LIGHT_STATE_IDLE_MAINTENANCE
270 LIGHT_STATE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
271
272 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
273 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_IDLE_MAINTENANCE
274 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_OVERRIDE [
275 label="deep goes to STATE_IDLE"
276 ]
277
278 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
279 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_IDLE [
280 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
281 ]
282 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
283
284 LIGHT_STATE_OVERRIDE -> LIGHT_STATE_ACTIVE [
285 label="handleMotionDetectedLocked(), becomeActiveLocked()"
286 ]
287 }
288 }
289 </pre>
290 */
291 public class DeviceIdleController extends SystemService
292 implements AnyMotionDetector.DeviceIdleCallback {
293 private static final String TAG = "DeviceIdleController";
294
295 private static final boolean DEBUG = false;
296
297 private static final boolean COMPRESS_TIME = false;
298
299 private static final int EVENT_BUFFER_SIZE = 100;
300
301 private AlarmManager mAlarmManager;
302 private AlarmManagerInternal mLocalAlarmManager;
303 private IBatteryStats mBatteryStats;
304 private ActivityManagerInternal mLocalActivityManager;
305 private ActivityTaskManagerInternal mLocalActivityTaskManager;
306 private DeviceIdleInternal mLocalService;
307 private PackageManagerInternal mPackageManagerInternal;
308 private PowerManagerInternal mLocalPowerManager;
309 private PowerManager mPowerManager;
310 private INetworkPolicyManager mNetworkPolicyManager;
311 private SensorManager mSensorManager;
312 private final boolean mUseMotionSensor;
313 private Sensor mMotionSensor;
314 private LocationRequest mLocationRequest;
315 private Intent mIdleIntent;
316 private Intent mLightIdleIntent;
317 private AnyMotionDetector mAnyMotionDetector;
318 private final AppStateTrackerImpl mAppStateTracker;
319 @GuardedBy("this")
320 private boolean mLightEnabled;
321 @GuardedBy("this")
322 private boolean mDeepEnabled;
323 @GuardedBy("this")
324 private boolean mQuickDozeActivated;
325 @GuardedBy("this")
326 private boolean mQuickDozeActivatedWhileIdling;
327 @GuardedBy("this")
328 private boolean mForceIdle;
329 @GuardedBy("this")
330 private boolean mNetworkConnected;
331 @GuardedBy("this")
332 private boolean mScreenOn;
333 @GuardedBy("this")
334 private boolean mCharging;
335 @GuardedBy("this")
336 private boolean mNotMoving;
337 @GuardedBy("this")
338 private boolean mLocating;
339 @GuardedBy("this")
340 private boolean mLocated;
341 @GuardedBy("this")
342 private boolean mHasGps;
343 @GuardedBy("this")
344 private boolean mHasNetworkLocation;
345 @GuardedBy("this")
346 private Location mLastGenericLocation;
347 @GuardedBy("this")
348 private Location mLastGpsLocation;
349
350 /** Time in the elapsed realtime timebase when this listener last received a motion event. */
351 @GuardedBy("this")
352 private long mLastMotionEventElapsed;
353
354 // Current locked state of the screen
355 @GuardedBy("this")
356 private boolean mScreenLocked;
357 @GuardedBy("this")
358 private int mNumBlockingConstraints = 0;
359
360 /**
361 * Constraints are the "handbrakes" that stop the device from moving into a lower state until
362 * every one is released at the same time.
363 *
364 * @see #registerDeviceIdleConstraintInternal(IDeviceIdleConstraint, String, int)
365 */
366 private final ArrayMap<IDeviceIdleConstraint, DeviceIdleConstraintTracker>
367 mConstraints = new ArrayMap<>();
368 private ConstraintController mConstraintController;
369
370 /** Device is currently active. */
371 @VisibleForTesting
372 static final int STATE_ACTIVE = 0;
373 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
374 @VisibleForTesting
375 static final int STATE_INACTIVE = 1;
376 /** Device is past the initial inactive period, and waiting for the next idle period. */
377 @VisibleForTesting
378 static final int STATE_IDLE_PENDING = 2;
379 /** Device is currently sensing motion. */
380 @VisibleForTesting
381 static final int STATE_SENSING = 3;
382 /** Device is currently finding location (and may still be sensing). */
383 @VisibleForTesting
384 static final int STATE_LOCATING = 4;
385 /** Device is in the idle state, trying to stay asleep as much as possible. */
386 @VisibleForTesting
387 static final int STATE_IDLE = 5;
388 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
389 @VisibleForTesting
390 static final int STATE_IDLE_MAINTENANCE = 6;
391 /**
392 * Device is inactive and should go straight into idle (foregoing motion and location
393 * monitoring), but allow some time for current work to complete first.
394 */
395 @VisibleForTesting
396 static final int STATE_QUICK_DOZE_DELAY = 7;
397
398 private static final int ACTIVE_REASON_UNKNOWN = 0;
399 private static final int ACTIVE_REASON_MOTION = 1;
400 private static final int ACTIVE_REASON_SCREEN = 2;
401 private static final int ACTIVE_REASON_CHARGING = 3;
402 private static final int ACTIVE_REASON_UNLOCKED = 4;
403 private static final int ACTIVE_REASON_FROM_BINDER_CALL = 5;
404 private static final int ACTIVE_REASON_FORCED = 6;
405 private static final int ACTIVE_REASON_ALARM = 7;
406 @VisibleForTesting
407 static final int SET_IDLE_FACTOR_RESULT_UNINIT = -1;
408 @VisibleForTesting
409 static final int SET_IDLE_FACTOR_RESULT_IGNORED = 0;
410 @VisibleForTesting
411 static final int SET_IDLE_FACTOR_RESULT_OK = 1;
412 @VisibleForTesting
413 static final int SET_IDLE_FACTOR_RESULT_NOT_SUPPORT = 2;
414 @VisibleForTesting
415 static final int SET_IDLE_FACTOR_RESULT_INVALID = 3;
416 @VisibleForTesting
417 static final long MIN_STATE_STEP_ALARM_CHANGE = 60 * 1000;
418 @VisibleForTesting
419 static final float MIN_PRE_IDLE_FACTOR_CHANGE = 0.05f;
420
421 @VisibleForTesting
422 static String stateToString(int state) {
423 switch (state) {
424 case STATE_ACTIVE: return "ACTIVE";
425 case STATE_INACTIVE: return "INACTIVE";
426 case STATE_IDLE_PENDING: return "IDLE_PENDING";
427 case STATE_SENSING: return "SENSING";
428 case STATE_LOCATING: return "LOCATING";
429 case STATE_IDLE: return "IDLE";
430 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
431 case STATE_QUICK_DOZE_DELAY: return "QUICK_DOZE_DELAY";
432 default: return Integer.toString(state);
433 }
434 }
435
436 /** Device is currently active. */
437 @VisibleForTesting
438 static final int LIGHT_STATE_ACTIVE = 0;
439 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
440 @VisibleForTesting
441 static final int LIGHT_STATE_INACTIVE = 1;
442 /** Device is in the light idle state, trying to stay asleep as much as possible. */
443 @VisibleForTesting
444 static final int LIGHT_STATE_IDLE = 4;
445 /** Device is in the light idle state, we want to go in to idle maintenance but are
446 * waiting for network connectivity before doing so. */
447 @VisibleForTesting
448 static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
449 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
450 @VisibleForTesting
451 static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
452 /** Device light idle state is overridden, now applying deep doze state. */
453 @VisibleForTesting
454 static final int LIGHT_STATE_OVERRIDE = 7;
455
456 @VisibleForTesting
457 static String lightStateToString(int state) {
458 switch (state) {
459 case LIGHT_STATE_ACTIVE: return "ACTIVE";
460 case LIGHT_STATE_INACTIVE: return "INACTIVE";
461 case LIGHT_STATE_IDLE: return "IDLE";
462 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
463 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
464 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
465 default: return Integer.toString(state);
466 }
467 }
468
469 @GuardedBy("this")
470 private int mState;
471 @GuardedBy("this")
472 private int mLightState;
473
474 @GuardedBy("this")
475 private long mInactiveTimeout;
476 @GuardedBy("this")
477 private long mNextAlarmTime;
478 @GuardedBy("this")
479 private long mNextIdlePendingDelay;
480 @GuardedBy("this")
481 private long mNextIdleDelay;
482 @GuardedBy("this")
483 private long mNextLightIdleDelay;
484 @GuardedBy("this")
485 private long mNextLightAlarmTime;
486 @GuardedBy("this")
487 private long mNextLightMaintenanceAlarmTime;
488 @GuardedBy("this")
489 private long mNextSensingTimeoutAlarmTime;
490
491 /** How long a light idle maintenance window should last. */
492 @GuardedBy("this")
493 private long mCurLightIdleBudget;
494
495 /**
496 * Start time of the current (light or full) maintenance window, in the elapsed timebase. Valid
497 * only if {@link #mState} == {@link #STATE_IDLE_MAINTENANCE} or
498 * {@link #mLightState} == {@link #LIGHT_STATE_IDLE_MAINTENANCE}.
499 */
500 @GuardedBy("this")
501 private long mMaintenanceStartTime;
502 @GuardedBy("this")
503 private long mIdleStartTime;
504
505 @GuardedBy("this")
506 private int mActiveIdleOpCount;
507 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
508 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
509 // (especially NetworkPolicyManager) can shut
510 // down.
511 @GuardedBy("this")
512 private boolean mJobsActive;
513 @GuardedBy("this")
514 private boolean mAlarmsActive;
515
516 /* Factor to apply to INACTIVE_TIMEOUT and IDLE_AFTER_INACTIVE_TIMEOUT in order to enter
517 * STATE_IDLE faster or slower. Don't apply this to SENSING_TIMEOUT or LOCATING_TIMEOUT because:
518 * - Both of them are shorter
519 * - Device sensor might take time be to become be stabilized
520 * Also don't apply the factor if the device is in motion because device motion provides a
521 * stronger signal than a prediction algorithm.
522 */
523 @GuardedBy("this")
524 private float mPreIdleFactor;
525 @GuardedBy("this")
526 private float mLastPreIdleFactor;
527 @GuardedBy("this")
528 private int mActiveReason;
529
530 public final AtomicFile mConfigFile;
531
532 /**
533 * Package names the system has white-listed to opt out of power save restrictions,
534 * except for device idle mode.
535 */
536 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
537
538 /**
539 * Package names the user has white-listed using commandline option to opt out of
540 * power save restrictions, except for device idle mode.
541 */
542 private final ArraySet<String> mPowerSaveWhitelistUserAppsExceptIdle = new ArraySet<>();
543
544 /**
545 * Package names the system has white-listed to opt out of power save restrictions for
546 * all modes.
547 */
548 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
549
550 /**
551 * Package names the user has white-listed to opt out of power save restrictions.
552 */
553 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
554
555 /**
556 * App IDs of built-in system apps that have been white-listed except for idle modes.
557 */
558 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
559 = new SparseBooleanArray();
560
561 /**
562 * App IDs of built-in system apps that have been white-listed.
563 */
564 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
565
566 /**
567 * App IDs that have been white-listed to opt out of power save restrictions, except
568 * for device idle modes.
569 */
570 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
571
572 /**
573 * Current app IDs that are in the complete power save white list, but shouldn't be
574 * excluded from idle modes. This array can be shared with others because it will not be
575 * modified once set.
576 */
577 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
578
579 /**
580 * App IDs that have been white-listed to opt out of power save restrictions.
581 */
582 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
583
584 /**
585 * Current app IDs that are in the complete power save white list. This array can
586 * be shared with others because it will not be modified once set.
587 */
588 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
589
590 /**
591 * App IDs that have been white-listed by the user to opt out of power save restrictions.
592 */
593 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
594
595 /**
596 * Current app IDs that are in the user power save white list. This array can
597 * be shared with others because it will not be modified once set.
598 */
599 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
600
601 /**
602 * List of end times for app-IDs that are temporarily marked as being allowed to access
603 * the network and acquire wakelocks. Times are in milliseconds.
604 */
605 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
606 = new SparseArray<>();
607
608 private NetworkPolicyManagerInternal mNetworkPolicyManagerInternal;
609
610 /**
611 * Current app IDs of temporarily whitelist apps for high-priority messages.
612 */
613 private int[] mTempWhitelistAppIdArray = new int[0];
614
615 /**
616 * Apps in the system whitelist that have been taken out (probably because the user wanted to).
617 * They can be restored back by calling restoreAppToSystemWhitelist(String).
618 */
619 private ArrayMap<String, Integer> mRemovedFromSystemWhitelistApps = new ArrayMap<>();
620
621 private final ArraySet<DeviceIdleInternal.StationaryListener> mStationaryListeners =
622 new ArraySet<>();
623
624 private final ArraySet<PowerAllowlistInternal.TempAllowlistChangeListener>
625 mTempAllowlistChangeListeners = new ArraySet<>();
626
627 private static final int EVENT_NULL = 0;
628 private static final int EVENT_NORMAL = 1;
629 private static final int EVENT_LIGHT_IDLE = 2;
630 private static final int EVENT_LIGHT_MAINTENANCE = 3;
631 private static final int EVENT_DEEP_IDLE = 4;
632 private static final int EVENT_DEEP_MAINTENANCE = 5;
633
634 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
635 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
636 private final String[] mEventReasons = new String[EVENT_BUFFER_SIZE];
637
638 private void addEvent(int cmd, String reason) {
639 if (mEventCmds[0] != cmd) {
640 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
641 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
642 System.arraycopy(mEventReasons, 0, mEventReasons, 1, EVENT_BUFFER_SIZE - 1);
643 mEventCmds[0] = cmd;
644 mEventTimes[0] = SystemClock.elapsedRealtime();
645 mEventReasons[0] = reason;
646 }
647 }
648
649 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
650 @Override public void onReceive(Context context, Intent intent) {
651 switch (intent.getAction()) {
652 case ConnectivityManager.CONNECTIVITY_ACTION: {
653 updateConnectivityState(intent);
654 } break;
655 case Intent.ACTION_BATTERY_CHANGED: {
656 boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
657 boolean plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
658 synchronized (DeviceIdleController.this) {
659 updateChargingLocked(present && plugged);
660 }
661 } break;
662 case Intent.ACTION_PACKAGE_REMOVED: {
663 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
664 Uri data = intent.getData();
665 String ssp;
666 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
667 removePowerSaveWhitelistAppInternal(ssp);
668 }
669 }
670 } break;
671 }
672 }
673 };
674
675 private final AlarmManager.OnAlarmListener mLightAlarmListener = () -> {
676 if (DEBUG) {
677 Slog.d(TAG, "Light progression alarm fired");
678 }
679 synchronized (DeviceIdleController.this) {
680 stepLightIdleStateLocked("s:alarm");
681 }
682 };
683
684 private final AlarmManager.OnAlarmListener mLightMaintenanceAlarmListener = () -> {
685 if (DEBUG) {
686 Slog.d(TAG, "Light maintenance alarm fired");
687 }
688 synchronized (DeviceIdleController.this) {
689 stepLightIdleStateLocked("s:alarm");
690 }
691 };
692
693 /** AlarmListener to start monitoring motion if there are registered stationary listeners. */
694 private final AlarmManager.OnAlarmListener mMotionRegistrationAlarmListener = () -> {
695 synchronized (DeviceIdleController.this) {
696 if (mStationaryListeners.size() > 0) {
697 startMonitoringMotionLocked();
698 scheduleMotionTimeoutAlarmLocked();
699 }
700 }
701 };
702
703 private final AlarmManager.OnAlarmListener mMotionTimeoutAlarmListener = () -> {
704 synchronized (DeviceIdleController.this) {
705 if (!isStationaryLocked()) {
706 // If the device keeps registering motion, then the alarm should be
707 // rescheduled, so this shouldn't go off until the device is stationary.
708 // This case may happen in a race condition (alarm goes off right before
709 // motion is detected, but handleMotionDetectedLocked is called before
710 // we enter this block).
711 Slog.w(TAG, "motion timeout went off and device isn't stationary");
712 return;
713 }
714 }
715 postStationaryStatusUpdated();
716 };
717
718 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
719 = new AlarmManager.OnAlarmListener() {
720 @Override
721 public void onAlarm() {
722 synchronized (DeviceIdleController.this) {
723 if (mState == STATE_SENSING) {
724 // Restart the device idle progression in case the device moved but the screen
725 // didn't turn on.
726 becomeInactiveIfAppropriateLocked();
727 }
728 }
729 }
730 };
731
732 @VisibleForTesting
733 final AlarmManager.OnAlarmListener mDeepAlarmListener
734 = new AlarmManager.OnAlarmListener() {
735 @Override
736 public void onAlarm() {
737 synchronized (DeviceIdleController.this) {
738 stepIdleStateLocked("s:alarm");
739 }
740 }
741 };
742
743 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
744 @Override public void onReceive(Context context, Intent intent) {
745 // When coming out of a deep idle, we will add in some delay before we allow
746 // the system to settle down and finish the maintenance window. This is
747 // to give a chance for any pending work to be scheduled.
748 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
749 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
750 mConstants.MIN_DEEP_MAINTENANCE_TIME);
751 } else {
752 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
753 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
754 }
755 }
756 };
757
758 private final BroadcastReceiver mInteractivityReceiver = new BroadcastReceiver() {
759 @Override
760 public void onReceive(Context context, Intent intent) {
761 synchronized (DeviceIdleController.this) {
762 updateInteractivityLocked();
763 }
764 }
765 };
766
767 /** Post stationary status only to this listener. */
768 private void postStationaryStatus(DeviceIdleInternal.StationaryListener listener) {
769 mHandler.obtainMessage(MSG_REPORT_STATIONARY_STATUS, listener).sendToTarget();
770 }
771
772 /** Post stationary status to all registered listeners. */
773 private void postStationaryStatusUpdated() {
774 mHandler.sendEmptyMessage(MSG_REPORT_STATIONARY_STATUS);
775 }
776
777 @GuardedBy("this")
778 private boolean isStationaryLocked() {
779 final long now = mInjector.getElapsedRealtime();
780 return mMotionListener.active
781 // Listening for motion for long enough and last motion was long enough ago.
782 && now - Math.max(mMotionListener.activatedTimeElapsed, mLastMotionEventElapsed)
783 >= mConstants.MOTION_INACTIVE_TIMEOUT;
784 }
785
786 @VisibleForTesting
787 void registerStationaryListener(DeviceIdleInternal.StationaryListener listener) {
788 synchronized (this) {
789 if (!mStationaryListeners.add(listener)) {
790 // Listener already registered.
791 return;
792 }
793 postStationaryStatus(listener);
794 if (mMotionListener.active) {
795 if (!isStationaryLocked() && mStationaryListeners.size() == 1) {
796 // First listener to be registered and the device isn't stationary, so we
797 // need to register the alarm to report the device is stationary.
798 scheduleMotionTimeoutAlarmLocked();
799 }
800 } else {
801 startMonitoringMotionLocked();
802 scheduleMotionTimeoutAlarmLocked();
803 }
804 }
805 }
806
807 private void unregisterStationaryListener(DeviceIdleInternal.StationaryListener listener) {
808 synchronized (this) {
809 if (mStationaryListeners.remove(listener) && mStationaryListeners.size() == 0
810 // Motion detection is started when transitioning from INACTIVE to IDLE_PENDING
811 // and so doesn't need to be on for ACTIVE or INACTIVE states.
812 // Motion detection isn't needed when idling due to Quick Doze.
813 && (mState == STATE_ACTIVE || mState == STATE_INACTIVE
814 || mQuickDozeActivated)) {
815 maybeStopMonitoringMotionLocked();
816 }
817 }
818 }
819
820 private void registerTempAllowlistChangeListener(
821 @NonNull PowerAllowlistInternal.TempAllowlistChangeListener listener) {
822 synchronized (this) {
823 mTempAllowlistChangeListeners.add(listener);
824 }
825 }
826
827 private void unregisterTempAllowlistChangeListener(
828 @NonNull PowerAllowlistInternal.TempAllowlistChangeListener listener) {
829 synchronized (this) {
830 mTempAllowlistChangeListeners.remove(listener);
831 }
832 }
833
834 @VisibleForTesting
835 final class MotionListener extends TriggerEventListener
836 implements SensorEventListener {
837
838 boolean active = false;
839
840 /**
841 * Time in the elapsed realtime timebase when this listener was activated. Only valid if
842 * {@link #active} is true.
843 */
844 long activatedTimeElapsed;
845
846 public boolean isActive() {
847 return active;
848 }
849
850 @Override
851 public void onTrigger(TriggerEvent event) {
852 synchronized (DeviceIdleController.this) {
853 // One_shot sensors (which call onTrigger) are unregistered when onTrigger is called
854 active = false;
855 motionLocked();
856 }
857 }
858
859 @Override
860 public void onSensorChanged(SensorEvent event) {
861 synchronized (DeviceIdleController.this) {
862 // Since one_shot sensors are unregistered when onTrigger is called, unregister
863 // listeners here so that the MotionListener is in a consistent state when it calls
864 // out to motionLocked.
865 mSensorManager.unregisterListener(this, mMotionSensor);
866 active = false;
867 motionLocked();
868 }
869 }
870
871 @Override
872 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
873
874 public boolean registerLocked() {
875 boolean success;
876 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
877 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
878 } else {
879 success = mSensorManager.registerListener(
880 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
881 }
882 if (success) {
883 active = true;
884 activatedTimeElapsed = mInjector.getElapsedRealtime();
885 } else {
886 Slog.e(TAG, "Unable to register for " + mMotionSensor);
887 }
888 return success;
889 }
890
891 public void unregisterLocked() {
892 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
893 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
894 } else {
895 mSensorManager.unregisterListener(mMotionListener);
896 }
897 active = false;
898 }
899 }
900 @VisibleForTesting final MotionListener mMotionListener = new MotionListener();
901
902 private final LocationListener mGenericLocationListener = new LocationListener() {
903 @Override
904 public void onLocationChanged(Location location) {
905 synchronized (DeviceIdleController.this) {
906 receivedGenericLocationLocked(location);
907 }
908 }
909
910 @Override
911 public void onStatusChanged(String provider, int status, Bundle extras) {
912 }
913
914 @Override
915 public void onProviderEnabled(String provider) {
916 }
917
918 @Override
919 public void onProviderDisabled(String provider) {
920 }
921 };
922
923 private final LocationListener mGpsLocationListener = new LocationListener() {
924 @Override
925 public void onLocationChanged(Location location) {
926 synchronized (DeviceIdleController.this) {
927 receivedGpsLocationLocked(location);
928 }
929 }
930
931 @Override
932 public void onStatusChanged(String provider, int status, Bundle extras) {
933 }
934
935 @Override
936 public void onProviderEnabled(String provider) {
937 }
938
939 @Override
940 public void onProviderDisabled(String provider) {
941 }
942 };
943
944 /**
945 * All times are in milliseconds. These constants are kept synchronized with the system
946 * global Settings. Any access to this class or its fields should be done while
947 * holding the DeviceIdleController lock.
948 */
949 public final class Constants implements DeviceConfig.OnPropertiesChangedListener {
950 // Key names stored in the settings value.
951 private static final String KEY_FLEX_TIME_SHORT = "flex_time_short";
952 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT =
953 "light_after_inactive_to";
954 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
955 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
956 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
957 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET =
958 "light_idle_maintenance_min_budget";
959 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET =
960 "light_idle_maintenance_max_budget";
961 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
962 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
963 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
964 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
965 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
966 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
967 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
968 private static final String KEY_MOTION_INACTIVE_TIMEOUT_FLEX = "motion_inactive_to_flex";
969 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
970 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
971 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
972 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
973 private static final String KEY_QUICK_DOZE_DELAY_TIMEOUT = "quick_doze_delay_to";
974 private static final String KEY_IDLE_TIMEOUT = "idle_to";
975 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
976 private static final String KEY_IDLE_FACTOR = "idle_factor";
977 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
978 private static final String KEY_MAX_TEMP_APP_ALLOWLIST_DURATION_MS =
979 "max_temp_app_allowlist_duration_ms";
980 private static final String KEY_MMS_TEMP_APP_ALLOWLIST_DURATION_MS =
981 "mms_temp_app_allowlist_duration_ms";
982 private static final String KEY_SMS_TEMP_APP_ALLOWLIST_DURATION_MS =
983 "sms_temp_app_allowlist_duration_ms";
984 private static final String KEY_NOTIFICATION_ALLOWLIST_DURATION_MS =
985 "notification_allowlist_duration_ms";
986 /**
987 * Whether to wait for the user to unlock the device before causing screen-on to
988 * exit doze. Default = true
989 */
990 private static final String KEY_WAIT_FOR_UNLOCK = "wait_for_unlock";
991 private static final String KEY_PRE_IDLE_FACTOR_LONG =
992 "pre_idle_factor_long";
993 private static final String KEY_PRE_IDLE_FACTOR_SHORT =
994 "pre_idle_factor_short";
995 private static final String KEY_USE_WINDOW_ALARMS = "use_window_alarms";
996
997 private long mDefaultFlexTimeShort =
998 !COMPRESS_TIME ? 60 * 1000L : 5 * 1000L;
999 private long mDefaultLightIdleAfterInactiveTimeout =
1000 !COMPRESS_TIME ? 4 * 60 * 1000L : 30 * 1000L;
1001 private long mDefaultLightIdleTimeout =
1002 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L;
1003 private float mDefaultLightIdleFactor = 2f;
1004 private long mDefaultLightMaxIdleTimeout =
1005 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L;
1006 private long mDefaultLightIdleMaintenanceMinBudget =
1007 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L;
1008 private long mDefaultLightIdleMaintenanceMaxBudget =
1009 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L;
1010 private long mDefaultMinLightMaintenanceTime =
1011 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L;
1012 private long mDefaultMinDeepMaintenanceTime =
1013 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L;
1014 private long mDefaultInactiveTimeout =
1015 (30 * 60 * 1000L) / (!COMPRESS_TIME ? 1 : 10);
1016 private static final long DEFAULT_INACTIVE_TIMEOUT_SMALL_BATTERY =
1017 (15 * 60 * 1000L) / (!COMPRESS_TIME ? 1 : 10);
1018 private long mDefaultSensingTimeout =
1019 !COMPRESS_TIME ? 4 * 60 * 1000L : 60 * 1000L;
1020 private long mDefaultLocatingTimeout =
1021 !COMPRESS_TIME ? 30 * 1000L : 15 * 1000L;
1022 private float mDefaultLocationAccuracy = 20f;
1023 private long mDefaultMotionInactiveTimeout =
1024 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L;
1025 private long mDefaultMotionInactiveTimeoutFlex =
1026 !COMPRESS_TIME ? 60 * 1000L : 5 * 1000L;
1027 private long mDefaultIdleAfterInactiveTimeout =
1028 (30 * 60 * 1000L) / (!COMPRESS_TIME ? 1 : 10);
1029 private static final long DEFAULT_IDLE_AFTER_INACTIVE_TIMEOUT_SMALL_BATTERY =
1030 (15 * 60 * 1000L) / (!COMPRESS_TIME ? 1 : 10);
1031 private long mDefaultIdlePendingTimeout =
1032 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L;
1033 private long mDefaultMaxIdlePendingTimeout =
1034 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L;
1035 private float mDefaultIdlePendingFactor = 2f;
1036 private long mDefaultQuickDozeDelayTimeout =
1037 !COMPRESS_TIME ? 60 * 1000L : 15 * 1000L;
1038 private long mDefaultIdleTimeout =
1039 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L;
1040 private long mDefaultMaxIdleTimeout =
1041 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L;
1042 private float mDefaultIdleFactor = 2f;
1043 private long mDefaultMinTimeToAlarm =
1044 !COMPRESS_TIME ? 30 * 60 * 1000L : 6 * 60 * 1000L;
1045 private long mDefaultMaxTempAppAllowlistDurationMs = 5 * 60 * 1000L;
1046 private long mDefaultMmsTempAppAllowlistDurationMs = 60 * 1000L;
1047 private long mDefaultSmsTempAppAllowlistDurationMs = 20 * 1000L;
1048 private long mDefaultNotificationAllowlistDurationMs = 30 * 1000L;
1049 private boolean mDefaultWaitForUnlock = true;
1050 private float mDefaultPreIdleFactorLong = 1.67f;
1051 private float mDefaultPreIdleFactorShort = .33f;
1052 private boolean mDefaultUseWindowAlarms = true;
1053
1054 /**
1055 * A somewhat short alarm window size that we will tolerate for various alarm timings.
1056 *
1057 * @see #KEY_FLEX_TIME_SHORT
1058 */
1059 public long FLEX_TIME_SHORT = mDefaultFlexTimeShort;
1060
1061 /**
1062 * This is the time, after becoming inactive, that we go in to the first
1063 * light-weight idle mode.
1064 *
1065 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
1066 */
1067 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mDefaultLightIdleAfterInactiveTimeout;
1068
1069 /**
1070 * This is the initial time that we will run in light idle maintenance mode.
1071 *
1072 * @see #KEY_LIGHT_IDLE_TIMEOUT
1073 */
1074 public long LIGHT_IDLE_TIMEOUT = mDefaultLightIdleTimeout;
1075
1076 /**
1077 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
1078 *
1079 * @see #KEY_LIGHT_IDLE_FACTOR
1080 */
1081 public float LIGHT_IDLE_FACTOR = mDefaultLightIdleFactor;
1082
1083 /**
1084 * This is the maximum time we will stay in light idle mode.
1085 *
1086 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
1087 */
1088 public long LIGHT_MAX_IDLE_TIMEOUT = mDefaultLightMaxIdleTimeout;
1089
1090 /**
1091 * This is the minimum amount of time we want to make available for maintenance mode
1092 * when lightly idling. That is, we will always have at least this amount of time
1093 * available maintenance before timing out and cutting off maintenance mode.
1094 *
1095 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
1096 */
1097 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mDefaultLightIdleMaintenanceMinBudget;
1098
1099 /**
1100 * This is the maximum amount of time we want to make available for maintenance mode
1101 * when lightly idling. That is, if the system isn't using up its minimum maintenance
1102 * budget and this time is being added to the budget reserve, this is the maximum
1103 * reserve size we will allow to grow and thus the maximum amount of time we will
1104 * allow for the maintenance window.
1105 *
1106 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
1107 */
1108 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mDefaultLightIdleMaintenanceMaxBudget;
1109
1110 /**
1111 * This is the minimum amount of time that we will stay in maintenance mode after
1112 * a light doze. We have this minimum to allow various things to respond to switching
1113 * in to maintenance mode and scheduling their work -- otherwise we may
1114 * see there is nothing to do (no jobs pending) and go out of maintenance
1115 * mode immediately.
1116 *
1117 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
1118 */
1119 public long MIN_LIGHT_MAINTENANCE_TIME = mDefaultMinLightMaintenanceTime;
1120
1121 /**
1122 * This is the minimum amount of time that we will stay in maintenance mode after
1123 * a full doze. We have this minimum to allow various things to respond to switching
1124 * in to maintenance mode and scheduling their work -- otherwise we may
1125 * see there is nothing to do (no jobs pending) and go out of maintenance
1126 * mode immediately.
1127 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
1128 */
1129 public long MIN_DEEP_MAINTENANCE_TIME = mDefaultMinDeepMaintenanceTime;
1130
1131 /**
1132 * This is the time, after becoming inactive, at which we start looking at the
1133 * motion sensor to determine if the device is being left alone. We don't do this
1134 * immediately after going inactive just because we don't want to be continually running
1135 * the motion sensor whenever the screen is off.
1136 * @see #KEY_INACTIVE_TIMEOUT
1137 */
1138 public long INACTIVE_TIMEOUT = mDefaultInactiveTimeout;
1139
1140 /**
1141 * If we don't receive a callback from AnyMotion in this amount of time +
1142 * {@link #LOCATING_TIMEOUT}, we will change from
1143 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
1144 * will be ignored.
1145 * @see #KEY_SENSING_TIMEOUT
1146 */
1147 public long SENSING_TIMEOUT = mDefaultSensingTimeout;
1148
1149 /**
1150 * This is how long we will wait to try to get a good location fix before going in to
1151 * idle mode.
1152 * @see #KEY_LOCATING_TIMEOUT
1153 */
1154 public long LOCATING_TIMEOUT = mDefaultLocatingTimeout;
1155
1156 /**
1157 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
1158 * on to idle. We will be trying to get an accuracy fix at least this good or until
1159 * {@link #LOCATING_TIMEOUT} expires.
1160 * @see #KEY_LOCATION_ACCURACY
1161 */
1162 public float LOCATION_ACCURACY = mDefaultLocationAccuracy;
1163
1164 /**
1165 * This is the time, after seeing motion, that we wait after becoming inactive from
1166 * that until we start looking for motion again.
1167 *
1168 * @see #KEY_MOTION_INACTIVE_TIMEOUT
1169 */
1170 public long MOTION_INACTIVE_TIMEOUT = mDefaultMotionInactiveTimeout;
1171
1172 /**
1173 * This is the alarm window size we will tolerate for motion detection timings.
1174 *
1175 * @see #KEY_MOTION_INACTIVE_TIMEOUT_FLEX
1176 */
1177 public long MOTION_INACTIVE_TIMEOUT_FLEX = mDefaultMotionInactiveTimeoutFlex;
1178
1179 /**
1180 * This is the time, after the inactive timeout elapses, that we will wait looking
1181 * for motion until we truly consider the device to be idle.
1182 *
1183 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
1184 */
1185 public long IDLE_AFTER_INACTIVE_TIMEOUT = mDefaultIdleAfterInactiveTimeout;
1186
1187 /**
1188 * This is the initial time, after being idle, that we will allow ourself to be back
1189 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
1190 * idle.
1191 * @see #KEY_IDLE_PENDING_TIMEOUT
1192 */
1193 public long IDLE_PENDING_TIMEOUT = mDefaultIdlePendingTimeout;
1194
1195 /**
1196 * Maximum pending idle timeout (time spent running) we will be allowed to use.
1197 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
1198 */
1199 public long MAX_IDLE_PENDING_TIMEOUT = mDefaultMaxIdlePendingTimeout;
1200
1201 /**
1202 * Scaling factor to apply to current pending idle timeout each time we cycle through
1203 * that state.
1204 * @see #KEY_IDLE_PENDING_FACTOR
1205 */
1206 public float IDLE_PENDING_FACTOR = mDefaultIdlePendingFactor;
1207
1208 /**
1209 * This is amount of time we will wait from the point where we go into
1210 * STATE_QUICK_DOZE_DELAY until we actually go into STATE_IDLE, while waiting for jobs
1211 * and other current activity to finish.
1212 * @see #KEY_QUICK_DOZE_DELAY_TIMEOUT
1213 */
1214 public long QUICK_DOZE_DELAY_TIMEOUT = mDefaultQuickDozeDelayTimeout;
1215
1216 /**
1217 * This is the initial time that we want to sit in the idle state before waking up
1218 * again to return to pending idle and allowing normal work to run.
1219 * @see #KEY_IDLE_TIMEOUT
1220 */
1221 public long IDLE_TIMEOUT = mDefaultIdleTimeout;
1222
1223 /**
1224 * Maximum idle duration we will be allowed to use.
1225 * @see #KEY_MAX_IDLE_TIMEOUT
1226 */
1227 public long MAX_IDLE_TIMEOUT = mDefaultMaxIdleTimeout;
1228
1229 /**
1230 * Scaling factor to apply to current idle timeout each time we cycle through that state.
1231 * @see #KEY_IDLE_FACTOR
1232 */
1233 public float IDLE_FACTOR = mDefaultIdleFactor;
1234
1235 /**
1236 * This is the minimum time we will allow until the next upcoming alarm for us to
1237 * actually go in to idle mode.
1238 * @see #KEY_MIN_TIME_TO_ALARM
1239 */
1240 public long MIN_TIME_TO_ALARM = mDefaultMinTimeToAlarm;
1241
1242 /**
1243 * Max amount of time to temporarily whitelist an app when it receives a high priority
1244 * tickle.
1245 *
1246 * @see #KEY_MAX_TEMP_APP_ALLOWLIST_DURATION_MS
1247 */
1248 public long MAX_TEMP_APP_ALLOWLIST_DURATION_MS = mDefaultMaxTempAppAllowlistDurationMs;
1249
1250 /**
1251 * Amount of time we would like to whitelist an app that is receiving an MMS.
1252 * @see #KEY_MMS_TEMP_APP_ALLOWLIST_DURATION_MS
1253 */
1254 public long MMS_TEMP_APP_ALLOWLIST_DURATION_MS = mDefaultMmsTempAppAllowlistDurationMs;
1255
1256 /**
1257 * Amount of time we would like to whitelist an app that is receiving an SMS.
1258 * @see #KEY_SMS_TEMP_APP_ALLOWLIST_DURATION_MS
1259 */
1260 public long SMS_TEMP_APP_ALLOWLIST_DURATION_MS = mDefaultSmsTempAppAllowlistDurationMs;
1261
1262 /**
1263 * Amount of time we would like to whitelist an app that is handling a
1264 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
1265 * @see #KEY_NOTIFICATION_ALLOWLIST_DURATION_MS
1266 */
1267 public long NOTIFICATION_ALLOWLIST_DURATION_MS = mDefaultNotificationAllowlistDurationMs;
1268
1269 /**
1270 * Pre idle time factor use to make idle delay longer
1271 */
1272 public float PRE_IDLE_FACTOR_LONG = mDefaultPreIdleFactorLong;
1273
1274 /**
1275 * Pre idle time factor use to make idle delay shorter
1276 */
1277 public float PRE_IDLE_FACTOR_SHORT = mDefaultPreIdleFactorShort;
1278
1279 public boolean WAIT_FOR_UNLOCK = mDefaultWaitForUnlock;
1280
1281 /**
1282 * Whether to use window alarms. True to use window alarms (call AlarmManager.setWindow()).
1283 * False to use the legacy inexact alarms (call AlarmManager.set()).
1284 */
1285 public boolean USE_WINDOW_ALARMS = mDefaultUseWindowAlarms;
1286
1287 private final boolean mSmallBatteryDevice;
1288
1289 public Constants() {
1290 initDefault();
1291 mSmallBatteryDevice = ActivityManager.isSmallBatteryDevice();
1292 if (mSmallBatteryDevice) {
1293 INACTIVE_TIMEOUT = DEFAULT_INACTIVE_TIMEOUT_SMALL_BATTERY;
1294 IDLE_AFTER_INACTIVE_TIMEOUT = DEFAULT_IDLE_AFTER_INACTIVE_TIMEOUT_SMALL_BATTERY;
1295 }
1296 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_DEVICE_IDLE,
1297 JobSchedulerBackgroundThread.getExecutor(), this);
1298 // Load all the constants.
1299 onPropertiesChanged(DeviceConfig.getProperties(DeviceConfig.NAMESPACE_DEVICE_IDLE));
1300 }
1301
1302 private void initDefault() {
1303 final Resources res = getContext().getResources();
1304
1305 mDefaultFlexTimeShort = getTimeout(
1306 res.getInteger(com.android.internal.R.integer.device_idle_flex_time_short_ms),
1307 mDefaultFlexTimeShort);
1308 mDefaultLightIdleAfterInactiveTimeout = getTimeout(res.getInteger(
1309 com.android.internal.R.integer.device_idle_light_after_inactive_to_ms),
1310 mDefaultLightIdleAfterInactiveTimeout);
1311 mDefaultLightIdleTimeout = getTimeout(
1312 res.getInteger(com.android.internal.R.integer.device_idle_light_idle_to_ms),
1313 mDefaultLightIdleTimeout);
1314 mDefaultLightIdleFactor = res.getFloat(
1315 com.android.internal.R.integer.device_idle_light_idle_factor);
1316 mDefaultLightMaxIdleTimeout = getTimeout(
1317 res.getInteger(com.android.internal.R.integer.device_idle_light_max_idle_to_ms),
1318 mDefaultLightMaxIdleTimeout);
1319 mDefaultLightIdleMaintenanceMinBudget = getTimeout(res.getInteger(
1320 com.android.internal.R.integer.device_idle_light_idle_maintenance_min_budget_ms
1321 ), mDefaultLightIdleMaintenanceMinBudget);
1322 mDefaultLightIdleMaintenanceMaxBudget = getTimeout(res.getInteger(
1323 com.android.internal.R.integer.device_idle_light_idle_maintenance_max_budget_ms
1324 ), mDefaultLightIdleMaintenanceMaxBudget);
1325 mDefaultMinLightMaintenanceTime = getTimeout(res.getInteger(
1326 com.android.internal.R.integer.device_idle_min_light_maintenance_time_ms),
1327 mDefaultMinLightMaintenanceTime);
1328 mDefaultMinDeepMaintenanceTime = getTimeout(res.getInteger(
1329 com.android.internal.R.integer.device_idle_min_deep_maintenance_time_ms),
1330 mDefaultMinDeepMaintenanceTime);
1331 mDefaultInactiveTimeout = getTimeout(
1332 res.getInteger(com.android.internal.R.integer.device_idle_inactive_to_ms),
1333 mDefaultInactiveTimeout);
1334 mDefaultSensingTimeout = getTimeout(
1335 res.getInteger(com.android.internal.R.integer.device_idle_sensing_to_ms),
1336 mDefaultSensingTimeout);
1337 mDefaultLocatingTimeout = getTimeout(
1338 res.getInteger(com.android.internal.R.integer.device_idle_locating_to_ms),
1339 mDefaultLocatingTimeout);
1340 mDefaultLocationAccuracy = res.getFloat(
1341 com.android.internal.R.integer.device_idle_location_accuracy);
1342 mDefaultMotionInactiveTimeout = getTimeout(res.getInteger(
1343 com.android.internal.R.integer.device_idle_motion_inactive_to_ms),
1344 mDefaultMotionInactiveTimeout);
1345 mDefaultMotionInactiveTimeoutFlex = getTimeout(res.getInteger(
1346 com.android.internal.R.integer.device_idle_motion_inactive_to_flex_ms),
1347 mDefaultMotionInactiveTimeoutFlex);
1348 mDefaultIdleAfterInactiveTimeout = getTimeout(res.getInteger(
1349 com.android.internal.R.integer.device_idle_idle_after_inactive_to_ms),
1350 mDefaultIdleAfterInactiveTimeout);
1351 mDefaultIdlePendingTimeout = getTimeout(
1352 res.getInteger(com.android.internal.R.integer.device_idle_idle_pending_to_ms),
1353 mDefaultIdlePendingTimeout);
1354 mDefaultMaxIdlePendingTimeout = getTimeout(res.getInteger(
1355 com.android.internal.R.integer.device_idle_max_idle_pending_to_ms),
1356 mDefaultMaxIdlePendingTimeout);
1357 mDefaultIdlePendingFactor = res.getFloat(
1358 com.android.internal.R.integer.device_idle_idle_pending_factor);
1359 mDefaultQuickDozeDelayTimeout = getTimeout(res.getInteger(
1360 com.android.internal.R.integer.device_idle_quick_doze_delay_to_ms),
1361 mDefaultQuickDozeDelayTimeout);
1362 mDefaultIdleTimeout = getTimeout(
1363 res.getInteger(com.android.internal.R.integer.device_idle_idle_to_ms),
1364 mDefaultIdleTimeout);
1365 mDefaultMaxIdleTimeout = getTimeout(
1366 res.getInteger(com.android.internal.R.integer.device_idle_max_idle_to_ms),
1367 mDefaultMaxIdleTimeout);
1368 mDefaultIdleFactor = res.getFloat(
1369 com.android.internal.R.integer.device_idle_idle_factor);
1370 mDefaultMinTimeToAlarm = getTimeout(res.getInteger(
1371 com.android.internal.R.integer.device_idle_min_time_to_alarm_ms),
1372 mDefaultMinTimeToAlarm);
1373 mDefaultMaxTempAppAllowlistDurationMs = res.getInteger(
1374 com.android.internal.R.integer.device_idle_max_temp_app_allowlist_duration_ms);
1375 mDefaultMmsTempAppAllowlistDurationMs = res.getInteger(
1376 com.android.internal.R.integer.device_idle_mms_temp_app_allowlist_duration_ms);
1377 mDefaultSmsTempAppAllowlistDurationMs = res.getInteger(
1378 com.android.internal.R.integer.device_idle_sms_temp_app_allowlist_duration_ms);
1379 mDefaultNotificationAllowlistDurationMs = res.getInteger(
1380 com.android.internal.R.integer.device_idle_notification_allowlist_duration_ms);
1381 mDefaultWaitForUnlock = res.getBoolean(
1382 com.android.internal.R.bool.device_idle_wait_for_unlock);
1383 mDefaultPreIdleFactorLong = res.getFloat(
1384 com.android.internal.R.integer.device_idle_pre_idle_factor_long);
1385 mDefaultPreIdleFactorShort = res.getFloat(
1386 com.android.internal.R.integer.device_idle_pre_idle_factor_short);
1387 mDefaultUseWindowAlarms = res.getBoolean(
1388 com.android.internal.R.bool.device_idle_use_window_alarms);
1389
1390 FLEX_TIME_SHORT = mDefaultFlexTimeShort;
1391 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mDefaultLightIdleAfterInactiveTimeout;
1392 LIGHT_IDLE_TIMEOUT = mDefaultLightIdleTimeout;
1393 LIGHT_IDLE_FACTOR = mDefaultLightIdleFactor;
1394 LIGHT_MAX_IDLE_TIMEOUT = mDefaultLightMaxIdleTimeout;
1395 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mDefaultLightIdleMaintenanceMinBudget;
1396 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mDefaultLightIdleMaintenanceMaxBudget;
1397 MIN_LIGHT_MAINTENANCE_TIME = mDefaultMinLightMaintenanceTime;
1398 MIN_DEEP_MAINTENANCE_TIME = mDefaultMinDeepMaintenanceTime;
1399 INACTIVE_TIMEOUT = mDefaultInactiveTimeout;
1400 SENSING_TIMEOUT = mDefaultSensingTimeout;
1401 LOCATING_TIMEOUT = mDefaultLocatingTimeout;
1402 LOCATION_ACCURACY = mDefaultLocationAccuracy;
1403 MOTION_INACTIVE_TIMEOUT = mDefaultMotionInactiveTimeout;
1404 MOTION_INACTIVE_TIMEOUT_FLEX = mDefaultMotionInactiveTimeoutFlex;
1405 IDLE_AFTER_INACTIVE_TIMEOUT = mDefaultIdleAfterInactiveTimeout;
1406 IDLE_PENDING_TIMEOUT = mDefaultIdlePendingTimeout;
1407 MAX_IDLE_PENDING_TIMEOUT = mDefaultMaxIdlePendingTimeout;
1408 IDLE_PENDING_FACTOR = mDefaultIdlePendingFactor;
1409 QUICK_DOZE_DELAY_TIMEOUT = mDefaultQuickDozeDelayTimeout;
1410 IDLE_TIMEOUT = mDefaultIdleTimeout;
1411 MAX_IDLE_TIMEOUT = mDefaultMaxIdleTimeout;
1412 IDLE_FACTOR = mDefaultIdleFactor;
1413 MIN_TIME_TO_ALARM = mDefaultMinTimeToAlarm;
1414 MAX_TEMP_APP_ALLOWLIST_DURATION_MS = mDefaultMaxTempAppAllowlistDurationMs;
1415 MMS_TEMP_APP_ALLOWLIST_DURATION_MS = mDefaultMmsTempAppAllowlistDurationMs;
1416 SMS_TEMP_APP_ALLOWLIST_DURATION_MS = mDefaultSmsTempAppAllowlistDurationMs;
1417 NOTIFICATION_ALLOWLIST_DURATION_MS = mDefaultNotificationAllowlistDurationMs;
1418 WAIT_FOR_UNLOCK = mDefaultWaitForUnlock;
1419 PRE_IDLE_FACTOR_LONG = mDefaultPreIdleFactorLong;
1420 PRE_IDLE_FACTOR_SHORT = mDefaultPreIdleFactorShort;
1421 USE_WINDOW_ALARMS = mDefaultUseWindowAlarms;
1422 }
1423
1424 private long getTimeout(long defTimeout, long compTimeout) {
1425 return (!COMPRESS_TIME || defTimeout < compTimeout) ? defTimeout : compTimeout;
1426 }
1427
1428
1429 @Override
1430 public void onPropertiesChanged(DeviceConfig.Properties properties) {
1431 synchronized (DeviceIdleController.this) {
1432 for (String name : properties.getKeyset()) {
1433 if (name == null) {
1434 continue;
1435 }
1436 switch (name) {
1437 case KEY_FLEX_TIME_SHORT:
1438 FLEX_TIME_SHORT = properties.getLong(
1439 KEY_FLEX_TIME_SHORT, mDefaultFlexTimeShort);
1440 break;
1441 case KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT:
1442 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = properties.getLong(
1443 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
1444 mDefaultLightIdleAfterInactiveTimeout);
1445 break;
1446 case KEY_LIGHT_IDLE_TIMEOUT:
1447 LIGHT_IDLE_TIMEOUT = properties.getLong(
1448 KEY_LIGHT_IDLE_TIMEOUT, mDefaultLightIdleTimeout);
1449 break;
1450 case KEY_LIGHT_IDLE_FACTOR:
1451 LIGHT_IDLE_FACTOR = Math.max(1, properties.getFloat(
1452 KEY_LIGHT_IDLE_FACTOR, mDefaultLightIdleFactor));
1453 break;
1454 case KEY_LIGHT_MAX_IDLE_TIMEOUT:
1455 LIGHT_MAX_IDLE_TIMEOUT = properties.getLong(
1456 KEY_LIGHT_MAX_IDLE_TIMEOUT, mDefaultLightMaxIdleTimeout);
1457 break;
1458 case KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET:
1459 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = properties.getLong(
1460 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
1461 mDefaultLightIdleMaintenanceMinBudget);
1462 break;
1463 case KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET:
1464 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = properties.getLong(
1465 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
1466 mDefaultLightIdleMaintenanceMaxBudget);
1467 break;
1468 case KEY_MIN_LIGHT_MAINTENANCE_TIME:
1469 MIN_LIGHT_MAINTENANCE_TIME = properties.getLong(
1470 KEY_MIN_LIGHT_MAINTENANCE_TIME,
1471 mDefaultMinLightMaintenanceTime);
1472 break;
1473 case KEY_MIN_DEEP_MAINTENANCE_TIME:
1474 MIN_DEEP_MAINTENANCE_TIME = properties.getLong(
1475 KEY_MIN_DEEP_MAINTENANCE_TIME,
1476 mDefaultMinDeepMaintenanceTime);
1477 break;
1478 case KEY_INACTIVE_TIMEOUT:
1479 final long defaultInactiveTimeout = mSmallBatteryDevice
1480 ? DEFAULT_INACTIVE_TIMEOUT_SMALL_BATTERY
1481 : mDefaultInactiveTimeout;
1482 INACTIVE_TIMEOUT = properties.getLong(
1483 KEY_INACTIVE_TIMEOUT, defaultInactiveTimeout);
1484 break;
1485 case KEY_SENSING_TIMEOUT:
1486 SENSING_TIMEOUT = properties.getLong(
1487 KEY_SENSING_TIMEOUT, mDefaultSensingTimeout);
1488 break;
1489 case KEY_LOCATING_TIMEOUT:
1490 LOCATING_TIMEOUT = properties.getLong(
1491 KEY_LOCATING_TIMEOUT, mDefaultLocatingTimeout);
1492 break;
1493 case KEY_LOCATION_ACCURACY:
1494 LOCATION_ACCURACY = properties.getFloat(
1495 KEY_LOCATION_ACCURACY, mDefaultLocationAccuracy);
1496 break;
1497 case KEY_MOTION_INACTIVE_TIMEOUT:
1498 MOTION_INACTIVE_TIMEOUT = properties.getLong(
1499 KEY_MOTION_INACTIVE_TIMEOUT, mDefaultMotionInactiveTimeout);
1500 break;
1501 case KEY_MOTION_INACTIVE_TIMEOUT_FLEX:
1502 MOTION_INACTIVE_TIMEOUT_FLEX = properties.getLong(
1503 KEY_MOTION_INACTIVE_TIMEOUT_FLEX,
1504 mDefaultMotionInactiveTimeoutFlex);
1505 break;
1506 case KEY_IDLE_AFTER_INACTIVE_TIMEOUT:
1507 final long defaultIdleAfterInactiveTimeout = mSmallBatteryDevice
1508 ? DEFAULT_IDLE_AFTER_INACTIVE_TIMEOUT_SMALL_BATTERY
1509 : mDefaultIdleAfterInactiveTimeout;
1510 IDLE_AFTER_INACTIVE_TIMEOUT = properties.getLong(
1511 KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
1512 defaultIdleAfterInactiveTimeout);
1513 break;
1514 case KEY_IDLE_PENDING_TIMEOUT:
1515 IDLE_PENDING_TIMEOUT = properties.getLong(
1516 KEY_IDLE_PENDING_TIMEOUT, mDefaultIdlePendingTimeout);
1517 break;
1518 case KEY_MAX_IDLE_PENDING_TIMEOUT:
1519 MAX_IDLE_PENDING_TIMEOUT = properties.getLong(
1520 KEY_MAX_IDLE_PENDING_TIMEOUT, mDefaultMaxIdlePendingTimeout);
1521 break;
1522 case KEY_IDLE_PENDING_FACTOR:
1523 IDLE_PENDING_FACTOR = properties.getFloat(
1524 KEY_IDLE_PENDING_FACTOR, mDefaultIdlePendingFactor);
1525 break;
1526 case KEY_QUICK_DOZE_DELAY_TIMEOUT:
1527 QUICK_DOZE_DELAY_TIMEOUT = properties.getLong(
1528 KEY_QUICK_DOZE_DELAY_TIMEOUT, mDefaultQuickDozeDelayTimeout);
1529 break;
1530 case KEY_IDLE_TIMEOUT:
1531 IDLE_TIMEOUT = properties.getLong(
1532 KEY_IDLE_TIMEOUT, mDefaultIdleTimeout);
1533 break;
1534 case KEY_MAX_IDLE_TIMEOUT:
1535 MAX_IDLE_TIMEOUT = properties.getLong(
1536 KEY_MAX_IDLE_TIMEOUT, mDefaultMaxIdleTimeout);
1537 break;
1538 case KEY_IDLE_FACTOR:
1539 IDLE_FACTOR = properties.getFloat(KEY_IDLE_FACTOR, mDefaultIdleFactor);
1540 break;
1541 case KEY_MIN_TIME_TO_ALARM:
1542 MIN_TIME_TO_ALARM = properties.getLong(
1543 KEY_MIN_TIME_TO_ALARM, mDefaultMinTimeToAlarm);
1544 break;
1545 case KEY_MAX_TEMP_APP_ALLOWLIST_DURATION_MS:
1546 MAX_TEMP_APP_ALLOWLIST_DURATION_MS = properties.getLong(
1547 KEY_MAX_TEMP_APP_ALLOWLIST_DURATION_MS,
1548 mDefaultMaxTempAppAllowlistDurationMs);
1549 break;
1550 case KEY_MMS_TEMP_APP_ALLOWLIST_DURATION_MS:
1551 MMS_TEMP_APP_ALLOWLIST_DURATION_MS = properties.getLong(
1552 KEY_MMS_TEMP_APP_ALLOWLIST_DURATION_MS,
1553 mDefaultMmsTempAppAllowlistDurationMs);
1554 break;
1555 case KEY_SMS_TEMP_APP_ALLOWLIST_DURATION_MS:
1556 SMS_TEMP_APP_ALLOWLIST_DURATION_MS = properties.getLong(
1557 KEY_SMS_TEMP_APP_ALLOWLIST_DURATION_MS,
1558 mDefaultSmsTempAppAllowlistDurationMs);
1559 break;
1560 case KEY_NOTIFICATION_ALLOWLIST_DURATION_MS:
1561 NOTIFICATION_ALLOWLIST_DURATION_MS = properties.getLong(
1562 KEY_NOTIFICATION_ALLOWLIST_DURATION_MS,
1563 mDefaultNotificationAllowlistDurationMs);
1564 break;
1565 case KEY_WAIT_FOR_UNLOCK:
1566 WAIT_FOR_UNLOCK = properties.getBoolean(
1567 KEY_WAIT_FOR_UNLOCK, mDefaultWaitForUnlock);
1568 break;
1569 case KEY_PRE_IDLE_FACTOR_LONG:
1570 PRE_IDLE_FACTOR_LONG = properties.getFloat(
1571 KEY_PRE_IDLE_FACTOR_LONG, mDefaultPreIdleFactorLong);
1572 break;
1573 case KEY_PRE_IDLE_FACTOR_SHORT:
1574 PRE_IDLE_FACTOR_SHORT = properties.getFloat(
1575 KEY_PRE_IDLE_FACTOR_SHORT, mDefaultPreIdleFactorShort);
1576 break;
1577 case KEY_USE_WINDOW_ALARMS:
1578 USE_WINDOW_ALARMS = properties.getBoolean(
1579 KEY_USE_WINDOW_ALARMS, mDefaultUseWindowAlarms);
1580 break;
1581 default:
1582 Slog.e(TAG, "Unknown configuration key: " + name);
1583 break;
1584 }
1585 }
1586 }
1587 }
1588
1589 void dump(PrintWriter pw) {
1590 pw.println(" Settings:");
1591
1592 pw.print(" "); pw.print(KEY_FLEX_TIME_SHORT); pw.print("=");
1593 TimeUtils.formatDuration(FLEX_TIME_SHORT, pw);
1594 pw.println();
1595
1596 pw.print(" ");
1597 pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
1598 pw.print("=");
1599 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1600 pw.println();
1601
1602 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
1603 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
1604 pw.println();
1605
1606 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
1607 pw.print(LIGHT_IDLE_FACTOR);
1608 pw.println();
1609
1610 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
1611 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
1612 pw.println();
1613
1614 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
1615 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
1616 pw.println();
1617
1618 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
1619 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
1620 pw.println();
1621
1622 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
1623 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
1624 pw.println();
1625
1626 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
1627 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
1628 pw.println();
1629
1630 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
1631 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
1632 pw.println();
1633
1634 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
1635 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
1636 pw.println();
1637
1638 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
1639 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
1640 pw.println();
1641
1642 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
1643 pw.print(LOCATION_ACCURACY); pw.print("m");
1644 pw.println();
1645
1646 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
1647 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
1648 pw.println();
1649
1650 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT_FLEX); pw.print("=");
1651 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT_FLEX, pw);
1652 pw.println();
1653
1654 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
1655 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1656 pw.println();
1657
1658 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
1659 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
1660 pw.println();
1661
1662 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
1663 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
1664 pw.println();
1665
1666 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
1667 pw.println(IDLE_PENDING_FACTOR);
1668
1669 pw.print(" "); pw.print(KEY_QUICK_DOZE_DELAY_TIMEOUT); pw.print("=");
1670 TimeUtils.formatDuration(QUICK_DOZE_DELAY_TIMEOUT, pw);
1671 pw.println();
1672
1673 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
1674 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
1675 pw.println();
1676
1677 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
1678 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
1679 pw.println();
1680
1681 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
1682 pw.println(IDLE_FACTOR);
1683
1684 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
1685 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
1686 pw.println();
1687
1688 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_ALLOWLIST_DURATION_MS); pw.print("=");
1689 TimeUtils.formatDuration(MAX_TEMP_APP_ALLOWLIST_DURATION_MS, pw);
1690 pw.println();
1691
1692 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_ALLOWLIST_DURATION_MS); pw.print("=");
1693 TimeUtils.formatDuration(MMS_TEMP_APP_ALLOWLIST_DURATION_MS, pw);
1694 pw.println();
1695
1696 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_ALLOWLIST_DURATION_MS); pw.print("=");
1697 TimeUtils.formatDuration(SMS_TEMP_APP_ALLOWLIST_DURATION_MS, pw);
1698 pw.println();
1699
1700 pw.print(" "); pw.print(KEY_NOTIFICATION_ALLOWLIST_DURATION_MS); pw.print("=");
1701 TimeUtils.formatDuration(NOTIFICATION_ALLOWLIST_DURATION_MS, pw);
1702 pw.println();
1703
1704 pw.print(" "); pw.print(KEY_WAIT_FOR_UNLOCK); pw.print("=");
1705 pw.println(WAIT_FOR_UNLOCK);
1706
1707 pw.print(" "); pw.print(KEY_PRE_IDLE_FACTOR_LONG); pw.print("=");
1708 pw.println(PRE_IDLE_FACTOR_LONG);
1709
1710 pw.print(" "); pw.print(KEY_PRE_IDLE_FACTOR_SHORT); pw.print("=");
1711 pw.println(PRE_IDLE_FACTOR_SHORT);
1712
1713 pw.print(" "); pw.print(KEY_USE_WINDOW_ALARMS); pw.print("=");
1714 pw.println(USE_WINDOW_ALARMS);
1715 }
1716 }
1717
1718 private Constants mConstants;
1719
1720 @Override
1721 public void onAnyMotionResult(int result) {
1722 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
1723 synchronized (this) {
1724 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
1725 cancelSensingTimeoutAlarmLocked();
1726 }
1727 if ((result == AnyMotionDetector.RESULT_MOVED)
1728 || (result == AnyMotionDetector.RESULT_UNKNOWN)) {
1729 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
1730 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
1731 if (mState == STATE_SENSING) {
1732 // If we are currently sensing, it is time to move to locating.
1733 mNotMoving = true;
1734 stepIdleStateLocked("s:stationary");
1735 } else if (mState == STATE_LOCATING) {
1736 // If we are currently locating, note that we are not moving and step
1737 // if we have located the position.
1738 mNotMoving = true;
1739 if (mLocated) {
1740 stepIdleStateLocked("s:stationary");
1741 }
1742 }
1743 }
1744 }
1745 }
1746
1747 private static final int MSG_WRITE_CONFIG = 1;
1748 private static final int MSG_REPORT_IDLE_ON = 2;
1749 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1750 private static final int MSG_REPORT_IDLE_OFF = 4;
1751 private static final int MSG_REPORT_ACTIVE = 5;
1752 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1753 @VisibleForTesting
1754 static final int MSG_REPORT_STATIONARY_STATUS = 7;
1755 private static final int MSG_FINISH_IDLE_OP = 8;
1756 private static final int MSG_SEND_CONSTRAINT_MONITORING = 10;
1757 @VisibleForTesting
1758 static final int MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR = 11;
1759 @VisibleForTesting
1760 static final int MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR = 12;
1761 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 13;
1762 private static final int MSG_REPORT_TEMP_APP_WHITELIST_ADDED_TO_NPMS = 14;
1763 private static final int MSG_REPORT_TEMP_APP_WHITELIST_REMOVED_TO_NPMS = 15;
1764
1765 final class MyHandler extends Handler {
1766 MyHandler(Looper looper) {
1767 super(looper);
1768 }
1769
1770 @Override public void handleMessage(Message msg) {
1771 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
1772 switch (msg.what) {
1773 case MSG_WRITE_CONFIG: {
1774 // Does not hold a wakelock. Just let this happen whenever.
1775 handleWriteConfigFile();
1776 } break;
1777 case MSG_REPORT_IDLE_ON:
1778 case MSG_REPORT_IDLE_ON_LIGHT: {
1779 // mGoingIdleWakeLock is held at this point
1780 EventLogTags.writeDeviceIdleOnStart();
1781 final boolean deepChanged;
1782 final boolean lightChanged;
1783 if (msg.what == MSG_REPORT_IDLE_ON) {
1784 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
1785 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1786 } else {
1787 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
1788 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1789 }
1790 try {
1791 mNetworkPolicyManager.setDeviceIdleMode(true);
1792 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
1793 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
1794 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
1795 } catch (RemoteException e) {
1796 }
1797 if (deepChanged) {
1798 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1799 }
1800 if (lightChanged) {
1801 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1802 }
1803 EventLogTags.writeDeviceIdleOnComplete();
1804 mGoingIdleWakeLock.release();
1805 } break;
1806 case MSG_REPORT_IDLE_OFF: {
1807 // mActiveIdleWakeLock is held at this point
1808 EventLogTags.writeDeviceIdleOffStart("unknown");
1809 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
1810 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1811 try {
1812 mNetworkPolicyManager.setDeviceIdleMode(false);
1813 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1814 null, Process.myUid());
1815 } catch (RemoteException e) {
1816 }
1817 if (deepChanged) {
1818 incActiveIdleOps();
1819 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1820 null, mIdleStartedDoneReceiver, null, 0, null, null);
1821 }
1822 if (lightChanged) {
1823 incActiveIdleOps();
1824 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1825 null, mIdleStartedDoneReceiver, null, 0, null, null);
1826 }
1827 // Always start with one active op for the message being sent here.
1828 // Now we are done!
1829 decActiveIdleOps();
1830 EventLogTags.writeDeviceIdleOffComplete();
1831 } break;
1832 case MSG_REPORT_ACTIVE: {
1833 // The device is awake at this point, so no wakelock necessary.
1834 String activeReason = (String)msg.obj;
1835 int activeUid = msg.arg1;
1836 EventLogTags.writeDeviceIdleOffStart(
1837 activeReason != null ? activeReason : "unknown");
1838 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
1839 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1840 try {
1841 mNetworkPolicyManager.setDeviceIdleMode(false);
1842 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1843 activeReason, activeUid);
1844 } catch (RemoteException e) {
1845 }
1846 if (deepChanged) {
1847 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1848 }
1849 if (lightChanged) {
1850 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1851 }
1852 EventLogTags.writeDeviceIdleOffComplete();
1853 } break;
1854 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
1855 // TODO: What is keeping the device awake at this point? Does it need to be?
1856 int uid = msg.arg1;
1857 checkTempAppWhitelistTimeout(uid);
1858 } break;
1859 case MSG_FINISH_IDLE_OP: {
1860 // mActiveIdleWakeLock is held at this point
1861 decActiveIdleOps();
1862 } break;
1863 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1864 final int uid = msg.arg1;
1865 final boolean added = (msg.arg2 == 1);
1866 PowerAllowlistInternal.TempAllowlistChangeListener[] listeners;
1867 synchronized (DeviceIdleController.this) {
1868 listeners = mTempAllowlistChangeListeners.toArray(
1869 new PowerAllowlistInternal.TempAllowlistChangeListener[
1870 mTempAllowlistChangeListeners.size()]);
1871 }
1872 for (PowerAllowlistInternal.TempAllowlistChangeListener listener : listeners) {
1873 if (added) {
1874 listener.onAppAdded(uid);
1875 } else {
1876 listener.onAppRemoved(uid);
1877 }
1878 }
1879 } break;
1880 case MSG_REPORT_TEMP_APP_WHITELIST_ADDED_TO_NPMS: {
1881 final int appId = msg.arg1;
1882 final int reasonCode = msg.arg2;
1883 final String reason = (String) msg.obj;
1884 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true,
1885 reasonCode, reason);
1886 } break;
1887 case MSG_REPORT_TEMP_APP_WHITELIST_REMOVED_TO_NPMS: {
1888 final int appId = msg.arg1;
1889 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, false,
1890 REASON_UNKNOWN, /* reason= */ null);
1891 } break;
1892 case MSG_SEND_CONSTRAINT_MONITORING: {
1893 final IDeviceIdleConstraint constraint = (IDeviceIdleConstraint) msg.obj;
1894 final boolean monitoring = (msg.arg1 == 1);
1895 if (monitoring) {
1896 constraint.startMonitoring();
1897 } else {
1898 constraint.stopMonitoring();
1899 }
1900 } break;
1901 case MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR: {
1902 updatePreIdleFactor();
1903 } break;
1904 case MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR: {
1905 updatePreIdleFactor();
1906 maybeDoImmediateMaintenance();
1907 } break;
1908 case MSG_REPORT_STATIONARY_STATUS: {
1909 final DeviceIdleInternal.StationaryListener newListener =
1910 (DeviceIdleInternal.StationaryListener) msg.obj;
1911 final DeviceIdleInternal.StationaryListener[] listeners;
1912 final boolean isStationary;
1913 synchronized (DeviceIdleController.this) {
1914 isStationary = isStationaryLocked();
1915 if (newListener == null) {
1916 // Only notify all listeners if we aren't directing to one listener.
1917 listeners = mStationaryListeners.toArray(
1918 new DeviceIdleInternal.StationaryListener[
1919 mStationaryListeners.size()]);
1920 } else {
1921 listeners = null;
1922 }
1923 }
1924 if (listeners != null) {
1925 for (DeviceIdleInternal.StationaryListener listener : listeners) {
1926 listener.onDeviceStationaryChanged(isStationary);
1927 }
1928 }
1929 if (newListener != null) {
1930 newListener.onDeviceStationaryChanged(isStationary);
1931 }
1932 }
1933 break;
1934 }
1935 }
1936 }
1937
1938 final MyHandler mHandler;
1939
1940 BinderService mBinderService;
1941
1942 private final class BinderService extends IDeviceIdleController.Stub {
1943 @Override public void addPowerSaveWhitelistApp(String name) {
1944 if (DEBUG) {
1945 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1946 }
1947 addPowerSaveWhitelistApps(Collections.singletonList(name));
1948 }
1949
1950 @Override
1951 public int addPowerSaveWhitelistApps(List<String> packageNames) {
1952 if (DEBUG) {
1953 Slog.i(TAG,
1954 "addPowerSaveWhitelistApps(name = " + packageNames + ")");
1955 }
1956 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1957 null);
1958 final long ident = Binder.clearCallingIdentity();
1959 try {
1960 return addPowerSaveWhitelistAppsInternal(packageNames);
1961 } finally {
1962 Binder.restoreCallingIdentity(ident);
1963 }
1964 }
1965
1966 @Override public void removePowerSaveWhitelistApp(String name) {
1967 if (DEBUG) {
1968 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1969 }
1970 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1971 null);
1972 final long ident = Binder.clearCallingIdentity();
1973 try {
1974 if (!removePowerSaveWhitelistAppInternal(name)
1975 && mPowerSaveWhitelistAppsExceptIdle.containsKey(name)) {
1976 throw new UnsupportedOperationException("Cannot remove system whitelisted app");
1977 }
1978 } finally {
1979 Binder.restoreCallingIdentity(ident);
1980 }
1981 }
1982
1983 @Override public void removeSystemPowerWhitelistApp(String name) {
1984 if (DEBUG) {
1985 Slog.d(TAG, "removeAppFromSystemWhitelist(name = " + name + ")");
1986 }
1987 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1988 null);
1989 final long ident = Binder.clearCallingIdentity();
1990 try {
1991 removeSystemPowerWhitelistAppInternal(name);
1992 } finally {
1993 Binder.restoreCallingIdentity(ident);
1994 }
1995 }
1996
1997 @Override public void restoreSystemPowerWhitelistApp(String name) {
1998 if (DEBUG) {
1999 Slog.d(TAG, "restoreAppToSystemWhitelist(name = " + name + ")");
2000 }
2001 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2002 null);
2003 final long ident = Binder.clearCallingIdentity();
2004 try {
2005 restoreSystemPowerWhitelistAppInternal(name);
2006 } finally {
2007 Binder.restoreCallingIdentity(ident);
2008 }
2009 }
2010
2011 public String[] getRemovedSystemPowerWhitelistApps() {
2012 return getRemovedSystemPowerWhitelistAppsInternal(
2013 Binder.getCallingUid(), UserHandle.getCallingUserId());
2014 }
2015
2016 @Override public String[] getSystemPowerWhitelistExceptIdle() {
2017 return getSystemPowerWhitelistExceptIdleInternal(
2018 Binder.getCallingUid(), UserHandle.getCallingUserId());
2019 }
2020
2021 @Override public String[] getSystemPowerWhitelist() {
2022 return getSystemPowerWhitelistInternal(
2023 Binder.getCallingUid(), UserHandle.getCallingUserId());
2024 }
2025
2026 @Override public String[] getUserPowerWhitelist() {
2027 return getUserPowerWhitelistInternal(
2028 Binder.getCallingUid(), UserHandle.getCallingUserId());
2029 }
2030
2031 @Override public String[] getFullPowerWhitelistExceptIdle() {
2032 return getFullPowerWhitelistExceptIdleInternal(
2033 Binder.getCallingUid(), UserHandle.getCallingUserId());
2034 }
2035
2036 @Override public String[] getFullPowerWhitelist() {
2037 return getFullPowerWhitelistInternal(
2038 Binder.getCallingUid(), UserHandle.getCallingUserId());
2039 }
2040
2041 @Override public int[] getAppIdWhitelistExceptIdle() {
2042 return getAppIdWhitelistExceptIdleInternal();
2043 }
2044
2045 @Override public int[] getAppIdWhitelist() {
2046 return getAppIdWhitelistInternal();
2047 }
2048
2049 @Override public int[] getAppIdUserWhitelist() {
2050 return getAppIdUserWhitelistInternal();
2051 }
2052
2053 @Override public int[] getAppIdTempWhitelist() {
2054 return getAppIdTempWhitelistInternal();
2055 }
2056
2057 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
2058 if (mPackageManagerInternal
2059 .filterAppAccess(name, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
2060 return false;
2061 }
2062 return isPowerSaveWhitelistExceptIdleAppInternal(name);
2063 }
2064
2065 @Override public boolean isPowerSaveWhitelistApp(String name) {
2066 if (mPackageManagerInternal
2067 .filterAppAccess(name, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
2068 return false;
2069 }
2070 return isPowerSaveWhitelistAppInternal(name);
2071 }
2072
2073 @Override
2074 public long whitelistAppTemporarily(String packageName, int userId,
2075 @ReasonCode int reasonCode, @Nullable String reason) throws RemoteException {
2076 // At least 10 seconds.
2077 long durationMs = Math.max(10_000L, mConstants.MAX_TEMP_APP_ALLOWLIST_DURATION_MS / 2);
2078 addPowerSaveTempAllowlistAppChecked(packageName, durationMs, userId, reasonCode,
2079 reason);
2080 return durationMs;
2081 }
2082
2083 @Override
2084 public void addPowerSaveTempWhitelistApp(String packageName, long duration, int userId,
2085 @ReasonCode int reasonCode, @Nullable String reason) throws RemoteException {
2086 addPowerSaveTempAllowlistAppChecked(packageName, duration, userId, reasonCode, reason);
2087 }
2088
2089 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName, int userId,
2090 @ReasonCode int reasonCode, @Nullable String reason) throws RemoteException {
2091 long durationMs = mConstants.MMS_TEMP_APP_ALLOWLIST_DURATION_MS;
2092 addPowerSaveTempAllowlistAppChecked(packageName, durationMs, userId, reasonCode,
2093 reason);
2094 return durationMs;
2095 }
2096
2097 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName, int userId,
2098 @ReasonCode int reasonCode, @Nullable String reason) throws RemoteException {
2099 long durationMs = mConstants.SMS_TEMP_APP_ALLOWLIST_DURATION_MS;
2100 addPowerSaveTempAllowlistAppChecked(packageName, durationMs, userId, reasonCode,
2101 reason);
2102 return durationMs;
2103 }
2104
2105 @Override public void exitIdle(String reason) {
2106 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
2107 null);
2108 final long ident = Binder.clearCallingIdentity();
2109 try {
2110 exitIdleInternal(reason);
2111 } finally {
2112 Binder.restoreCallingIdentity(ident);
2113 }
2114 }
2115
2116 @Override public int setPreIdleTimeoutMode(int mode) {
2117 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
2118 null);
2119 final long ident = Binder.clearCallingIdentity();
2120 try {
2121 return DeviceIdleController.this.setPreIdleTimeoutMode(mode);
2122 } finally {
2123 Binder.restoreCallingIdentity(ident);
2124 }
2125 }
2126
2127 @Override public void resetPreIdleTimeoutMode() {
2128 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
2129 null);
2130 final long ident = Binder.clearCallingIdentity();
2131 try {
2132 DeviceIdleController.this.resetPreIdleTimeoutMode();
2133 } finally {
2134 Binder.restoreCallingIdentity(ident);
2135 }
2136 }
2137
2138 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2139 DeviceIdleController.this.dump(fd, pw, args);
2140 }
2141
2142 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
2143 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
2144 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
2145 }
2146 }
2147
2148 private class LocalService implements DeviceIdleInternal {
2149 @Override
2150 public void onConstraintStateChanged(IDeviceIdleConstraint constraint, boolean active) {
2151 synchronized (DeviceIdleController.this) {
2152 onConstraintStateChangedLocked(constraint, active);
2153 }
2154 }
2155
2156 @Override
2157 public void registerDeviceIdleConstraint(IDeviceIdleConstraint constraint, String name,
2158 @IDeviceIdleConstraint.MinimumState int minState) {
2159 registerDeviceIdleConstraintInternal(constraint, name, minState);
2160 }
2161
2162 @Override
2163 public void unregisterDeviceIdleConstraint(IDeviceIdleConstraint constraint) {
2164 unregisterDeviceIdleConstraintInternal(constraint);
2165 }
2166
2167 @Override
2168 public void exitIdle(String reason) {
2169 exitIdleInternal(reason);
2170 }
2171
2172 @Override
2173 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
2174 long durationMs, int userId, boolean sync, @ReasonCode int reasonCode,
2175 @Nullable String reason) {
2176 addPowerSaveTempAllowlistAppInternal(callingUid, packageName, durationMs,
2177 TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
2178 userId, sync, reasonCode, reason);
2179 }
2180
2181 @Override
2182 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
2183 long durationMs, @TempAllowListType int tempAllowListType, int userId, boolean sync,
2184 @ReasonCode int reasonCode, @Nullable String reason) {
2185 addPowerSaveTempAllowlistAppInternal(callingUid, packageName, durationMs,
2186 tempAllowListType, userId, sync, reasonCode, reason);
2187 }
2188
2189 @Override
2190 public void addPowerSaveTempWhitelistAppDirect(int uid, long durationMs,
2191 @TempAllowListType int tempAllowListType, boolean sync, @ReasonCode int reasonCode,
2192 @Nullable String reason, int callingUid) {
2193 addPowerSaveTempWhitelistAppDirectInternal(callingUid, uid, durationMs,
2194 tempAllowListType, sync, reasonCode, reason);
2195 }
2196
2197 // duration in milliseconds
2198 @Override
2199 public long getNotificationAllowlistDuration() {
2200 return mConstants.NOTIFICATION_ALLOWLIST_DURATION_MS;
2201 }
2202
2203 @Override
2204 public void setJobsActive(boolean active) {
2205 DeviceIdleController.this.setJobsActive(active);
2206 }
2207
2208 // Up-call from alarm manager.
2209 @Override
2210 public void setAlarmsActive(boolean active) {
2211 DeviceIdleController.this.setAlarmsActive(active);
2212 }
2213
2214 /** Is the app on any of the power save whitelists, whether system or user? */
2215 @Override
2216 public boolean isAppOnWhitelist(int appid) {
2217 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
2218 }
2219
2220 /**
2221 * Returns the array of app ids whitelisted by user. Take care not to
2222 * modify this, as it is a reference to the original copy. But the reference
2223 * can change when the list changes, so it needs to be re-acquired when
2224 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
2225 */
2226 @Override
2227 public int[] getPowerSaveWhitelistUserAppIds() {
2228 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
2229 }
2230
2231 @Override
2232 public int[] getPowerSaveTempWhitelistAppIds() {
2233 return DeviceIdleController.this.getAppIdTempWhitelistInternal();
2234 }
2235
2236 @Override
2237 public void registerStationaryListener(StationaryListener listener) {
2238 DeviceIdleController.this.registerStationaryListener(listener);
2239 }
2240
2241 @Override
2242 public void unregisterStationaryListener(StationaryListener listener) {
2243 DeviceIdleController.this.unregisterStationaryListener(listener);
2244 }
2245
2246 @Override
2247 public @TempAllowListType int getTempAllowListType(@ReasonCode int reasonCode,
2248 @TempAllowListType int defaultType) {
2249 return DeviceIdleController.this.getTempAllowListType(reasonCode, defaultType);
2250 }
2251 }
2252
2253 private class LocalPowerAllowlistService implements PowerAllowlistInternal {
2254
2255 @Override
2256 public void registerTempAllowlistChangeListener(
2257 @NonNull TempAllowlistChangeListener listener) {
2258 DeviceIdleController.this.registerTempAllowlistChangeListener(listener);
2259 }
2260
2261 @Override
2262 public void unregisterTempAllowlistChangeListener(
2263 @NonNull TempAllowlistChangeListener listener) {
2264 DeviceIdleController.this.unregisterTempAllowlistChangeListener(listener);
2265 }
2266 }
2267
2268 static class Injector {
2269 private final Context mContext;
2270 private ConnectivityManager mConnectivityManager;
2271 private Constants mConstants;
2272 private LocationManager mLocationManager;
2273
2274 Injector(Context ctx) {
2275 mContext = ctx.createAttributionContext(TAG);
2276 }
2277
2278 AlarmManager getAlarmManager() {
2279 return mContext.getSystemService(AlarmManager.class);
2280 }
2281
2282 AnyMotionDetector getAnyMotionDetector(Handler handler, SensorManager sm,
2283 AnyMotionDetector.DeviceIdleCallback callback, float angleThreshold) {
2284 return new AnyMotionDetector(getPowerManager(), handler, sm, callback, angleThreshold);
2285 }
2286
2287 AppStateTrackerImpl getAppStateTracker(Context ctx, Looper looper) {
2288 return new AppStateTrackerImpl(ctx, looper);
2289 }
2290
2291 ConnectivityManager getConnectivityManager() {
2292 if (mConnectivityManager == null) {
2293 mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
2294 }
2295 return mConnectivityManager;
2296 }
2297
2298 Constants getConstants(DeviceIdleController controller) {
2299 if (mConstants == null) {
2300 mConstants = controller.new Constants();
2301 }
2302 return mConstants;
2303 }
2304
2305
2306 /** Returns the current elapsed realtime in milliseconds. */
2307 long getElapsedRealtime() {
2308 return SystemClock.elapsedRealtime();
2309 }
2310
2311 LocationManager getLocationManager() {
2312 if (mLocationManager == null) {
2313 mLocationManager = mContext.getSystemService(LocationManager.class);
2314 }
2315 return mLocationManager;
2316 }
2317
2318 MyHandler getHandler(DeviceIdleController controller) {
2319 return controller.new MyHandler(JobSchedulerBackgroundThread.getHandler().getLooper());
2320 }
2321
2322 Sensor getMotionSensor() {
2323 final SensorManager sensorManager = getSensorManager();
2324 Sensor motionSensor = null;
2325 int sigMotionSensorId = mContext.getResources().getInteger(
2326 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
2327 if (sigMotionSensorId > 0) {
2328 motionSensor = sensorManager.getDefaultSensor(sigMotionSensorId, true);
2329 }
2330 if (motionSensor == null && mContext.getResources().getBoolean(
2331 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
2332 motionSensor = sensorManager.getDefaultSensor(
2333 Sensor.TYPE_WRIST_TILT_GESTURE, true);
2334 }
2335 if (motionSensor == null) {
2336 // As a last ditch, fall back to SMD.
2337 motionSensor = sensorManager.getDefaultSensor(
2338 Sensor.TYPE_SIGNIFICANT_MOTION, true);
2339 }
2340 return motionSensor;
2341 }
2342
2343 PowerManager getPowerManager() {
2344 return mContext.getSystemService(PowerManager.class);
2345 }
2346
2347 SensorManager getSensorManager() {
2348 return mContext.getSystemService(SensorManager.class);
2349 }
2350
2351 ConstraintController getConstraintController(Handler handler,
2352 DeviceIdleInternal localService) {
2353 if (mContext.getPackageManager()
2354 .hasSystemFeature(PackageManager.FEATURE_LEANBACK_ONLY)) {
2355 return new TvConstraintController(mContext, handler);
2356 }
2357 return null;
2358 }
2359
2360 boolean useMotionSensor() {
2361 return mContext.getResources().getBoolean(
2362 com.android.internal.R.bool.config_autoPowerModeUseMotionSensor);
2363 }
2364 }
2365
2366 private final Injector mInjector;
2367
2368 private ActivityTaskManagerInternal.ScreenObserver mScreenObserver =
2369 new ActivityTaskManagerInternal.ScreenObserver() {
2370 @Override
2371 public void onAwakeStateChanged(boolean isAwake) { }
2372
2373 @Override
2374 public void onKeyguardStateChanged(boolean isShowing) {
2375 synchronized (DeviceIdleController.this) {
2376 DeviceIdleController.this.keyguardShowingLocked(isShowing);
2377 }
2378 }
2379 };
2380
2381 @VisibleForTesting DeviceIdleController(Context context, Injector injector) {
2382 super(context);
2383 mInjector = injector;
2384 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
2385 mHandler = mInjector.getHandler(this);
2386 mAppStateTracker = mInjector.getAppStateTracker(context,
2387 JobSchedulerBackgroundThread.get().getLooper());
2388 LocalServices.addService(AppStateTracker.class, mAppStateTracker);
2389 mUseMotionSensor = mInjector.useMotionSensor();
2390 }
2391
2392 public DeviceIdleController(Context context) {
2393 this(context, new Injector(context));
2394 }
2395
2396 boolean isAppOnWhitelistInternal(int appid) {
2397 synchronized (this) {
2398 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
2399 }
2400 }
2401
2402 int[] getPowerSaveWhitelistUserAppIds() {
2403 synchronized (this) {
2404 return mPowerSaveWhitelistUserAppIdArray;
2405 }
2406 }
2407
2408 private static File getSystemDir() {
2409 return new File(Environment.getDataDirectory(), "system");
2410 }
2411
2412 @Override
2413 public void onStart() {
2414 final PackageManager pm = getContext().getPackageManager();
2415
2416 synchronized (this) {
2417 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
2418 com.android.internal.R.bool.config_enableAutoPowerModes);
2419 SystemConfig sysConfig = SystemConfig.getInstance();
2420 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
2421 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
2422 String pkg = allowPowerExceptIdle.valueAt(i);
2423 try {
2424 ApplicationInfo ai = pm.getApplicationInfo(pkg,
2425 PackageManager.MATCH_SYSTEM_ONLY);
2426 int appid = UserHandle.getAppId(ai.uid);
2427 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
2428 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
2429 } catch (PackageManager.NameNotFoundException e) {
2430 }
2431 }
2432 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
2433 for (int i=0; i<allowPower.size(); i++) {
2434 String pkg = allowPower.valueAt(i);
2435 try {
2436 ApplicationInfo ai = pm.getApplicationInfo(pkg,
2437 PackageManager.MATCH_SYSTEM_ONLY);
2438 int appid = UserHandle.getAppId(ai.uid);
2439 // These apps are on both the whitelist-except-idle as well
2440 // as the full whitelist, so they apply in all cases.
2441 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
2442 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
2443 mPowerSaveWhitelistApps.put(ai.packageName, appid);
2444 mPowerSaveWhitelistSystemAppIds.put(appid, true);
2445 } catch (PackageManager.NameNotFoundException e) {
2446 }
2447 }
2448
2449 mConstants = mInjector.getConstants(this);
2450
2451 readConfigFileLocked();
2452 updateWhitelistAppIdsLocked();
2453
2454 mNetworkConnected = true;
2455 mScreenOn = true;
2456 mScreenLocked = false;
2457 // Start out assuming we are charging. If we aren't, we will at least get
2458 // a battery update the next time the level drops.
2459 mCharging = true;
2460 mActiveReason = ACTIVE_REASON_UNKNOWN;
2461 moveToStateLocked(STATE_ACTIVE, "boot");
2462 moveToLightStateLocked(LIGHT_STATE_ACTIVE, "boot");
2463 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
2464 mPreIdleFactor = 1.0f;
2465 mLastPreIdleFactor = 1.0f;
2466 }
2467
2468 mBinderService = new BinderService();
2469 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
2470 mLocalService = new LocalService();
2471 publishLocalService(DeviceIdleInternal.class, mLocalService);
2472 publishLocalService(PowerAllowlistInternal.class, new LocalPowerAllowlistService());
2473 }
2474
2475 @Override
2476 public void onBootPhase(int phase) {
2477 if (phase == PHASE_SYSTEM_SERVICES_READY) {
2478 synchronized (this) {
2479 mAlarmManager = mInjector.getAlarmManager();
2480 mLocalAlarmManager = getLocalService(AlarmManagerInternal.class);
2481 mBatteryStats = BatteryStatsService.getService();
2482 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
2483 mLocalActivityTaskManager = getLocalService(ActivityTaskManagerInternal.class);
2484 mPackageManagerInternal = getLocalService(PackageManagerInternal.class);
2485 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
2486 mPowerManager = mInjector.getPowerManager();
2487 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
2488 "deviceidle_maint");
2489 mActiveIdleWakeLock.setReferenceCounted(false);
2490 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
2491 "deviceidle_going_idle");
2492 mGoingIdleWakeLock.setReferenceCounted(true);
2493 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
2494 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
2495 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
2496 mSensorManager = mInjector.getSensorManager();
2497
2498 if (mUseMotionSensor) {
2499 mMotionSensor = mInjector.getMotionSensor();
2500 }
2501
2502 if (getContext().getResources().getBoolean(
2503 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
2504 mLocationRequest = new LocationRequest.Builder(/*intervalMillis=*/ 0)
2505 .setQuality(LocationRequest.QUALITY_HIGH_ACCURACY)
2506 .setMaxUpdates(1)
2507 .build();
2508 }
2509
2510 mConstraintController = mInjector.getConstraintController(
2511 mHandler, getLocalService(LocalService.class));
2512 if (mConstraintController != null) {
2513 mConstraintController.start();
2514 }
2515
2516 float angleThreshold = getContext().getResources().getInteger(
2517 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
2518 mAnyMotionDetector = mInjector.getAnyMotionDetector(mHandler, mSensorManager, this,
2519 angleThreshold);
2520
2521 mAppStateTracker.onSystemServicesReady();
2522
2523 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
2524 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2525 | Intent.FLAG_RECEIVER_FOREGROUND);
2526 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
2527 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2528 | Intent.FLAG_RECEIVER_FOREGROUND);
2529
2530 IntentFilter filter = new IntentFilter();
2531 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
2532 getContext().registerReceiver(mReceiver, filter);
2533
2534 filter = new IntentFilter();
2535 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2536 filter.addDataScheme("package");
2537 getContext().registerReceiver(mReceiver, filter);
2538
2539 filter = new IntentFilter();
2540 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
2541 getContext().registerReceiver(mReceiver, filter);
2542
2543 filter = new IntentFilter();
2544 filter.addAction(Intent.ACTION_SCREEN_OFF);
2545 filter.addAction(Intent.ACTION_SCREEN_ON);
2546 getContext().registerReceiver(mInteractivityReceiver, filter);
2547
2548 mLocalActivityManager.setDeviceIdleAllowlist(
2549 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
2550 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2551
2552 mLocalPowerManager.registerLowPowerModeObserver(ServiceType.QUICK_DOZE,
2553 state -> {
2554 synchronized (DeviceIdleController.this) {
2555 updateQuickDozeFlagLocked(state.batterySaverEnabled);
2556 }
2557 });
2558 updateQuickDozeFlagLocked(
2559 mLocalPowerManager.getLowPowerState(
2560 ServiceType.QUICK_DOZE).batterySaverEnabled);
2561
2562 mLocalActivityTaskManager.registerScreenObserver(mScreenObserver);
2563
2564 passWhiteListsToForceAppStandbyTrackerLocked();
2565 updateInteractivityLocked();
2566 }
2567 updateConnectivityState(null);
2568 }
2569 }
2570
2571 @VisibleForTesting
2572 boolean hasMotionSensor() {
2573 return mUseMotionSensor && mMotionSensor != null;
2574 }
2575
2576 private void registerDeviceIdleConstraintInternal(IDeviceIdleConstraint constraint,
2577 final String name, final int type) {
2578 final int minState;
2579 switch (type) {
2580 case IDeviceIdleConstraint.ACTIVE:
2581 minState = STATE_ACTIVE;
2582 break;
2583 case IDeviceIdleConstraint.SENSING_OR_ABOVE:
2584 minState = STATE_SENSING;
2585 break;
2586 default:
2587 Slog.wtf(TAG, "Registering device-idle constraint with invalid type: " + type);
2588 return;
2589 }
2590 synchronized (this) {
2591 if (mConstraints.containsKey(constraint)) {
2592 Slog.e(TAG, "Re-registering device-idle constraint: " + constraint + ".");
2593 return;
2594 }
2595 DeviceIdleConstraintTracker tracker = new DeviceIdleConstraintTracker(name, minState);
2596 mConstraints.put(constraint, tracker);
2597 updateActiveConstraintsLocked();
2598 }
2599 }
2600
2601 private void unregisterDeviceIdleConstraintInternal(IDeviceIdleConstraint constraint) {
2602 synchronized (this) {
2603 // Artificially force the constraint to inactive to unblock anything waiting for it.
2604 onConstraintStateChangedLocked(constraint, /* active= */ false);
2605
2606 // Let the constraint know that we are not listening to it any more.
2607 setConstraintMonitoringLocked(constraint, /* monitoring= */ false);
2608 mConstraints.remove(constraint);
2609 }
2610 }
2611
2612 @GuardedBy("this")
2613 private void onConstraintStateChangedLocked(IDeviceIdleConstraint constraint, boolean active) {
2614 DeviceIdleConstraintTracker tracker = mConstraints.get(constraint);
2615 if (tracker == null) {
2616 Slog.e(TAG, "device-idle constraint " + constraint + " has not been registered.");
2617 return;
2618 }
2619 if (active != tracker.active && tracker.monitoring) {
2620 tracker.active = active;
2621 mNumBlockingConstraints += (tracker.active ? +1 : -1);
2622 if (mNumBlockingConstraints == 0) {
2623 if (mState == STATE_ACTIVE) {
2624 becomeInactiveIfAppropriateLocked();
2625 } else if (mNextAlarmTime == 0 || mNextAlarmTime < SystemClock.elapsedRealtime()) {
2626 stepIdleStateLocked("s:" + tracker.name);
2627 }
2628 }
2629 }
2630 }
2631
2632 @GuardedBy("this")
2633 private void setConstraintMonitoringLocked(IDeviceIdleConstraint constraint, boolean monitor) {
2634 DeviceIdleConstraintTracker tracker = mConstraints.get(constraint);
2635 if (tracker.monitoring != monitor) {
2636 tracker.monitoring = monitor;
2637 updateActiveConstraintsLocked();
2638 // We send the callback on a separate thread instead of just relying on oneway as
2639 // the client could be in the system server with us and cause re-entry problems.
2640 mHandler.obtainMessage(MSG_SEND_CONSTRAINT_MONITORING,
2641 /* monitoring= */ monitor ? 1 : 0,
2642 /* <not used>= */ -1,
2643 /* constraint= */ constraint).sendToTarget();
2644 }
2645 }
2646
2647 @GuardedBy("this")
2648 private void updateActiveConstraintsLocked() {
2649 mNumBlockingConstraints = 0;
2650 for (int i = 0; i < mConstraints.size(); i++) {
2651 final IDeviceIdleConstraint constraint = mConstraints.keyAt(i);
2652 final DeviceIdleConstraintTracker tracker = mConstraints.valueAt(i);
2653 final boolean monitoring = (tracker.minState == mState);
2654 if (monitoring != tracker.monitoring) {
2655 setConstraintMonitoringLocked(constraint, monitoring);
2656 tracker.active = monitoring;
2657 }
2658 if (tracker.monitoring && tracker.active) {
2659 mNumBlockingConstraints++;
2660 }
2661 }
2662 }
2663
2664 private int addPowerSaveWhitelistAppsInternal(List<String> pkgNames) {
2665 int numAdded = 0;
2666 int numErrors = 0;
2667 synchronized (this) {
2668 for (int i = pkgNames.size() - 1; i >= 0; --i) {
2669 final String name = pkgNames.get(i);
2670 if (name == null) {
2671 numErrors++;
2672 continue;
2673 }
2674 try {
2675 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
2676 PackageManager.MATCH_ANY_USER);
2677 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid))
2678 == null) {
2679 numAdded++;
2680 }
2681 } catch (PackageManager.NameNotFoundException e) {
2682 Slog.e(TAG, "Tried to add unknown package to power save whitelist: " + name);
2683 numErrors++;
2684 }
2685 }
2686 if (numAdded > 0) {
2687 reportPowerSaveWhitelistChangedLocked();
2688 updateWhitelistAppIdsLocked();
2689 writeConfigFileLocked();
2690 }
2691 }
2692 return pkgNames.size() - numErrors;
2693 }
2694
2695 public boolean removePowerSaveWhitelistAppInternal(String name) {
2696 synchronized (this) {
2697 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
2698 reportPowerSaveWhitelistChangedLocked();
2699 updateWhitelistAppIdsLocked();
2700 writeConfigFileLocked();
2701 return true;
2702 }
2703 }
2704 return false;
2705 }
2706
2707 public boolean getPowerSaveWhitelistAppInternal(String name) {
2708 synchronized (this) {
2709 return mPowerSaveWhitelistUserApps.containsKey(name);
2710 }
2711 }
2712
2713 void resetSystemPowerWhitelistInternal() {
2714 synchronized (this) {
2715 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
2716 mRemovedFromSystemWhitelistApps.clear();
2717 reportPowerSaveWhitelistChangedLocked();
2718 updateWhitelistAppIdsLocked();
2719 writeConfigFileLocked();
2720 }
2721 }
2722
2723 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
2724 synchronized (this) {
2725 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
2726 return false;
2727 }
2728 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
2729 reportPowerSaveWhitelistChangedLocked();
2730 updateWhitelistAppIdsLocked();
2731 writeConfigFileLocked();
2732 return true;
2733 }
2734 }
2735
2736 public boolean removeSystemPowerWhitelistAppInternal(String name) {
2737 synchronized (this) {
2738 if (!mPowerSaveWhitelistApps.containsKey(name)) {
2739 return false;
2740 }
2741 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
2742 reportPowerSaveWhitelistChangedLocked();
2743 updateWhitelistAppIdsLocked();
2744 writeConfigFileLocked();
2745 return true;
2746 }
2747 }
2748
2749 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
2750 synchronized (this) {
2751 try {
2752 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
2753 PackageManager.MATCH_ANY_USER);
2754 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
2755 == null) {
2756 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
2757 reportPowerSaveWhitelistChangedLocked();
2758 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
2759 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
2760 mPowerSaveWhitelistExceptIdleAppIds);
2761
2762 passWhiteListsToForceAppStandbyTrackerLocked();
2763 }
2764 return true;
2765 } catch (PackageManager.NameNotFoundException e) {
2766 return false;
2767 }
2768 }
2769 }
2770
2771 public void resetPowerSaveWhitelistExceptIdleInternal() {
2772 synchronized (this) {
2773 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
2774 mPowerSaveWhitelistUserAppsExceptIdle)) {
2775 reportPowerSaveWhitelistChangedLocked();
2776 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
2777 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
2778 mPowerSaveWhitelistExceptIdleAppIds);
2779 mPowerSaveWhitelistUserAppsExceptIdle.clear();
2780
2781 passWhiteListsToForceAppStandbyTrackerLocked();
2782 }
2783 }
2784 }
2785
2786 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
2787 synchronized (this) {
2788 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
2789 }
2790 }
2791
2792 private String[] getSystemPowerWhitelistExceptIdleInternal(final int callingUid,
2793 final int callingUserId) {
2794 final String[] apps;
2795 synchronized (this) {
2796 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2797 apps = new String[size];
2798 for (int i = 0; i < size; i++) {
2799 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
2800 }
2801 }
2802 return ArrayUtils.filter(apps, String[]::new,
2803 (pkg) -> !mPackageManagerInternal.filterAppAccess(pkg, callingUid, callingUserId));
2804 }
2805
2806 private String[] getSystemPowerWhitelistInternal(final int callingUid,
2807 final int callingUserId) {
2808 final String[] apps;
2809 synchronized (this) {
2810 int size = mPowerSaveWhitelistApps.size();
2811 apps = new String[size];
2812 for (int i = 0; i < size; i++) {
2813 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
2814 }
2815 }
2816 return ArrayUtils.filter(apps, String[]::new,
2817 (pkg) -> !mPackageManagerInternal.filterAppAccess(pkg, callingUid, callingUserId));
2818 }
2819
2820 private String[] getRemovedSystemPowerWhitelistAppsInternal(final int callingUid,
2821 final int callingUserId) {
2822 final String[] apps;
2823 synchronized (this) {
2824 int size = mRemovedFromSystemWhitelistApps.size();
2825 apps = new String[size];
2826 for (int i = 0; i < size; i++) {
2827 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
2828 }
2829 }
2830 return ArrayUtils.filter(apps, String[]::new,
2831 (pkg) -> !mPackageManagerInternal.filterAppAccess(pkg, callingUid, callingUserId));
2832 }
2833
2834 private String[] getUserPowerWhitelistInternal(final int callingUid, final int callingUserId) {
2835 final String[] apps;
2836 synchronized (this) {
2837 int size = mPowerSaveWhitelistUserApps.size();
2838 apps = new String[size];
2839 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2840 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
2841 }
2842 }
2843 return ArrayUtils.filter(apps, String[]::new,
2844 (pkg) -> !mPackageManagerInternal.filterAppAccess(pkg, callingUid, callingUserId));
2845 }
2846
2847 private String[] getFullPowerWhitelistExceptIdleInternal(final int callingUid,
2848 final int callingUserId) {
2849 final String[] apps;
2850 synchronized (this) {
2851 int size =
2852 mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
2853 apps = new String[size];
2854 int cur = 0;
2855 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
2856 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
2857 cur++;
2858 }
2859 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2860 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
2861 cur++;
2862 }
2863 }
2864 return ArrayUtils.filter(apps, String[]::new,
2865 (pkg) -> !mPackageManagerInternal.filterAppAccess(pkg, callingUid, callingUserId));
2866 }
2867
2868 private String[] getFullPowerWhitelistInternal(final int callingUid, final int callingUserId) {
2869 final String[] apps;
2870 synchronized (this) {
2871 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
2872 apps = new String[size];
2873 int cur = 0;
2874 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
2875 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
2876 cur++;
2877 }
2878 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2879 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
2880 cur++;
2881 }
2882 }
2883 return ArrayUtils.filter(apps, String[]::new,
2884 (pkg) -> !mPackageManagerInternal.filterAppAccess(pkg, callingUid, callingUserId));
2885 }
2886
2887 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
2888 synchronized (this) {
2889 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
2890 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2891 }
2892 }
2893
2894 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
2895 synchronized (this) {
2896 return mPowerSaveWhitelistApps.containsKey(packageName)
2897 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2898 }
2899 }
2900
2901 public int[] getAppIdWhitelistExceptIdleInternal() {
2902 synchronized (this) {
2903 return mPowerSaveWhitelistExceptIdleAppIdArray;
2904 }
2905 }
2906
2907 public int[] getAppIdWhitelistInternal() {
2908 synchronized (this) {
2909 return mPowerSaveWhitelistAllAppIdArray;
2910 }
2911 }
2912
2913 public int[] getAppIdUserWhitelistInternal() {
2914 synchronized (this) {
2915 return mPowerSaveWhitelistUserAppIdArray;
2916 }
2917 }
2918
2919 public int[] getAppIdTempWhitelistInternal() {
2920 synchronized (this) {
2921 return mTempWhitelistAppIdArray;
2922 }
2923 }
2924
2925 private @TempAllowListType int getTempAllowListType(@ReasonCode int reasonCode,
2926 @TempAllowListType int defaultType) {
2927 switch (reasonCode) {
2928 case PowerExemptionManager.REASON_PUSH_MESSAGING_OVER_QUOTA:
2929 return mLocalActivityManager.getPushMessagingOverQuotaBehavior();
2930 case PowerExemptionManager.REASON_DENIED:
2931 return TEMPORARY_ALLOW_LIST_TYPE_NONE;
2932 default:
2933 return defaultType;
2934 }
2935 }
2936
2937 void addPowerSaveTempAllowlistAppChecked(String packageName, long duration,
2938 int userId, @ReasonCode int reasonCode, @Nullable String reason)
2939 throws RemoteException {
2940 getContext().enforceCallingOrSelfPermission(
2941 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2942 "No permission to change device idle whitelist");
2943 final int callingUid = Binder.getCallingUid();
2944 userId = ActivityManager.getService().handleIncomingUser(
2945 Binder.getCallingPid(),
2946 callingUid,
2947 userId,
2948 /*allowAll=*/ false,
2949 /*requireFull=*/ false,
2950 "addPowerSaveTempWhitelistApp", null);
2951 final long token = Binder.clearCallingIdentity();
2952 try {
2953 @TempAllowListType int type = getTempAllowListType(reasonCode,
2954 TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED);
2955 if (type != TEMPORARY_ALLOW_LIST_TYPE_NONE) {
2956 addPowerSaveTempAllowlistAppInternal(callingUid,
2957 packageName, duration, type, userId, true, reasonCode, reason);
2958 }
2959 } finally {
2960 Binder.restoreCallingIdentity(token);
2961 }
2962 }
2963
2964 void removePowerSaveTempAllowlistAppChecked(String packageName, int userId)
2965 throws RemoteException {
2966 getContext().enforceCallingOrSelfPermission(
2967 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2968 "No permission to change device idle whitelist");
2969 final int callingUid = Binder.getCallingUid();
2970 userId = ActivityManager.getService().handleIncomingUser(
2971 Binder.getCallingPid(),
2972 callingUid,
2973 userId,
2974 /*allowAll=*/ false,
2975 /*requireFull=*/ false,
2976 "removePowerSaveTempWhitelistApp", null);
2977 final long token = Binder.clearCallingIdentity();
2978 try {
2979 removePowerSaveTempAllowlistAppInternal(packageName, userId);
2980 } finally {
2981 Binder.restoreCallingIdentity(token);
2982 }
2983 }
2984
2985 /**
2986 * Adds an app to the temporary whitelist and resets the endTime for granting the
2987 * app an exemption to access network and acquire wakelocks.
2988 */
2989 void addPowerSaveTempAllowlistAppInternal(int callingUid, String packageName,
2990 long durationMs, @TempAllowListType int tempAllowListType, int userId, boolean sync,
2991 @ReasonCode int reasonCode, @Nullable String reason) {
2992 try {
2993 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
2994 addPowerSaveTempWhitelistAppDirectInternal(callingUid, uid, durationMs,
2995 tempAllowListType, sync, reasonCode, reason);
2996 } catch (NameNotFoundException e) {
2997 }
2998 }
2999
3000 /**
3001 * Adds an app to the temporary whitelist and resets the endTime for granting the
3002 * app an exemption to access network and acquire wakelocks.
3003 */
3004 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int uid,
3005 long duration, @TempAllowListType int tempAllowListType, boolean sync,
3006 @ReasonCode int reasonCode, @Nullable String reason) {
3007 final long timeNow = SystemClock.elapsedRealtime();
3008 boolean informWhitelistChanged = false;
3009 int appId = UserHandle.getAppId(uid);
3010 synchronized (this) {
3011 duration = Math.min(duration, mConstants.MAX_TEMP_APP_ALLOWLIST_DURATION_MS);
3012 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
3013 final boolean newEntry = entry == null;
3014 // Set the new end time
3015 if (newEntry) {
3016 entry = new Pair<>(new MutableLong(0), reason);
3017 mTempWhitelistAppIdEndTimes.put(appId, entry);
3018 }
3019 entry.first.value = timeNow + duration;
3020 if (DEBUG) {
3021 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
3022 }
3023 if (newEntry) {
3024 // No pending timeout for the app id, post a delayed message
3025 try {
3026 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
3027 reason, uid);
3028 } catch (RemoteException e) {
3029 }
3030 postTempActiveTimeoutMessage(uid, duration);
3031 updateTempWhitelistAppIdsLocked(uid, true, duration, tempAllowListType,
3032 reasonCode, reason, callingUid);
3033 if (sync) {
3034 informWhitelistChanged = true;
3035 } else {
3036 // NPMS needs to update its state synchronously in certain situations so we
3037 // can't have it use the TempAllowlistChangeListener path right now.
3038 // TODO: see if there's a way to simplify/consolidate
3039 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_ADDED_TO_NPMS, appId,
3040 reasonCode, reason).sendToTarget();
3041 }
3042 reportTempWhitelistChangedLocked(uid, true);
3043 } else {
3044 // The uid is already temp allowlisted, only need to update AMS for temp allowlist
3045 // duration.
3046 if (mLocalActivityManager != null) {
3047 mLocalActivityManager.updateDeviceIdleTempAllowlist(null, uid, true,
3048 duration, tempAllowListType, reasonCode, reason, callingUid);
3049 }
3050 }
3051 }
3052 if (informWhitelistChanged) {
3053 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true,
3054 reasonCode, reason);
3055 }
3056 }
3057
3058 /**
3059 * Removes an app from the temporary whitelist and notifies the observers.
3060 */
3061 private void removePowerSaveTempAllowlistAppInternal(String packageName, int userId) {
3062 try {
3063 final int uid = getContext().getPackageManager().getPackageUidAsUser(
3064 packageName, userId);
3065 removePowerSaveTempWhitelistAppDirectInternal(uid);
3066 } catch (NameNotFoundException e) {
3067 }
3068 }
3069
3070 private void removePowerSaveTempWhitelistAppDirectInternal(int uid) {
3071 final int appId = UserHandle.getAppId(uid);
3072 synchronized (this) {
3073 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
3074 if (idx < 0) {
3075 // Nothing else to do
3076 return;
3077 }
3078 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
3079 mTempWhitelistAppIdEndTimes.removeAt(idx);
3080 onAppRemovedFromTempWhitelistLocked(uid, reason);
3081 }
3082 }
3083
3084 private void postTempActiveTimeoutMessage(int uid, long delay) {
3085 if (DEBUG) {
3086 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
3087 }
3088 mHandler.sendMessageDelayed(
3089 mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0), delay);
3090 }
3091
3092 void checkTempAppWhitelistTimeout(int uid) {
3093 final long timeNow = SystemClock.elapsedRealtime();
3094 final int appId = UserHandle.getAppId(uid);
3095 if (DEBUG) {
3096 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
3097 }
3098 synchronized (this) {
3099 Pair<MutableLong, String> entry =
3100 mTempWhitelistAppIdEndTimes.get(appId);
3101 if (entry == null) {
3102 // Nothing to do
3103 return;
3104 }
3105 if (timeNow >= entry.first.value) {
3106 mTempWhitelistAppIdEndTimes.delete(appId);
3107 onAppRemovedFromTempWhitelistLocked(uid, entry.second);
3108 } else {
3109 // Need more time
3110 if (DEBUG) {
3111 Slog.d(TAG, "Time to remove uid " + uid + ": " + entry.first.value);
3112 }
3113 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
3114 }
3115 }
3116 }
3117
3118 @GuardedBy("this")
3119 private void onAppRemovedFromTempWhitelistLocked(int uid, @Nullable String reason) {
3120 if (DEBUG) {
3121 Slog.d(TAG, "Removing uid " + uid + " from temp whitelist");
3122 }
3123 final int appId = UserHandle.getAppId(uid);
3124 updateTempWhitelistAppIdsLocked(uid, false, 0, 0, REASON_UNKNOWN,
3125 reason, INVALID_UID);
3126 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_REMOVED_TO_NPMS, appId,
3127 /* unused= */ 0).sendToTarget();
3128 reportTempWhitelistChangedLocked(uid, false);
3129 try {
3130 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
3131 reason, appId);
3132 } catch (RemoteException e) {
3133 }
3134 }
3135
3136 public void exitIdleInternal(String reason) {
3137 synchronized (this) {
3138 mActiveReason = ACTIVE_REASON_FROM_BINDER_CALL;
3139 becomeActiveLocked(reason, Binder.getCallingUid());
3140 }
3141 }
3142
3143 @VisibleForTesting
3144 boolean isNetworkConnected() {
3145 synchronized (this) {
3146 return mNetworkConnected;
3147 }
3148 }
3149
3150 void updateConnectivityState(Intent connIntent) {
3151 ConnectivityManager cm;
3152 synchronized (this) {
3153 cm = mInjector.getConnectivityManager();
3154 }
3155 if (cm == null) {
3156 return;
3157 }
3158 // Note: can't call out to ConnectivityService with our lock held.
3159 NetworkInfo ni = cm.getActiveNetworkInfo();
3160 synchronized (this) {
3161 boolean conn;
3162 if (ni == null) {
3163 conn = false;
3164 } else {
3165 if (connIntent == null) {
3166 conn = ni.isConnected();
3167 } else {
3168 final int networkType =
3169 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
3170 ConnectivityManager.TYPE_NONE);
3171 if (ni.getType() != networkType) {
3172 return;
3173 }
3174 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
3175 false);
3176 }
3177 }
3178 if (conn != mNetworkConnected) {
3179 mNetworkConnected = conn;
3180 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
3181 stepLightIdleStateLocked("network", /* forceProgression */ true);
3182 }
3183 }
3184 }
3185 }
3186
3187 @VisibleForTesting
3188 boolean isScreenOn() {
3189 synchronized (this) {
3190 return mScreenOn;
3191 }
3192 }
3193
3194 @GuardedBy("this")
3195 void updateInteractivityLocked() {
3196 // The interactivity state from the power manager tells us whether the display is
3197 // in a state that we need to keep things running so they will update at a normal
3198 // frequency.
3199 boolean screenOn = mPowerManager.isInteractive();
3200 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
3201 if (!screenOn && mScreenOn) {
3202 mScreenOn = false;
3203 if (!mForceIdle) {
3204 becomeInactiveIfAppropriateLocked();
3205 }
3206 } else if (screenOn) {
3207 mScreenOn = true;
3208 if (!mForceIdle && (!mScreenLocked || !mConstants.WAIT_FOR_UNLOCK)) {
3209 mActiveReason = ACTIVE_REASON_SCREEN;
3210 becomeActiveLocked("screen", Process.myUid());
3211 }
3212 }
3213 }
3214
3215 @VisibleForTesting
3216 boolean isCharging() {
3217 synchronized (this) {
3218 return mCharging;
3219 }
3220 }
3221
3222 @GuardedBy("this")
3223 void updateChargingLocked(boolean charging) {
3224 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
3225 if (!charging && mCharging) {
3226 mCharging = false;
3227 if (!mForceIdle) {
3228 becomeInactiveIfAppropriateLocked();
3229 }
3230 } else if (charging) {
3231 mCharging = charging;
3232 if (!mForceIdle) {
3233 mActiveReason = ACTIVE_REASON_CHARGING;
3234 becomeActiveLocked("charging", Process.myUid());
3235 }
3236 }
3237 }
3238
3239 @VisibleForTesting
3240 boolean isQuickDozeEnabled() {
3241 synchronized (this) {
3242 return mQuickDozeActivated;
3243 }
3244 }
3245
3246 /** Updates the quick doze flag and enters deep doze if appropriate. */
3247 @VisibleForTesting
3248 @GuardedBy("this")
3249 void updateQuickDozeFlagLocked(boolean enabled) {
3250 if (DEBUG) Slog.i(TAG, "updateQuickDozeFlagLocked: enabled=" + enabled);
3251 mQuickDozeActivated = enabled;
3252 mQuickDozeActivatedWhileIdling =
3253 mQuickDozeActivated && (mState == STATE_IDLE || mState == STATE_IDLE_MAINTENANCE);
3254 if (enabled) {
3255 // If Quick Doze is enabled, see if we should go straight into it.
3256 becomeInactiveIfAppropriateLocked();
3257 }
3258 // Going from Deep Doze to Light Idle (if quick doze becomes disabled) is tricky and
3259 // probably not worth the overhead, so leave in deep doze if that's the case until the
3260 // next natural time to come out of it.
3261 }
3262
3263
3264 /** Returns true if the screen is locked. */
3265 @VisibleForTesting
3266 boolean isKeyguardShowing() {
3267 synchronized (this) {
3268 return mScreenLocked;
3269 }
3270 }
3271
3272 @VisibleForTesting
3273 @GuardedBy("this")
3274 void keyguardShowingLocked(boolean showing) {
3275 if (DEBUG) Slog.i(TAG, "keyguardShowing=" + showing);
3276 if (mScreenLocked != showing) {
3277 mScreenLocked = showing;
3278 if (mScreenOn && !mForceIdle && !mScreenLocked) {
3279 mActiveReason = ACTIVE_REASON_UNLOCKED;
3280 becomeActiveLocked("unlocked", Process.myUid());
3281 }
3282 }
3283 }
3284
3285 @VisibleForTesting
3286 @GuardedBy("this")
3287 void scheduleReportActiveLocked(String activeReason, int activeUid) {
3288 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
3289 mHandler.sendMessage(msg);
3290 }
3291
3292 @GuardedBy("this")
3293 void becomeActiveLocked(String activeReason, int activeUid) {
3294 becomeActiveLocked(activeReason, activeUid, mConstants.INACTIVE_TIMEOUT, true);
3295 }
3296
3297 @GuardedBy("this")
3298 private void becomeActiveLocked(String activeReason, int activeUid,
3299 long newInactiveTimeout, boolean changeLightIdle) {
3300 if (DEBUG) {
3301 Slog.i(TAG, "becomeActiveLocked, reason=" + activeReason
3302 + ", changeLightIdle=" + changeLightIdle);
3303 }
3304 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
3305 moveToStateLocked(STATE_ACTIVE, activeReason);
3306 mInactiveTimeout = newInactiveTimeout;
3307 resetIdleManagementLocked();
3308 // Don't reset maintenance window start time if we're in a light idle maintenance window
3309 // because its used in the light idle budget calculation.
3310 if (mLightState != LIGHT_STATE_IDLE_MAINTENANCE) {
3311 mMaintenanceStartTime = 0;
3312 }
3313
3314 if (changeLightIdle) {
3315 moveToLightStateLocked(LIGHT_STATE_ACTIVE, activeReason);
3316 resetLightIdleManagementLocked();
3317 // Only report active if light is also ACTIVE.
3318 scheduleReportActiveLocked(activeReason, activeUid);
3319 addEvent(EVENT_NORMAL, activeReason);
3320 }
3321 }
3322 }
3323
3324 /** Must only be used in tests. */
3325 @VisibleForTesting
3326 void setDeepEnabledForTest(boolean enabled) {
3327 synchronized (this) {
3328 mDeepEnabled = enabled;
3329 }
3330 }
3331
3332 /** Must only be used in tests. */
3333 @VisibleForTesting
3334 void setLightEnabledForTest(boolean enabled) {
3335 synchronized (this) {
3336 mLightEnabled = enabled;
3337 }
3338 }
3339
3340 /** Sanity check to make sure DeviceIdleController and AlarmManager are on the same page. */
3341 @GuardedBy("this")
3342 private void verifyAlarmStateLocked() {
3343 if (mState == STATE_ACTIVE && mNextAlarmTime != 0) {
3344 Slog.wtf(TAG, "mState=ACTIVE but mNextAlarmTime=" + mNextAlarmTime);
3345 }
3346 if (mState != STATE_IDLE && mLocalAlarmManager.isIdling()) {
3347 Slog.wtf(TAG, "mState=" + stateToString(mState) + " but AlarmManager is idling");
3348 }
3349 if (mState == STATE_IDLE && !mLocalAlarmManager.isIdling()) {
3350 Slog.wtf(TAG, "mState=IDLE but AlarmManager is not idling");
3351 }
3352 if (mLightState == LIGHT_STATE_ACTIVE && mNextLightAlarmTime != 0) {
3353 Slog.wtf(TAG, "mLightState=ACTIVE but mNextLightAlarmTime is "
3354 + TimeUtils.formatDuration(mNextLightAlarmTime - SystemClock.elapsedRealtime())
3355 + " from now");
3356 }
3357 }
3358
3359 @GuardedBy("this")
3360 void becomeInactiveIfAppropriateLocked() {
3361 verifyAlarmStateLocked();
3362
3363 final boolean isScreenBlockingInactive =
3364 mScreenOn && (!mConstants.WAIT_FOR_UNLOCK || !mScreenLocked);
3365 if (DEBUG) {
3366 Slog.d(TAG, "becomeInactiveIfAppropriateLocked():"
3367 + " isScreenBlockingInactive=" + isScreenBlockingInactive
3368 + " (mScreenOn=" + mScreenOn
3369 + ", WAIT_FOR_UNLOCK=" + mConstants.WAIT_FOR_UNLOCK
3370 + ", mScreenLocked=" + mScreenLocked + ")"
3371 + " mCharging=" + mCharging
3372 + " mForceIdle=" + mForceIdle
3373 );
3374 }
3375 if (!mForceIdle && (mCharging || isScreenBlockingInactive)) {
3376 return;
3377 }
3378 // Become inactive and determine if we will ultimately go idle.
3379 if (mDeepEnabled) {
3380 if (mQuickDozeActivated) {
3381 if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
3382 || mState == STATE_IDLE_MAINTENANCE) {
3383 // Already "idling". Don't want to restart the process.
3384 // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
3385 // values, so returning here is safe.
3386 return;
3387 }
3388 moveToStateLocked(STATE_QUICK_DOZE_DELAY, "no activity");
3389 // Make sure any motion sensing or locating is stopped.
3390 resetIdleManagementLocked();
3391 if (isUpcomingAlarmClock()) {
3392 // If there's an upcoming AlarmClock alarm, we won't go into idle, so
3393 // setting a wakeup alarm before the upcoming alarm is futile. Set the quick
3394 // doze alarm to after the upcoming AlarmClock alarm.
3395 scheduleAlarmLocked(
3396 mAlarmManager.getNextWakeFromIdleTime() - mInjector.getElapsedRealtime()
3397 + mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
3398 } else {
3399 // Wait a small amount of time in case something (eg: background service from
3400 // recently closed app) needs to finish running.
3401 scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
3402 }
3403 } else if (mState == STATE_ACTIVE) {
3404 moveToStateLocked(STATE_INACTIVE, "no activity");
3405 resetIdleManagementLocked();
3406 long delay = mInactiveTimeout;
3407 if (shouldUseIdleTimeoutFactorLocked()) {
3408 delay = (long) (mPreIdleFactor * delay);
3409 }
3410 if (isUpcomingAlarmClock()) {
3411 // If there's an upcoming AlarmClock alarm, we won't go into idle, so
3412 // setting a wakeup alarm before the upcoming alarm is futile. Set the idle
3413 // alarm to after the upcoming AlarmClock alarm.
3414 scheduleAlarmLocked(
3415 mAlarmManager.getNextWakeFromIdleTime() - mInjector.getElapsedRealtime()
3416 + delay, false);
3417 } else {
3418 scheduleAlarmLocked(delay, false);
3419 }
3420 }
3421 }
3422 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
3423 moveToLightStateLocked(LIGHT_STATE_INACTIVE, "no activity");
3424 resetLightIdleManagementLocked();
3425 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
3426 mConstants.FLEX_TIME_SHORT);
3427 // After moving in INACTIVE, the maintenance window should start the time inactive
3428 // timeout and a single light idle period.
3429 scheduleLightMaintenanceAlarmLocked(
3430 mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT + mConstants.LIGHT_IDLE_TIMEOUT);
3431 }
3432 }
3433
3434 @GuardedBy("this")
3435 private void resetIdleManagementLocked() {
3436 mNextIdlePendingDelay = 0;
3437 mNextIdleDelay = 0;
3438 mIdleStartTime = 0;
3439 mQuickDozeActivatedWhileIdling = false;
3440 cancelAlarmLocked();
3441 cancelSensingTimeoutAlarmLocked();
3442 cancelLocatingLocked();
3443 maybeStopMonitoringMotionLocked();
3444 mAnyMotionDetector.stop();
3445 updateActiveConstraintsLocked();
3446 }
3447
3448 @GuardedBy("this")
3449 private void resetLightIdleManagementLocked() {
3450 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
3451 mMaintenanceStartTime = 0;
3452 mCurLightIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
3453 cancelAllLightAlarmsLocked();
3454 }
3455
3456 @GuardedBy("this")
3457 void exitForceIdleLocked() {
3458 if (mForceIdle) {
3459 mForceIdle = false;
3460 if (mScreenOn || mCharging) {
3461 mActiveReason = ACTIVE_REASON_FORCED;
3462 becomeActiveLocked("exit-force", Process.myUid());
3463 }
3464 }
3465 }
3466
3467 /**
3468 * Must only be used in tests.
3469 *
3470 * This sets the state value directly and thus doesn't trigger any behavioral changes.
3471 */
3472 @VisibleForTesting
3473 void setLightStateForTest(int lightState) {
3474 synchronized (this) {
3475 mLightState = lightState;
3476 }
3477 }
3478
3479 @VisibleForTesting
3480 int getLightState() {
3481 synchronized (this) {
3482 return mLightState;
3483 }
3484 }
3485
3486 @GuardedBy("this")
3487 private void stepLightIdleStateLocked(String reason) {
3488 stepLightIdleStateLocked(reason, false);
3489 }
3490
3491 @GuardedBy("this")
3492 @VisibleForTesting
3493 @SuppressLint("WakelockTimeout")
3494 void stepLightIdleStateLocked(String reason, boolean forceProgression) {
3495 if (mLightState == LIGHT_STATE_ACTIVE || mLightState == LIGHT_STATE_OVERRIDE) {
3496 // If we are already in deep device idle mode, then
3497 // there is nothing left to do for light mode.
3498 return;
3499 }
3500
3501 if (DEBUG) {
3502 Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + lightStateToString(mLightState)
3503 + " force=" + forceProgression);
3504 }
3505 EventLogTags.writeDeviceIdleLightStep();
3506
3507 final long nowElapsed = mInjector.getElapsedRealtime();
3508 final boolean crossedMaintenanceTime =
3509 mNextLightMaintenanceAlarmTime > 0 && nowElapsed >= mNextLightMaintenanceAlarmTime;
3510 final boolean crossedProgressionTime =
3511 mNextLightAlarmTime > 0 && nowElapsed >= mNextLightAlarmTime;
3512 final boolean enterMaintenance;
3513 if (crossedMaintenanceTime) {
3514 if (crossedProgressionTime) {
3515 enterMaintenance = (mNextLightAlarmTime <= mNextLightMaintenanceAlarmTime);
3516 } else {
3517 enterMaintenance = true;
3518 }
3519 } else if (crossedProgressionTime) {
3520 enterMaintenance = false;
3521 } else if (forceProgression) {
3522 // This will happen for adb commands, unit tests,
3523 // and when we're in WAITING_FOR_NETWORK and the network connects.
3524 enterMaintenance =
3525 mLightState == LIGHT_STATE_IDLE
3526 || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK;
3527 } else {
3528 Slog.wtfStack(TAG, "stepLightIdleStateLocked called in invalid state: " + mLightState);
3529 return;
3530 }
3531
3532 if (enterMaintenance) {
3533 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
3534 // We have been idling long enough, now it is time to do some work.
3535 mActiveIdleOpCount = 1;
3536 mActiveIdleWakeLock.acquire();
3537 mMaintenanceStartTime = SystemClock.elapsedRealtime();
3538 if (mCurLightIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
3539 mCurLightIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
3540 } else if (mCurLightIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
3541 mCurLightIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
3542 }
3543 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
3544 (long) (mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
3545 // We're entering MAINTENANCE. It should end curLightIdleBudget time from now.
3546 // The next maintenance window should be curLightIdleBudget + nextLightIdleDelay
3547 // time from now.
3548 scheduleLightAlarmLocked(mCurLightIdleBudget, mConstants.FLEX_TIME_SHORT);
3549 scheduleLightMaintenanceAlarmLocked(mCurLightIdleBudget + mNextLightIdleDelay);
3550 moveToLightStateLocked(LIGHT_STATE_IDLE_MAINTENANCE, reason);
3551 addEvent(EVENT_LIGHT_MAINTENANCE, null);
3552 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
3553 } else {
3554 // We'd like to do maintenance, but currently don't have network
3555 // connectivity... let's try to wait until the network comes back.
3556 // We'll only wait for another full idle period, however, and then give up.
3557 scheduleLightMaintenanceAlarmLocked(mNextLightIdleDelay);
3558 cancelLightAlarmLocked();
3559 moveToLightStateLocked(LIGHT_STATE_WAITING_FOR_NETWORK, reason);
3560 }
3561 } else {
3562 if (mMaintenanceStartTime != 0) {
3563 // Cap duration at budget since the non-wakeup alarm to exit maintenance may
3564 // not fire at the exact intended time, but once the system is up, we will stop
3565 // more ongoing work.
3566 long duration = Math.min(mCurLightIdleBudget,
3567 SystemClock.elapsedRealtime() - mMaintenanceStartTime);
3568 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
3569 // We didn't use up all of our minimum budget; add this to the reserve.
3570 mCurLightIdleBudget +=
3571 (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET - duration);
3572 } else {
3573 // We used more than our minimum budget; this comes out of the reserve.
3574 mCurLightIdleBudget -=
3575 (duration - mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
3576 }
3577 }
3578 mMaintenanceStartTime = 0;
3579 // We're entering IDLE. We may have used less than curLightIdleBudget for the
3580 // maintenance window, so reschedule the alarm starting from now.
3581 scheduleLightMaintenanceAlarmLocked(mNextLightIdleDelay);
3582 cancelLightAlarmLocked();
3583 moveToLightStateLocked(LIGHT_STATE_IDLE, reason);
3584 addEvent(EVENT_LIGHT_IDLE, null);
3585 mGoingIdleWakeLock.acquire();
3586 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
3587 }
3588 }
3589
3590 @VisibleForTesting
3591 int getState() {
3592 synchronized (this) {
3593 return mState;
3594 }
3595 }
3596
3597 /**
3598 * Returns true if there's an upcoming AlarmClock alarm that is soon enough to prevent the
3599 * device from going into idle.
3600 */
3601 private boolean isUpcomingAlarmClock() {
3602 return mInjector.getElapsedRealtime() + mConstants.MIN_TIME_TO_ALARM
3603 >= mAlarmManager.getNextWakeFromIdleTime();
3604 }
3605
3606 @VisibleForTesting
3607 @GuardedBy("this")
3608 void stepIdleStateLocked(String reason) {
3609 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
3610 EventLogTags.writeDeviceIdleStep();
3611
3612 if (isUpcomingAlarmClock()) {
3613 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
3614 if (mState != STATE_ACTIVE) {
3615 mActiveReason = ACTIVE_REASON_ALARM;
3616 becomeActiveLocked("alarm", Process.myUid());
3617 becomeInactiveIfAppropriateLocked();
3618 }
3619 return;
3620 }
3621
3622 if (mNumBlockingConstraints != 0 && !mForceIdle) {
3623 // We have some constraints from other parts of the system server preventing
3624 // us from moving to the next state.
3625 if (DEBUG) {
3626 Slog.i(TAG, "Cannot step idle state. Blocked by: " + mConstraints.values().stream()
3627 .filter(x -> x.active)
3628 .map(x -> x.name)
3629 .collect(Collectors.joining(",")));
3630 }
3631 return;
3632 }
3633
3634 switch (mState) {
3635 case STATE_INACTIVE:
3636 // We have now been inactive long enough, it is time to start looking
3637 // for motion and sleep some more while doing so.
3638 startMonitoringMotionLocked();
3639 long delay = mConstants.IDLE_AFTER_INACTIVE_TIMEOUT;
3640 if (shouldUseIdleTimeoutFactorLocked()) {
3641 delay = (long) (mPreIdleFactor * delay);
3642 }
3643 scheduleAlarmLocked(delay, false);
3644 moveToStateLocked(STATE_IDLE_PENDING, reason);
3645 break;
3646 case STATE_IDLE_PENDING:
3647 cancelLocatingLocked();
3648 mLocated = false;
3649 mLastGenericLocation = null;
3650 mLastGpsLocation = null;
3651 moveToStateLocked(STATE_SENSING, reason);
3652
3653 // Wait for open constraints and an accelerometer reading before moving on.
3654 if (mUseMotionSensor && mAnyMotionDetector.hasSensor()) {
3655 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
3656 mNotMoving = false;
3657 mAnyMotionDetector.checkForAnyMotion();
3658 break;
3659 } else if (mNumBlockingConstraints != 0) {
3660 cancelAlarmLocked();
3661 break;
3662 }
3663
3664 mNotMoving = true;
3665 // Otherwise, fall through and check this off the list of requirements.
3666 case STATE_SENSING:
3667 cancelSensingTimeoutAlarmLocked();
3668 moveToStateLocked(STATE_LOCATING, reason);
3669 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
3670 LocationManager locationManager = mInjector.getLocationManager();
3671 if (locationManager != null
3672 && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
3673 locationManager.requestLocationUpdates(mLocationRequest,
3674 mGenericLocationListener, mHandler.getLooper());
3675 mLocating = true;
3676 } else {
3677 mHasNetworkLocation = false;
3678 }
3679 if (locationManager != null
3680 && locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
3681 mHasGps = true;
3682 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
3683 mGpsLocationListener, mHandler.getLooper());
3684 mLocating = true;
3685 } else {
3686 mHasGps = false;
3687 }
3688 // If we have a location provider, we're all set, the listeners will move state
3689 // forward.
3690 if (mLocating) {
3691 break;
3692 }
3693
3694 // Otherwise, we have to move from locating into idle maintenance.
3695 case STATE_LOCATING:
3696 cancelAlarmLocked();
3697 cancelLocatingLocked();
3698 mAnyMotionDetector.stop();
3699
3700 // Intentional fallthrough -- time to go into IDLE state.
3701 case STATE_QUICK_DOZE_DELAY:
3702 // Reset the upcoming idle delays.
3703 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
3704 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
3705
3706 // Everything is in place to go into IDLE state.
3707 case STATE_IDLE_MAINTENANCE:
3708 scheduleAlarmLocked(mNextIdleDelay, true);
3709 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
3710 " ms.");
3711 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
3712 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
3713 mIdleStartTime = SystemClock.elapsedRealtime();
3714 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
3715 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
3716 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
3717 }
3718 moveToStateLocked(STATE_IDLE, reason);
3719 if (mLightState != LIGHT_STATE_OVERRIDE) {
3720 moveToLightStateLocked(LIGHT_STATE_OVERRIDE, "deep");
3721 cancelAllLightAlarmsLocked();
3722 }
3723 addEvent(EVENT_DEEP_IDLE, null);
3724 mGoingIdleWakeLock.acquire();
3725 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
3726 break;
3727 case STATE_IDLE:
3728 // We have been idling long enough, now it is time to do some work.
3729 mActiveIdleOpCount = 1;
3730 mActiveIdleWakeLock.acquire();
3731 scheduleAlarmLocked(mNextIdlePendingDelay, false);
3732 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
3733 "Next alarm in " + mNextIdlePendingDelay + " ms.");
3734 mMaintenanceStartTime = SystemClock.elapsedRealtime();
3735 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
3736 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
3737 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
3738 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
3739 }
3740 moveToStateLocked(STATE_IDLE_MAINTENANCE, reason);
3741 addEvent(EVENT_DEEP_MAINTENANCE, null);
3742 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
3743 break;
3744 }
3745 }
3746
3747 @GuardedBy("this")
3748 private void moveToLightStateLocked(int state, String reason) {
3749 if (DEBUG) {
3750 Slog.d(TAG, String.format("Moved from LIGHT_STATE_%s to LIGHT_STATE_%s.",
3751 lightStateToString(mLightState), lightStateToString(state)));
3752 }
3753 mLightState = state;
3754 EventLogTags.writeDeviceIdleLight(mLightState, reason);
3755 // This is currently how to set the current state in a trace.
3756 Trace.traceCounter(Trace.TRACE_TAG_SYSTEM_SERVER, "DozeLightState", state);
3757 }
3758
3759 @GuardedBy("this")
3760 private void moveToStateLocked(int state, String reason) {
3761 if (DEBUG) {
3762 Slog.d(TAG, String.format("Moved from STATE_%s to STATE_%s.",
3763 stateToString(mState), stateToString(state)));
3764 }
3765 mState = state;
3766 EventLogTags.writeDeviceIdle(mState, reason);
3767 // This is currently how to set the current state in a trace.
3768 Trace.traceCounter(Trace.TRACE_TAG_SYSTEM_SERVER, "DozeDeepState", state);
3769 updateActiveConstraintsLocked();
3770 }
3771
3772 void incActiveIdleOps() {
3773 synchronized (this) {
3774 mActiveIdleOpCount++;
3775 }
3776 }
3777
3778 void decActiveIdleOps() {
3779 synchronized (this) {
3780 mActiveIdleOpCount--;
3781 if (mActiveIdleOpCount <= 0) {
3782 exitMaintenanceEarlyIfNeededLocked();
3783 mActiveIdleWakeLock.release();
3784 }
3785 }
3786 }
3787
3788 /** Must only be used in tests. */
3789 @VisibleForTesting
3790 void setActiveIdleOpsForTest(int count) {
3791 synchronized (this) {
3792 mActiveIdleOpCount = count;
3793 }
3794 }
3795
3796 void setJobsActive(boolean active) {
3797 synchronized (this) {
3798 mJobsActive = active;
3799 if (!active) {
3800 exitMaintenanceEarlyIfNeededLocked();
3801 }
3802 }
3803 }
3804
3805 void setAlarmsActive(boolean active) {
3806 synchronized (this) {
3807 mAlarmsActive = active;
3808 if (!active) {
3809 exitMaintenanceEarlyIfNeededLocked();
3810 }
3811 }
3812 }
3813
3814 @VisibleForTesting
3815 int setPreIdleTimeoutMode(int mode) {
3816 return setPreIdleTimeoutFactor(getPreIdleTimeoutByMode(mode));
3817 }
3818
3819 @VisibleForTesting
3820 float getPreIdleTimeoutByMode(int mode) {
3821 switch (mode) {
3822 case PowerManager.PRE_IDLE_TIMEOUT_MODE_LONG: {
3823 return mConstants.PRE_IDLE_FACTOR_LONG;
3824 }
3825 case PowerManager.PRE_IDLE_TIMEOUT_MODE_SHORT: {
3826 return mConstants.PRE_IDLE_FACTOR_SHORT;
3827 }
3828 case PowerManager.PRE_IDLE_TIMEOUT_MODE_NORMAL: {
3829 return 1.0f;
3830 }
3831 default: {
3832 Slog.w(TAG, "Invalid time out factor mode: " + mode);
3833 return 1.0f;
3834 }
3835 }
3836 }
3837
3838 @VisibleForTesting
3839 float getPreIdleTimeoutFactor() {
3840 synchronized (this) {
3841 return mPreIdleFactor;
3842 }
3843 }
3844
3845 @VisibleForTesting
3846 int setPreIdleTimeoutFactor(float ratio) {
3847 synchronized (this) {
3848 if (!mDeepEnabled) {
3849 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: Deep Idle disable");
3850 return SET_IDLE_FACTOR_RESULT_NOT_SUPPORT;
3851 } else if (ratio <= MIN_PRE_IDLE_FACTOR_CHANGE) {
3852 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: Invalid input");
3853 return SET_IDLE_FACTOR_RESULT_INVALID;
3854 } else if (Math.abs(ratio - mPreIdleFactor) < MIN_PRE_IDLE_FACTOR_CHANGE) {
3855 if (DEBUG) {
3856 Slog.d(TAG, "setPreIdleTimeoutFactor: New factor same as previous factor");
3857 }
3858 return SET_IDLE_FACTOR_RESULT_IGNORED;
3859 }
3860 mLastPreIdleFactor = mPreIdleFactor;
3861 mPreIdleFactor = ratio;
3862 }
3863 if (DEBUG) Slog.d(TAG, "setPreIdleTimeoutFactor: " + ratio);
3864 postUpdatePreIdleFactor();
3865 return SET_IDLE_FACTOR_RESULT_OK;
3866 }
3867
3868 @VisibleForTesting
3869 void resetPreIdleTimeoutMode() {
3870 synchronized (this) {
3871 mLastPreIdleFactor = mPreIdleFactor;
3872 mPreIdleFactor = 1.0f;
3873 }
3874 if (DEBUG) Slog.d(TAG, "resetPreIdleTimeoutMode to 1.0");
3875 postResetPreIdleTimeoutFactor();
3876 }
3877
3878 private void postUpdatePreIdleFactor() {
3879 mHandler.sendEmptyMessage(MSG_UPDATE_PRE_IDLE_TIMEOUT_FACTOR);
3880 }
3881
3882 private void postResetPreIdleTimeoutFactor() {
3883 mHandler.sendEmptyMessage(MSG_RESET_PRE_IDLE_TIMEOUT_FACTOR);
3884 }
3885
3886 private void updatePreIdleFactor() {
3887 synchronized (this) {
3888 if (!shouldUseIdleTimeoutFactorLocked()) {
3889 return;
3890 }
3891 if (mState == STATE_INACTIVE || mState == STATE_IDLE_PENDING) {
3892 if (mNextAlarmTime == 0) {
3893 return;
3894 }
3895 long delay = mNextAlarmTime - SystemClock.elapsedRealtime();
3896 if (delay < MIN_STATE_STEP_ALARM_CHANGE) {
3897 return;
3898 }
3899 long newDelay = (long) (delay / mLastPreIdleFactor * mPreIdleFactor);
3900 if (Math.abs(delay - newDelay) < MIN_STATE_STEP_ALARM_CHANGE) {
3901 return;
3902 }
3903 scheduleAlarmLocked(newDelay, false);
3904 }
3905 }
3906 }
3907
3908 private void maybeDoImmediateMaintenance() {
3909 synchronized (this) {
3910 if (mState == STATE_IDLE) {
3911 long duration = SystemClock.elapsedRealtime() - mIdleStartTime;
3912 /* Let's trgger a immediate maintenance,
3913 * if it has been idle for a long time */
3914 if (duration > mConstants.IDLE_TIMEOUT) {
3915 scheduleAlarmLocked(0, false);
3916 }
3917 }
3918 }
3919 }
3920
3921 @GuardedBy("this")
3922 private boolean shouldUseIdleTimeoutFactorLocked() {
3923 // exclude ACTIVE_REASON_MOTION, for exclude device in pocket case
3924 if (mActiveReason == ACTIVE_REASON_MOTION) {
3925 return false;
3926 }
3927 return true;
3928 }
3929
3930 /** Must only be used in tests. */
3931 @VisibleForTesting
3932 void setIdleStartTimeForTest(long idleStartTime) {
3933 synchronized (this) {
3934 mIdleStartTime = idleStartTime;
3935 maybeDoImmediateMaintenance();
3936 }
3937 }
3938
3939 @VisibleForTesting
3940 long getNextAlarmTime() {
3941 synchronized (this) {
3942 return mNextAlarmTime;
3943 }
3944 }
3945
3946 @GuardedBy("this")
3947 boolean isOpsInactiveLocked() {
3948 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
3949 }
3950
3951 @GuardedBy("this")
3952 void exitMaintenanceEarlyIfNeededLocked() {
3953 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE) {
3954 if (isOpsInactiveLocked()) {
3955 final long now = SystemClock.elapsedRealtime();
3956 if (DEBUG) {
3957 StringBuilder sb = new StringBuilder();
3958 sb.append("Exit: start=");
3959 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
3960 sb.append(" now=");
3961 TimeUtils.formatDuration(now, sb);
3962 Slog.d(TAG, sb.toString());
3963 }
3964 if (mState == STATE_IDLE_MAINTENANCE) {
3965 stepIdleStateLocked("s:early");
3966 } else {
3967 stepLightIdleStateLocked("s:early", /* forceProgression */ true);
3968 }
3969 }
3970 }
3971 }
3972
3973 @GuardedBy("this")
3974 void motionLocked() {
3975 if (DEBUG) Slog.d(TAG, "motionLocked()");
3976 mLastMotionEventElapsed = mInjector.getElapsedRealtime();
3977 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
3978 }
3979
3980 @GuardedBy("this")
3981 void handleMotionDetectedLocked(long timeout, String type) {
3982 if (mStationaryListeners.size() > 0) {
3983 postStationaryStatusUpdated();
3984 cancelMotionTimeoutAlarmLocked();
3985 // We need to re-register the motion listener, but we don't want the sensors to be
3986 // constantly active or to churn the CPU by registering too early, register after some
3987 // delay.
3988 scheduleMotionRegistrationAlarmLocked();
3989 }
3990 if (mQuickDozeActivated && !mQuickDozeActivatedWhileIdling) {
3991 // Don't exit idle due to motion if quick doze is enabled.
3992 // However, if the device started idling due to the normal progression (going through
3993 // all the states) and then had quick doze activated, come out briefly on motion so the
3994 // user can get slightly fresher content.
3995 return;
3996 }
3997 maybeStopMonitoringMotionLocked();
3998 // The device is not yet active, so we want to go back to the pending idle
3999 // state to wait again for no motion. Note that we only monitor for motion
4000 // after moving out of the inactive state, so no need to worry about that.
4001 final boolean becomeInactive = mState != STATE_ACTIVE
4002 || mLightState == LIGHT_STATE_OVERRIDE;
4003 // We only want to change the IDLE state if it's OVERRIDE.
4004 becomeActiveLocked(type, Process.myUid(), timeout, mLightState == LIGHT_STATE_OVERRIDE);
4005 if (becomeInactive) {
4006 becomeInactiveIfAppropriateLocked();
4007 }
4008 }
4009
4010 @GuardedBy("this")
4011 void receivedGenericLocationLocked(Location location) {
4012 if (mState != STATE_LOCATING) {
4013 cancelLocatingLocked();
4014 return;
4015 }
4016 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
4017 mLastGenericLocation = new Location(location);
4018 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
4019 return;
4020 }
4021 mLocated = true;
4022 if (mNotMoving) {
4023 stepIdleStateLocked("s:location");
4024 }
4025 }
4026
4027 @GuardedBy("this")
4028 void receivedGpsLocationLocked(Location location) {
4029 if (mState != STATE_LOCATING) {
4030 cancelLocatingLocked();
4031 return;
4032 }
4033 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
4034 mLastGpsLocation = new Location(location);
4035 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
4036 return;
4037 }
4038 mLocated = true;
4039 if (mNotMoving) {
4040 stepIdleStateLocked("s:gps");
4041 }
4042 }
4043
4044 void startMonitoringMotionLocked() {
4045 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
4046 if (mMotionSensor != null && !mMotionListener.active) {
4047 mMotionListener.registerLocked();
4048 }
4049 }
4050
4051 /**
4052 * Stops motion monitoring. Will not stop monitoring if there are registered stationary
4053 * listeners.
4054 */
4055 private void maybeStopMonitoringMotionLocked() {
4056 if (DEBUG) Slog.d(TAG, "maybeStopMonitoringMotionLocked()");
4057 if (mMotionSensor != null && mStationaryListeners.size() == 0) {
4058 if (mMotionListener.active) {
4059 mMotionListener.unregisterLocked();
4060 cancelMotionTimeoutAlarmLocked();
4061 }
4062 cancelMotionRegistrationAlarmLocked();
4063 }
4064 }
4065
4066 @GuardedBy("this")
4067 void cancelAlarmLocked() {
4068 if (mNextAlarmTime != 0) {
4069 mNextAlarmTime = 0;
4070 mAlarmManager.cancel(mDeepAlarmListener);
4071 }
4072 }
4073
4074 @GuardedBy("this")
4075 private void cancelAllLightAlarmsLocked() {
4076 cancelLightAlarmLocked();
4077 cancelLightMaintenanceAlarmLocked();
4078 }
4079
4080 @GuardedBy("this")
4081 private void cancelLightAlarmLocked() {
4082 if (mNextLightAlarmTime != 0) {
4083 mNextLightAlarmTime = 0;
4084 mAlarmManager.cancel(mLightAlarmListener);
4085 }
4086 }
4087
4088 @GuardedBy("this")
4089 private void cancelLightMaintenanceAlarmLocked() {
4090 if (mNextLightMaintenanceAlarmTime != 0) {
4091 mNextLightMaintenanceAlarmTime = 0;
4092 mAlarmManager.cancel(mLightMaintenanceAlarmListener);
4093 }
4094 }
4095
4096 @GuardedBy("this")
4097 void cancelLocatingLocked() {
4098 if (mLocating) {
4099 LocationManager locationManager = mInjector.getLocationManager();
4100 locationManager.removeUpdates(mGenericLocationListener);
4101 locationManager.removeUpdates(mGpsLocationListener);
4102 mLocating = false;
4103 }
4104 }
4105
4106 private void cancelMotionTimeoutAlarmLocked() {
4107 mAlarmManager.cancel(mMotionTimeoutAlarmListener);
4108 }
4109
4110 private void cancelMotionRegistrationAlarmLocked() {
4111 mAlarmManager.cancel(mMotionRegistrationAlarmListener);
4112 }
4113
4114 @GuardedBy("this")
4115 void cancelSensingTimeoutAlarmLocked() {
4116 if (mNextSensingTimeoutAlarmTime != 0) {
4117 mNextSensingTimeoutAlarmTime = 0;
4118 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
4119 }
4120 }
4121
4122 @GuardedBy("this")
4123 void scheduleAlarmLocked(long delay, boolean idleUntil) {
4124 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
4125
4126 if (mUseMotionSensor && mMotionSensor == null
4127 && mState != STATE_QUICK_DOZE_DELAY
4128 && mState != STATE_IDLE
4129 && mState != STATE_IDLE_MAINTENANCE) {
4130 // If there is no motion sensor on this device, but we need one, then we won't schedule
4131 // alarms, because we can't determine if the device is not moving. This effectively
4132 // turns off normal execution of device idling, although it is still possible to
4133 // manually poke it by pretending like the alarm is going off.
4134 // STATE_QUICK_DOZE_DELAY skips the motion sensing so if the state is past the motion
4135 // sensing stage (ie, is QUICK_DOZE_DELAY, IDLE, or IDLE_MAINTENANCE), then idling
4136 // can continue until the user interacts with the device.
4137 return;
4138 }
4139 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
4140 if (idleUntil) {
4141 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4142 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
4143 } else if (mState == STATE_LOCATING) {
4144 // Use setExact so we don't keep the GPS active for too long.
4145 mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4146 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
4147 } else {
4148 if (mConstants.USE_WINDOW_ALARMS) {
4149 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4150 mNextAlarmTime, mConstants.FLEX_TIME_SHORT,
4151 "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
4152 } else {
4153 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4154 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
4155 }
4156 }
4157 }
4158
4159 @GuardedBy("this")
4160 @VisibleForTesting
4161 void scheduleLightAlarmLocked(long delay, long flex) {
4162 if (DEBUG) {
4163 Slog.d(TAG, "scheduleLightAlarmLocked(" + delay
4164 + (mConstants.USE_WINDOW_ALARMS ? "/" + flex : "")
4165 + ")");
4166 }
4167 mNextLightAlarmTime = mInjector.getElapsedRealtime() + delay;
4168 if (mConstants.USE_WINDOW_ALARMS) {
4169 mAlarmManager.setWindow(
4170 AlarmManager.ELAPSED_REALTIME,
4171 mNextLightAlarmTime, flex,
4172 "DeviceIdleController.light", mLightAlarmListener, mHandler);
4173 } else {
4174 mAlarmManager.set(
4175 AlarmManager.ELAPSED_REALTIME,
4176 mNextLightAlarmTime,
4177 "DeviceIdleController.light", mLightAlarmListener, mHandler);
4178 }
4179 }
4180
4181 @GuardedBy("this")
4182 @VisibleForTesting
4183 void scheduleLightMaintenanceAlarmLocked(long delay) {
4184 if (DEBUG) {
4185 Slog.d(TAG, "scheduleLightMaintenanceAlarmLocked(" + delay + ")");
4186 }
4187 mNextLightMaintenanceAlarmTime = mInjector.getElapsedRealtime() + delay;
4188 mAlarmManager.setWindow(
4189 AlarmManager.ELAPSED_REALTIME_WAKEUP,
4190 mNextLightMaintenanceAlarmTime, mConstants.FLEX_TIME_SHORT,
4191 "DeviceIdleController.light", mLightMaintenanceAlarmListener, mHandler);
4192 }
4193
4194 @VisibleForTesting
4195 long getNextLightAlarmTimeForTesting() {
4196 synchronized (this) {
4197 return mNextLightAlarmTime;
4198 }
4199 }
4200
4201 @VisibleForTesting
4202 long getNextLightMaintenanceAlarmTimeForTesting() {
4203 synchronized (this) {
4204 return mNextLightMaintenanceAlarmTime;
4205 }
4206 }
4207
4208 private void scheduleMotionRegistrationAlarmLocked() {
4209 if (DEBUG) Slog.d(TAG, "scheduleMotionRegistrationAlarmLocked");
4210 long nextMotionRegistrationAlarmTime =
4211 mInjector.getElapsedRealtime() + mConstants.MOTION_INACTIVE_TIMEOUT / 2;
4212 if (mConstants.USE_WINDOW_ALARMS) {
4213 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4214 nextMotionRegistrationAlarmTime, mConstants.MOTION_INACTIVE_TIMEOUT_FLEX,
4215 "DeviceIdleController.motion_registration", mMotionRegistrationAlarmListener,
4216 mHandler);
4217 } else {
4218 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextMotionRegistrationAlarmTime,
4219 "DeviceIdleController.motion_registration", mMotionRegistrationAlarmListener,
4220 mHandler);
4221 }
4222 }
4223
4224 private void scheduleMotionTimeoutAlarmLocked() {
4225 if (DEBUG) Slog.d(TAG, "scheduleMotionAlarmLocked");
4226 long nextMotionTimeoutAlarmTime =
4227 mInjector.getElapsedRealtime() + mConstants.MOTION_INACTIVE_TIMEOUT;
4228 if (mConstants.USE_WINDOW_ALARMS) {
4229 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4230 nextMotionTimeoutAlarmTime,
4231 mConstants.MOTION_INACTIVE_TIMEOUT_FLEX,
4232 "DeviceIdleController.motion", mMotionTimeoutAlarmListener, mHandler);
4233 } else {
4234 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextMotionTimeoutAlarmTime,
4235 "DeviceIdleController.motion", mMotionTimeoutAlarmListener, mHandler);
4236 }
4237 }
4238
4239 @GuardedBy("this")
4240 void scheduleSensingTimeoutAlarmLocked(long delay) {
4241 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
4242 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
4243 if (mConstants.USE_WINDOW_ALARMS) {
4244 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP,
4245 mNextSensingTimeoutAlarmTime,
4246 mConstants.FLEX_TIME_SHORT,
4247 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
4248 } else {
4249 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
4250 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
4251 }
4252 }
4253
4254 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
4255 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
4256 outAppIds.clear();
4257 if (systemApps != null) {
4258 for (int i = 0; i < systemApps.size(); i++) {
4259 outAppIds.put(systemApps.valueAt(i), true);
4260 }
4261 }
4262 if (userApps != null) {
4263 for (int i = 0; i < userApps.size(); i++) {
4264 outAppIds.put(userApps.valueAt(i), true);
4265 }
4266 }
4267 int size = outAppIds.size();
4268 int[] appids = new int[size];
4269 for (int i = 0; i < size; i++) {
4270 appids[i] = outAppIds.keyAt(i);
4271 }
4272 return appids;
4273 }
4274
4275 private void updateWhitelistAppIdsLocked() {
4276 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
4277 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
4278 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
4279 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
4280 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
4281 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
4282 if (mLocalActivityManager != null) {
4283 mLocalActivityManager.setDeviceIdleAllowlist(
4284 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
4285 }
4286 if (mLocalPowerManager != null) {
4287 if (DEBUG) {
4288 Slog.d(TAG, "Setting wakelock whitelist to "
4289 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
4290 }
4291 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
4292 }
4293 passWhiteListsToForceAppStandbyTrackerLocked();
4294 }
4295
4296 /**
4297 * update temp allowlist.
4298 * @param uid uid to add or remove from temp allowlist.
4299 * @param adding true to add to temp allowlist, false to remove from temp allowlist.
4300 * @param durationMs duration in milliseconds to add to temp allowlist, only valid when
4301 * param adding is true.
4302 * @param type temp allowlist type defined at {@link TempAllowListType}
4303 * @prama reasonCode one of {@Link ReasonCode}
4304 * @param reason A human-readable reason for logging purposes.
4305 * @param callingUid the callingUid that setup this temp-allowlist, only valid when param adding
4306 * is true.
4307 */
4308 @GuardedBy("this")
4309 private void updateTempWhitelistAppIdsLocked(int uid, boolean adding, long durationMs,
4310 @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason,
4311 int callingUid) {
4312 final int size = mTempWhitelistAppIdEndTimes.size();
4313 if (mTempWhitelistAppIdArray.length != size) {
4314 mTempWhitelistAppIdArray = new int[size];
4315 }
4316 for (int i = 0; i < size; i++) {
4317 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
4318 }
4319 if (mLocalActivityManager != null) {
4320 if (DEBUG) {
4321 Slog.d(TAG, "Setting activity manager temp whitelist to "
4322 + Arrays.toString(mTempWhitelistAppIdArray));
4323 }
4324 mLocalActivityManager.updateDeviceIdleTempAllowlist(mTempWhitelistAppIdArray, uid,
4325 adding, durationMs, type, reasonCode, reason, callingUid);
4326 }
4327 if (mLocalPowerManager != null) {
4328 if (DEBUG) {
4329 Slog.d(TAG, "Setting wakelock temp whitelist to "
4330 + Arrays.toString(mTempWhitelistAppIdArray));
4331 }
4332 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
4333 }
4334 passWhiteListsToForceAppStandbyTrackerLocked();
4335 }
4336
4337 private void reportPowerSaveWhitelistChangedLocked() {
4338 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
4339 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4340 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
4341 }
4342
4343 private void reportTempWhitelistChangedLocked(final int uid, final boolean added) {
4344 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, uid, added ? 1 : 0)
4345 .sendToTarget();
4346 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
4347 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4348 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
4349 }
4350
4351 private void passWhiteListsToForceAppStandbyTrackerLocked() {
4352 mAppStateTracker.setPowerSaveExemptionListAppIds(
4353 mPowerSaveWhitelistExceptIdleAppIdArray,
4354 mPowerSaveWhitelistUserAppIdArray,
4355 mTempWhitelistAppIdArray);
4356 }
4357
4358 @GuardedBy("this")
4359 void readConfigFileLocked() {
4360 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
4361 mPowerSaveWhitelistUserApps.clear();
4362 FileInputStream stream;
4363 try {
4364 stream = mConfigFile.openRead();
4365 } catch (FileNotFoundException e) {
4366 return;
4367 }
4368 try {
4369 XmlPullParser parser = Xml.newPullParser();
4370 parser.setInput(stream, StandardCharsets.UTF_8.name());
4371 readConfigFileLocked(parser);
4372 } catch (XmlPullParserException e) {
4373 } finally {
4374 try {
4375 stream.close();
4376 } catch (IOException e) {
4377 }
4378 }
4379 }
4380
4381 @GuardedBy("this")
4382 private void readConfigFileLocked(XmlPullParser parser) {
4383 final PackageManager pm = getContext().getPackageManager();
4384
4385 try {
4386 int type;
4387 while ((type = parser.next()) != XmlPullParser.START_TAG
4388 && type != XmlPullParser.END_DOCUMENT) {
4389 ;
4390 }
4391
4392 if (type != XmlPullParser.START_TAG) {
4393 throw new IllegalStateException("no start tag found");
4394 }
4395
4396 int outerDepth = parser.getDepth();
4397 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
4398 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
4399 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
4400 continue;
4401 }
4402
4403 String tagName = parser.getName();
4404 switch (tagName) {
4405 case "wl":
4406 String name = parser.getAttributeValue(null, "n");
4407 if (name != null) {
4408 try {
4409 ApplicationInfo ai = pm.getApplicationInfo(name,
4410 PackageManager.MATCH_ANY_USER);
4411 mPowerSaveWhitelistUserApps.put(ai.packageName,
4412 UserHandle.getAppId(ai.uid));
4413 } catch (PackageManager.NameNotFoundException e) {
4414 }
4415 }
4416 break;
4417 case "un-wl":
4418 final String packageName = parser.getAttributeValue(null, "n");
4419 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
4420 mRemovedFromSystemWhitelistApps.put(packageName,
4421 mPowerSaveWhitelistApps.remove(packageName));
4422 }
4423 break;
4424 default:
4425 Slog.w(TAG, "Unknown element under <config>: "
4426 + parser.getName());
4427 XmlUtils.skipCurrentTag(parser);
4428 break;
4429 }
4430 }
4431
4432 } catch (IllegalStateException e) {
4433 Slog.w(TAG, "Failed parsing config " + e);
4434 } catch (NullPointerException e) {
4435 Slog.w(TAG, "Failed parsing config " + e);
4436 } catch (NumberFormatException e) {
4437 Slog.w(TAG, "Failed parsing config " + e);
4438 } catch (XmlPullParserException e) {
4439 Slog.w(TAG, "Failed parsing config " + e);
4440 } catch (IOException e) {
4441 Slog.w(TAG, "Failed parsing config " + e);
4442 } catch (IndexOutOfBoundsException e) {
4443 Slog.w(TAG, "Failed parsing config " + e);
4444 }
4445 }
4446
4447 void writeConfigFileLocked() {
4448 mHandler.removeMessages(MSG_WRITE_CONFIG);
4449 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
4450 }
4451
4452 void handleWriteConfigFile() {
4453 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
4454
4455 try {
4456 synchronized (this) {
4457 XmlSerializer out = new FastXmlSerializer();
4458 out.setOutput(memStream, StandardCharsets.UTF_8.name());
4459 writeConfigFileLocked(out);
4460 }
4461 } catch (IOException e) {
4462 }
4463
4464 synchronized (mConfigFile) {
4465 FileOutputStream stream = null;
4466 try {
4467 stream = mConfigFile.startWrite();
4468 memStream.writeTo(stream);
4469 mConfigFile.finishWrite(stream);
4470 } catch (IOException e) {
4471 Slog.w(TAG, "Error writing config file", e);
4472 mConfigFile.failWrite(stream);
4473 }
4474 }
4475 }
4476
4477 void writeConfigFileLocked(XmlSerializer out) throws IOException {
4478 out.startDocument(null, true);
4479 out.startTag(null, "config");
4480 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
4481 String name = mPowerSaveWhitelistUserApps.keyAt(i);
4482 out.startTag(null, "wl");
4483 out.attribute(null, "n", name);
4484 out.endTag(null, "wl");
4485 }
4486 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
4487 out.startTag(null, "un-wl");
4488 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
4489 out.endTag(null, "un-wl");
4490 }
4491 out.endTag(null, "config");
4492 out.endDocument();
4493 }
4494
4495 static void dumpHelp(PrintWriter pw) {
4496 pw.println("Device idle controller (deviceidle) commands:");
4497 pw.println(" help");
4498 pw.println(" Print this help text.");
4499 pw.println(" step [light|deep]");
4500 pw.println(" Immediately step to next state, without waiting for alarm.");
4501 pw.println(" force-idle [light|deep]");
4502 pw.println(" Force directly into idle mode, regardless of other device state.");
4503 pw.println(" force-inactive");
4504 pw.println(" Force to be inactive, ready to freely step idle states.");
4505 pw.println(" unforce");
4506 pw.println(" Resume normal functioning after force-idle or force-inactive.");
4507 pw.println(" get [light|deep|force|screen|charging|network]");
4508 pw.println(" Retrieve the current given state.");
4509 pw.println(" disable [light|deep|all]");
4510 pw.println(" Completely disable device idle mode.");
4511 pw.println(" enable [light|deep|all]");
4512 pw.println(" Re-enable device idle mode after it had previously been disabled.");
4513 pw.println(" enabled [light|deep|all]");
4514 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
4515 pw.println(" whitelist");
4516 pw.println(" Print currently whitelisted apps.");
4517 pw.println(" whitelist [package ...]");
4518 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
4519 pw.println(" sys-whitelist [package ...|reset]");
4520 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
4521 + " to put it back in the system whitelist.");
4522 pw.println(" Note that only packages that were"
4523 + " earlier removed from the system whitelist can be added back.");
4524 pw.println(" reset will reset the whitelist to the original state");
4525 pw.println(" Prints the system whitelist if no arguments are specified");
4526 pw.println(" except-idle-whitelist [package ...|reset]");
4527 pw.println(" Prefix the package with '+' to add it to whitelist or "
4528 + "'=' to check if it is already whitelisted");
4529 pw.println(" [reset] will reset the whitelist to it's original state");
4530 pw.println(" Note that unlike <whitelist> cmd, "
4531 + "changes made using this won't be persisted across boots");
4532 pw.println(" tempwhitelist");
4533 pw.println(" Print packages that are temporarily whitelisted.");
4534 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
4535 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
4536 pw.println(" If no DURATION is specified, 10 seconds is used");
4537 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
4538 + "and any [-d] is ignored");
4539 pw.println(" motion");
4540 pw.println(" Simulate a motion event to bring the device out of deep doze");
4541 pw.println(" pre-idle-factor [0|1|2]");
4542 pw.println(" Set a new factor to idle time before step to idle"
4543 + "(inactive_to and idle_after_inactive_to)");
4544 pw.println(" reset-pre-idle-factor");
4545 pw.println(" Reset factor to idle time to default");
4546 }
4547
4548 class Shell extends ShellCommand {
4549 int userId = UserHandle.USER_SYSTEM;
4550
4551 @Override
4552 public int onCommand(String cmd) {
4553 return onShellCommand(this, cmd);
4554 }
4555
4556 @Override
4557 public void onHelp() {
4558 PrintWriter pw = getOutPrintWriter();
4559 dumpHelp(pw);
4560 }
4561 }
4562
4563 int onShellCommand(Shell shell, String cmd) {
4564 PrintWriter pw = shell.getOutPrintWriter();
4565 if ("step".equals(cmd)) {
4566 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4567 null);
4568 synchronized (this) {
4569 final long token = Binder.clearCallingIdentity();
4570 String arg = shell.getNextArg();
4571 try {
4572 if (arg == null || "deep".equals(arg)) {
4573 stepIdleStateLocked("s:shell");
4574 pw.print("Stepped to deep: ");
4575 pw.println(stateToString(mState));
4576 } else if ("light".equals(arg)) {
4577 stepLightIdleStateLocked("s:shell", /* forceProgression */ true);
4578 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
4579 } else {
4580 pw.println("Unknown idle mode: " + arg);
4581 }
4582 } finally {
4583 Binder.restoreCallingIdentity(token);
4584 }
4585 }
4586 } else if ("force-idle".equals(cmd)) {
4587 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4588 null);
4589 synchronized (this) {
4590 final long token = Binder.clearCallingIdentity();
4591 String arg = shell.getNextArg();
4592 try {
4593 if (arg == null || "deep".equals(arg)) {
4594 if (!mDeepEnabled) {
4595 pw.println("Unable to go deep idle; not enabled");
4596 return -1;
4597 }
4598 mForceIdle = true;
4599 becomeInactiveIfAppropriateLocked();
4600 int curState = mState;
4601 while (curState != STATE_IDLE) {
4602 stepIdleStateLocked("s:shell");
4603 if (curState == mState) {
4604 pw.print("Unable to go deep idle; stopped at ");
4605 pw.println(stateToString(mState));
4606 exitForceIdleLocked();
4607 return -1;
4608 }
4609 curState = mState;
4610 }
4611 pw.println("Now forced in to deep idle mode");
4612 } else if ("light".equals(arg)) {
4613 mForceIdle = true;
4614 becomeInactiveIfAppropriateLocked();
4615 int curLightState = mLightState;
4616 while (curLightState != LIGHT_STATE_IDLE) {
4617 stepLightIdleStateLocked("s:shell", /* forceProgression */ true);
4618 if (curLightState == mLightState) {
4619 pw.print("Unable to go light idle; stopped at ");
4620 pw.println(lightStateToString(mLightState));
4621 exitForceIdleLocked();
4622 return -1;
4623 }
4624 curLightState = mLightState;
4625 }
4626 pw.println("Now forced in to light idle mode");
4627 } else {
4628 pw.println("Unknown idle mode: " + arg);
4629 }
4630 } finally {
4631 Binder.restoreCallingIdentity(token);
4632 }
4633 }
4634 } else if ("force-inactive".equals(cmd)) {
4635 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4636 null);
4637 synchronized (this) {
4638 final long token = Binder.clearCallingIdentity();
4639 try {
4640 mForceIdle = true;
4641 becomeInactiveIfAppropriateLocked();
4642 pw.print("Light state: ");
4643 pw.print(lightStateToString(mLightState));
4644 pw.print(", deep state: ");
4645 pw.println(stateToString(mState));
4646 } finally {
4647 Binder.restoreCallingIdentity(token);
4648 }
4649 }
4650 } else if ("unforce".equals(cmd)) {
4651 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4652 null);
4653 synchronized (this) {
4654 final long token = Binder.clearCallingIdentity();
4655 try {
4656 exitForceIdleLocked();
4657 pw.print("Light state: ");
4658 pw.print(lightStateToString(mLightState));
4659 pw.print(", deep state: ");
4660 pw.println(stateToString(mState));
4661 } finally {
4662 Binder.restoreCallingIdentity(token);
4663 }
4664 }
4665 } else if ("get".equals(cmd)) {
4666 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4667 null);
4668 synchronized (this) {
4669 String arg = shell.getNextArg();
4670 if (arg != null) {
4671 final long token = Binder.clearCallingIdentity();
4672 try {
4673 switch (arg) {
4674 case "light": pw.println(lightStateToString(mLightState)); break;
4675 case "deep": pw.println(stateToString(mState)); break;
4676 case "force": pw.println(mForceIdle); break;
4677 case "quick": pw.println(mQuickDozeActivated); break;
4678 case "screen": pw.println(mScreenOn); break;
4679 case "charging": pw.println(mCharging); break;
4680 case "network": pw.println(mNetworkConnected); break;
4681 default: pw.println("Unknown get option: " + arg); break;
4682 }
4683 } finally {
4684 Binder.restoreCallingIdentity(token);
4685 }
4686 } else {
4687 pw.println("Argument required");
4688 }
4689 }
4690 } else if ("disable".equals(cmd)) {
4691 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4692 null);
4693 synchronized (this) {
4694 final long token = Binder.clearCallingIdentity();
4695 String arg = shell.getNextArg();
4696 try {
4697 boolean becomeActive = false;
4698 boolean valid = false;
4699 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
4700 valid = true;
4701 if (mDeepEnabled) {
4702 mDeepEnabled = false;
4703 becomeActive = true;
4704 pw.println("Deep idle mode disabled");
4705 }
4706 }
4707 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
4708 valid = true;
4709 if (mLightEnabled) {
4710 mLightEnabled = false;
4711 becomeActive = true;
4712 pw.println("Light idle mode disabled");
4713 }
4714 }
4715 if (becomeActive) {
4716 mActiveReason = ACTIVE_REASON_FORCED;
4717 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
4718 Process.myUid());
4719 }
4720 if (!valid) {
4721 pw.println("Unknown idle mode: " + arg);
4722 }
4723 } finally {
4724 Binder.restoreCallingIdentity(token);
4725 }
4726 }
4727 } else if ("enable".equals(cmd)) {
4728 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4729 null);
4730 synchronized (this) {
4731 final long token = Binder.clearCallingIdentity();
4732 String arg = shell.getNextArg();
4733 try {
4734 boolean becomeInactive = false;
4735 boolean valid = false;
4736 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
4737 valid = true;
4738 if (!mDeepEnabled) {
4739 mDeepEnabled = true;
4740 becomeInactive = true;
4741 pw.println("Deep idle mode enabled");
4742 }
4743 }
4744 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
4745 valid = true;
4746 if (!mLightEnabled) {
4747 mLightEnabled = true;
4748 becomeInactive = true;
4749 pw.println("Light idle mode enable");
4750 }
4751 }
4752 if (becomeInactive) {
4753 becomeInactiveIfAppropriateLocked();
4754 }
4755 if (!valid) {
4756 pw.println("Unknown idle mode: " + arg);
4757 }
4758 } finally {
4759 Binder.restoreCallingIdentity(token);
4760 }
4761 }
4762 } else if ("enabled".equals(cmd)) {
4763 synchronized (this) {
4764 String arg = shell.getNextArg();
4765 if (arg == null || "all".equals(arg)) {
4766 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
4767 } else if ("deep".equals(arg)) {
4768 pw.println(mDeepEnabled ? "1" : 0);
4769 } else if ("light".equals(arg)) {
4770 pw.println(mLightEnabled ? "1" : 0);
4771 } else {
4772 pw.println("Unknown idle mode: " + arg);
4773 }
4774 }
4775 } else if ("whitelist".equals(cmd)) {
4776 String arg = shell.getNextArg();
4777 if (arg != null) {
4778 getContext().enforceCallingOrSelfPermission(
4779 android.Manifest.permission.DEVICE_POWER, null);
4780 final long token = Binder.clearCallingIdentity();
4781 try {
4782 do {
4783 if (arg.length() < 1 || (arg.charAt(0) != '-'
4784 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
4785 pw.println("Package must be prefixed with +, -, or =: " + arg);
4786 return -1;
4787 }
4788 char op = arg.charAt(0);
4789 String pkg = arg.substring(1);
4790 if (op == '+') {
4791 if (addPowerSaveWhitelistAppsInternal(Collections.singletonList(pkg))
4792 == 1) {
4793 pw.println("Added: " + pkg);
4794 } else {
4795 pw.println("Unknown package: " + pkg);
4796 }
4797 } else if (op == '-') {
4798 if (removePowerSaveWhitelistAppInternal(pkg)) {
4799 pw.println("Removed: " + pkg);
4800 }
4801 } else {
4802 pw.println(getPowerSaveWhitelistAppInternal(pkg));
4803 }
4804 } while ((arg=shell.getNextArg()) != null);
4805 } finally {
4806 Binder.restoreCallingIdentity(token);
4807 }
4808 } else {
4809 synchronized (this) {
4810 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
4811 pw.print("system-excidle,");
4812 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
4813 pw.print(",");
4814 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
4815 }
4816 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
4817 pw.print("system,");
4818 pw.print(mPowerSaveWhitelistApps.keyAt(j));
4819 pw.print(",");
4820 pw.println(mPowerSaveWhitelistApps.valueAt(j));
4821 }
4822 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
4823 pw.print("user,");
4824 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
4825 pw.print(",");
4826 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
4827 }
4828 }
4829 }
4830 } else if ("tempwhitelist".equals(cmd)) {
4831 long duration = 10000;
4832 boolean removePkg = false;
4833 String opt;
4834 while ((opt=shell.getNextOption()) != null) {
4835 if ("-u".equals(opt)) {
4836 opt = shell.getNextArg();
4837 if (opt == null) {
4838 pw.println("-u requires a user number");
4839 return -1;
4840 }
4841 shell.userId = Integer.parseInt(opt);
4842 } else if ("-d".equals(opt)) {
4843 opt = shell.getNextArg();
4844 if (opt == null) {
4845 pw.println("-d requires a duration");
4846 return -1;
4847 }
4848 duration = Long.parseLong(opt);
4849 } else if ("-r".equals(opt)) {
4850 removePkg = true;
4851 }
4852 }
4853 String arg = shell.getNextArg();
4854 if (arg != null) {
4855 try {
4856 if (removePkg) {
4857 removePowerSaveTempAllowlistAppChecked(arg, shell.userId);
4858 } else {
4859 addPowerSaveTempAllowlistAppChecked(arg, duration, shell.userId,
4860 REASON_SHELL, "shell");
4861 }
4862 } catch (Exception e) {
4863 pw.println("Failed: " + e);
4864 return -1;
4865 }
4866 } else if (removePkg) {
4867 pw.println("[-r] requires a package name");
4868 return -1;
4869 } else {
4870 dumpTempWhitelistSchedule(pw, false);
4871 }
4872 } else if ("except-idle-whitelist".equals(cmd)) {
4873 getContext().enforceCallingOrSelfPermission(
4874 android.Manifest.permission.DEVICE_POWER, null);
4875 final long token = Binder.clearCallingIdentity();
4876 try {
4877 String arg = shell.getNextArg();
4878 if (arg == null) {
4879 pw.println("No arguments given");
4880 return -1;
4881 } else if ("reset".equals(arg)) {
4882 resetPowerSaveWhitelistExceptIdleInternal();
4883 } else {
4884 do {
4885 if (arg.length() < 1 || (arg.charAt(0) != '-'
4886 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
4887 pw.println("Package must be prefixed with +, -, or =: " + arg);
4888 return -1;
4889 }
4890 char op = arg.charAt(0);
4891 String pkg = arg.substring(1);
4892 if (op == '+') {
4893 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
4894 pw.println("Added: " + pkg);
4895 } else {
4896 pw.println("Unknown package: " + pkg);
4897 }
4898 } else if (op == '=') {
4899 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
4900 } else {
4901 pw.println("Unknown argument: " + arg);
4902 return -1;
4903 }
4904 } while ((arg = shell.getNextArg()) != null);
4905 }
4906 } finally {
4907 Binder.restoreCallingIdentity(token);
4908 }
4909 } else if ("sys-whitelist".equals(cmd)) {
4910 String arg = shell.getNextArg();
4911 if (arg != null) {
4912 getContext().enforceCallingOrSelfPermission(
4913 android.Manifest.permission.DEVICE_POWER, null);
4914 final long token = Binder.clearCallingIdentity();
4915 try {
4916 if ("reset".equals(arg)) {
4917 resetSystemPowerWhitelistInternal();
4918 } else {
4919 do {
4920 if (arg.length() < 1
4921 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
4922 pw.println("Package must be prefixed with + or - " + arg);
4923 return -1;
4924 }
4925 final char op = arg.charAt(0);
4926 final String pkg = arg.substring(1);
4927 switch (op) {
4928 case '+':
4929 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
4930 pw.println("Restored " + pkg);
4931 }
4932 break;
4933 case '-':
4934 if (removeSystemPowerWhitelistAppInternal(pkg)) {
4935 pw.println("Removed " + pkg);
4936 }
4937 break;
4938 }
4939 } while ((arg = shell.getNextArg()) != null);
4940 }
4941 } finally {
4942 Binder.restoreCallingIdentity(token);
4943 }
4944 } else {
4945 synchronized (this) {
4946 for (int j = 0; j < mPowerSaveWhitelistApps.size(); j++) {
4947 pw.print(mPowerSaveWhitelistApps.keyAt(j));
4948 pw.print(",");
4949 pw.println(mPowerSaveWhitelistApps.valueAt(j));
4950 }
4951 }
4952 }
4953 } else if ("motion".equals(cmd)) {
4954 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4955 null);
4956 synchronized (this) {
4957 final long token = Binder.clearCallingIdentity();
4958 try {
4959 motionLocked();
4960 pw.print("Light state: ");
4961 pw.print(lightStateToString(mLightState));
4962 pw.print(", deep state: ");
4963 pw.println(stateToString(mState));
4964 } finally {
4965 Binder.restoreCallingIdentity(token);
4966 }
4967 }
4968 } else if ("pre-idle-factor".equals(cmd)) {
4969 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
4970 null);
4971 synchronized (this) {
4972 final long token = Binder.clearCallingIdentity();
4973 int ret = SET_IDLE_FACTOR_RESULT_UNINIT;
4974 try {
4975 String arg = shell.getNextArg();
4976 boolean valid = false;
4977 int mode = 0;
4978 if (arg != null) {
4979 mode = Integer.parseInt(arg);
4980 ret = setPreIdleTimeoutMode(mode);
4981 if (ret == SET_IDLE_FACTOR_RESULT_OK) {
4982 pw.println("pre-idle-factor: " + mode);
4983 valid = true;
4984 } else if (ret == SET_IDLE_FACTOR_RESULT_NOT_SUPPORT) {
4985 valid = true;
4986 pw.println("Deep idle not supported");
4987 } else if (ret == SET_IDLE_FACTOR_RESULT_IGNORED) {
4988 valid = true;
4989 pw.println("Idle timeout factor not changed");
4990 }
4991 }
4992 if (!valid) {
4993 pw.println("Unknown idle timeout factor: " + arg
4994 + ",(error code: " + ret + ")");
4995 }
4996 } catch (NumberFormatException e) {
4997 pw.println("Unknown idle timeout factor"
4998 + ",(error code: " + ret + ")");
4999 } finally {
5000 Binder.restoreCallingIdentity(token);
5001 }
5002 }
5003 } else if ("reset-pre-idle-factor".equals(cmd)) {
5004 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
5005 null);
5006 synchronized (this) {
5007 final long token = Binder.clearCallingIdentity();
5008 try {
5009 resetPreIdleTimeoutMode();
5010 } finally {
5011 Binder.restoreCallingIdentity(token);
5012 }
5013 }
5014 } else {
5015 return shell.handleDefaultCommands(cmd);
5016 }
5017 return 0;
5018 }
5019
5020 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5021 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
5022
5023 if (args != null) {
5024 int userId = UserHandle.USER_SYSTEM;
5025 for (int i=0; i<args.length; i++) {
5026 String arg = args[i];
5027 if ("-h".equals(arg)) {
5028 dumpHelp(pw);
5029 return;
5030 } else if ("-u".equals(arg)) {
5031 i++;
5032 if (i < args.length) {
5033 arg = args[i];
5034 userId = Integer.parseInt(arg);
5035 }
5036 } else if ("-a".equals(arg)) {
5037 // Ignore, we always dump all.
5038 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
5039 pw.println("Unknown option: " + arg);
5040 return;
5041 } else {
5042 Shell shell = new Shell();
5043 shell.userId = userId;
5044 String[] newArgs = new String[args.length-i];
5045 System.arraycopy(args, i, newArgs, 0, args.length-i);
5046 shell.exec(mBinderService, null, fd, null, newArgs, null,
5047 new ResultReceiver(null));
5048 return;
5049 }
5050 }
5051 }
5052
5053 synchronized (this) {
5054 mConstants.dump(pw);
5055
5056 if (mEventCmds[0] != EVENT_NULL) {
5057 pw.println(" Idling history:");
5058 long now = SystemClock.elapsedRealtime();
5059 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
5060 int cmd = mEventCmds[i];
5061 if (cmd == EVENT_NULL) {
5062 continue;
5063 }
5064 String label;
5065 switch (mEventCmds[i]) {
5066 case EVENT_NORMAL: label = " normal"; break;
5067 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
5068 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
5069 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
5070 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
5071 default: label = " ??"; break;
5072 }
5073 pw.print(" ");
5074 pw.print(label);
5075 pw.print(": ");
5076 TimeUtils.formatDuration(mEventTimes[i], now, pw);
5077 if (mEventReasons[i] != null) {
5078 pw.print(" (");
5079 pw.print(mEventReasons[i]);
5080 pw.print(")");
5081 }
5082 pw.println();
5083
5084 }
5085 }
5086
5087 int size = mPowerSaveWhitelistAppsExceptIdle.size();
5088 if (size > 0) {
5089 pw.println(" Whitelist (except idle) system apps:");
5090 for (int i = 0; i < size; i++) {
5091 pw.print(" ");
5092 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
5093 }
5094 }
5095 size = mPowerSaveWhitelistApps.size();
5096 if (size > 0) {
5097 pw.println(" Whitelist system apps:");
5098 for (int i = 0; i < size; i++) {
5099 pw.print(" ");
5100 pw.println(mPowerSaveWhitelistApps.keyAt(i));
5101 }
5102 }
5103 size = mRemovedFromSystemWhitelistApps.size();
5104 if (size > 0) {
5105 pw.println(" Removed from whitelist system apps:");
5106 for (int i = 0; i < size; i++) {
5107 pw.print(" ");
5108 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
5109 }
5110 }
5111 size = mPowerSaveWhitelistUserApps.size();
5112 if (size > 0) {
5113 pw.println(" Whitelist user apps:");
5114 for (int i = 0; i < size; i++) {
5115 pw.print(" ");
5116 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
5117 }
5118 }
5119 size = mPowerSaveWhitelistExceptIdleAppIds.size();
5120 if (size > 0) {
5121 pw.println(" Whitelist (except idle) all app ids:");
5122 for (int i = 0; i < size; i++) {
5123 pw.print(" ");
5124 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
5125 pw.println();
5126 }
5127 }
5128 size = mPowerSaveWhitelistUserAppIds.size();
5129 if (size > 0) {
5130 pw.println(" Whitelist user app ids:");
5131 for (int i = 0; i < size; i++) {
5132 pw.print(" ");
5133 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
5134 pw.println();
5135 }
5136 }
5137 size = mPowerSaveWhitelistAllAppIds.size();
5138 if (size > 0) {
5139 pw.println(" Whitelist all app ids:");
5140 for (int i = 0; i < size; i++) {
5141 pw.print(" ");
5142 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
5143 pw.println();
5144 }
5145 }
5146 dumpTempWhitelistSchedule(pw, true);
5147
5148 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
5149 if (size > 0) {
5150 pw.println(" Temp whitelist app ids:");
5151 for (int i = 0; i < size; i++) {
5152 pw.print(" ");
5153 pw.print(mTempWhitelistAppIdArray[i]);
5154 pw.println();
5155 }
5156 }
5157
5158 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
5159 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
5160 pw.print(" mForceIdle="); pw.println(mForceIdle);
5161 pw.print(" mUseMotionSensor="); pw.print(mUseMotionSensor);
5162 if (mUseMotionSensor) {
5163 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
5164 } else {
5165 pw.println();
5166 }
5167 pw.print(" mScreenOn="); pw.println(mScreenOn);
5168 pw.print(" mScreenLocked="); pw.println(mScreenLocked);
5169 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
5170 pw.print(" mCharging="); pw.println(mCharging);
5171 if (mConstraints.size() != 0) {
5172 pw.println(" mConstraints={");
5173 for (int i = 0; i < mConstraints.size(); i++) {
5174 final DeviceIdleConstraintTracker tracker = mConstraints.valueAt(i);
5175 pw.print(" \""); pw.print(tracker.name); pw.print("\"=");
5176 if (tracker.minState == mState) {
5177 pw.println(tracker.active);
5178 } else {
5179 pw.print("ignored <mMinState="); pw.print(stateToString(tracker.minState));
5180 pw.println(">");
5181 }
5182 }
5183 pw.println(" }");
5184 }
5185 if (mUseMotionSensor || mStationaryListeners.size() > 0) {
5186 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
5187 pw.print(" mNotMoving="); pw.println(mNotMoving);
5188 pw.print(" mMotionListener.activatedTimeElapsed=");
5189 pw.println(mMotionListener.activatedTimeElapsed);
5190 pw.print(" mLastMotionEventElapsed="); pw.println(mLastMotionEventElapsed);
5191 pw.print(" "); pw.print(mStationaryListeners.size());
5192 pw.println(" stationary listeners registered");
5193 }
5194 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
5195 pw.print(mHasGps); pw.print(" mHasNetwork=");
5196 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
5197 if (mLastGenericLocation != null) {
5198 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
5199 }
5200 if (mLastGpsLocation != null) {
5201 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
5202 }
5203 pw.print(" mState="); pw.print(stateToString(mState));
5204 pw.print(" mLightState=");
5205 pw.println(lightStateToString(mLightState));
5206 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
5207 pw.println();
5208 if (mActiveIdleOpCount != 0) {
5209 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
5210 }
5211 if (mNextAlarmTime != 0) {
5212 pw.print(" mNextAlarmTime=");
5213 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
5214 pw.println();
5215 }
5216 if (mNextIdlePendingDelay != 0) {
5217 pw.print(" mNextIdlePendingDelay=");
5218 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
5219 pw.println();
5220 }
5221 if (mNextIdleDelay != 0) {
5222 pw.print(" mNextIdleDelay=");
5223 TimeUtils.formatDuration(mNextIdleDelay, pw);
5224 pw.println();
5225 }
5226 if (mNextLightIdleDelay != 0) {
5227 pw.print(" mNextLightIdleDelay=");
5228 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
5229 pw.println();
5230 }
5231 if (mNextLightAlarmTime != 0) {
5232 pw.print(" mNextLightAlarmTime=");
5233 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
5234 pw.println();
5235 }
5236 if (mNextLightMaintenanceAlarmTime != 0) {
5237 pw.print(" mNextLightMaintenanceAlarmTime=");
5238 TimeUtils.formatDuration(
5239 mNextLightMaintenanceAlarmTime, SystemClock.elapsedRealtime(), pw);
5240 pw.println();
5241 }
5242 if (mCurLightIdleBudget != 0) {
5243 pw.print(" mCurLightIdleBudget=");
5244 TimeUtils.formatDuration(mCurLightIdleBudget, pw);
5245 pw.println();
5246 }
5247 if (mMaintenanceStartTime != 0) {
5248 pw.print(" mMaintenanceStartTime=");
5249 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
5250 pw.println();
5251 }
5252 if (mJobsActive) {
5253 pw.print(" mJobsActive="); pw.println(mJobsActive);
5254 }
5255 if (mAlarmsActive) {
5256 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
5257 }
5258 if (Math.abs(mPreIdleFactor - 1.0f) > MIN_PRE_IDLE_FACTOR_CHANGE) {
5259 pw.print(" mPreIdleFactor="); pw.println(mPreIdleFactor);
5260 }
5261 }
5262 }
5263
5264 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
5265 final int size = mTempWhitelistAppIdEndTimes.size();
5266 if (size > 0) {
5267 String prefix = "";
5268 if (printTitle) {
5269 pw.println(" Temp whitelist schedule:");
5270 prefix = " ";
5271 }
5272 final long timeNow = SystemClock.elapsedRealtime();
5273 for (int i = 0; i < size; i++) {
5274 pw.print(prefix);
5275 pw.print("UID=");
5276 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
5277 pw.print(": ");
5278 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
5279 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
5280 pw.print(" - ");
5281 pw.println(entry.second);
5282 }
5283 }
5284 }
5285 }