Debian Codegraph @

apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java

raw symbols SCIP
1 /**
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17 package com.android.server.usage;
18
19 import static android.app.usage.UsageStatsManager.REASON_MAIN_DEFAULT;
20 import static android.app.usage.UsageStatsManager.REASON_MAIN_FORCED_BY_SYSTEM;
21 import static android.app.usage.UsageStatsManager.REASON_MAIN_FORCED_BY_USER;
22 import static android.app.usage.UsageStatsManager.REASON_MAIN_MASK;
23 import static android.app.usage.UsageStatsManager.REASON_MAIN_PREDICTED;
24 import static android.app.usage.UsageStatsManager.REASON_MAIN_TIMEOUT;
25 import static android.app.usage.UsageStatsManager.REASON_MAIN_USAGE;
26 import static android.app.usage.UsageStatsManager.REASON_SUB_DEFAULT_APP_RESTORED;
27 import static android.app.usage.UsageStatsManager.REASON_SUB_DEFAULT_APP_UPDATE;
28 import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY;
29 import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_USER_FLAG_INTERACTION;
30 import static android.app.usage.UsageStatsManager.REASON_SUB_MASK;
31 import static android.app.usage.UsageStatsManager.REASON_SUB_PREDICTED_RESTORED;
32 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_ACTIVE_TIMEOUT;
33 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE;
34 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
35 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_START;
36 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_FOREGROUND_SERVICE_START;
37 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_BACKGROUND;
38 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
39 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_NOTIFICATION_SEEN;
40 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SLICE_PINNED;
41 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SLICE_PINNED_PRIV;
42 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYNC_ADAPTER;
43 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_INTERACTION;
44 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_UPDATE;
45 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED;
46 import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_USER_INTERACTION;
47 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_ACTIVE;
48 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_EXEMPTED;
49 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_FREQUENT;
50 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_NEVER;
51 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_RARE;
52 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_RESTRICTED;
53 import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_WORKING_SET;
54 import static android.app.usage.UsageStatsManager.standbyBucketToString;
55 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
56
57 import static com.android.server.SystemService.PHASE_BOOT_COMPLETED;
58 import static com.android.server.SystemService.PHASE_SYSTEM_SERVICES_READY;
59 import static com.android.server.usage.AppIdleHistory.STANDBY_BUCKET_UNKNOWN;
60
61 import android.annotation.CurrentTimeMillisLong;
62 import android.annotation.NonNull;
63 import android.annotation.Nullable;
64 import android.annotation.UserIdInt;
65 import android.app.ActivityManager;
66 import android.app.usage.AppStandbyInfo;
67 import android.app.usage.UsageEvents;
68 import android.app.usage.UsageStatsManager.ForcedReasons;
69 import android.app.usage.UsageStatsManager.StandbyBuckets;
70 import android.app.usage.UsageStatsManagerInternal;
71 import android.appwidget.AppWidgetManager;
72 import android.content.BroadcastReceiver;
73 import android.content.ContentResolver;
74 import android.content.Context;
75 import android.content.Intent;
76 import android.content.IntentFilter;
77 import android.content.pm.ApplicationInfo;
78 import android.content.pm.CrossProfileAppsInternal;
79 import android.content.pm.PackageInfo;
80 import android.content.pm.PackageManager;
81 import android.content.pm.PackageManagerInternal;
82 import android.content.pm.ResolveInfo;
83 import android.database.ContentObserver;
84 import android.hardware.display.DisplayManager;
85 import android.net.NetworkScoreManager;
86 import android.os.BatteryManager;
87 import android.os.BatteryStats;
88 import android.os.Build;
89 import android.os.Environment;
90 import android.os.Handler;
91 import android.os.IDeviceIdleController;
92 import android.os.Looper;
93 import android.os.Message;
94 import android.os.PowerManager;
95 import android.os.Process;
96 import android.os.RemoteException;
97 import android.os.ServiceManager;
98 import android.os.SystemClock;
99 import android.os.Trace;
100 import android.os.UserHandle;
101 import android.provider.DeviceConfig;
102 import android.provider.Settings.Global;
103 import android.telephony.TelephonyManager;
104 import android.text.TextUtils;
105 import android.util.ArrayMap;
106 import android.util.ArraySet;
107 import android.util.IndentingPrintWriter;
108 import android.util.Slog;
109 import android.util.SparseArray;
110 import android.util.SparseBooleanArray;
111 import android.util.SparseLongArray;
112 import android.util.SparseSetArray;
113 import android.util.TimeUtils;
114 import android.view.Display;
115 import android.widget.Toast;
116
117 import com.android.internal.R;
118 import com.android.internal.annotations.GuardedBy;
119 import com.android.internal.annotations.VisibleForTesting;
120 import com.android.internal.app.IBatteryStats;
121 import com.android.internal.util.ArrayUtils;
122 import com.android.internal.util.ConcurrentUtils;
123 import com.android.server.AlarmManagerInternal;
124 import com.android.server.JobSchedulerBackgroundThread;
125 import com.android.server.LocalServices;
126 import com.android.server.pm.parsing.pkg.AndroidPackage;
127 import com.android.server.usage.AppIdleHistory.AppUsageHistory;
128
129 import libcore.util.EmptyArray;
130
131 import java.io.File;
132 import java.io.PrintWriter;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Collections;
136 import java.util.List;
137 import java.util.Map;
138 import java.util.Set;
139 import java.util.concurrent.CountDownLatch;
140
141 /**
142 * Manages the standby state of an app, listening to various events.
143 *
144 * Unit test:
145 * atest com.android.server.usage.AppStandbyControllerTests
146 */
147 public class AppStandbyController
148 implements AppStandbyInternal, UsageStatsManagerInternal.UsageEventListener {
149
150 private static final String TAG = "AppStandbyController";
151 // Do not submit with true.
152 static final boolean DEBUG = false;
153
154 static final boolean COMPRESS_TIME = false;
155 private static final long ONE_MINUTE = 60 * 1000;
156 private static final long ONE_HOUR = ONE_MINUTE * 60;
157 private static final long ONE_DAY = ONE_HOUR * 24;
158
159 /**
160 * The default minimum amount of time the screen must have been on before an app can time out
161 * from its current bucket to the next bucket.
162 */
163 @VisibleForTesting
164 static final long[] DEFAULT_SCREEN_TIME_THRESHOLDS = {
165 0,
166 0,
167 COMPRESS_TIME ? 2 * ONE_MINUTE : 1 * ONE_HOUR,
168 COMPRESS_TIME ? 4 * ONE_MINUTE : 2 * ONE_HOUR,
169 COMPRESS_TIME ? 8 * ONE_MINUTE : 6 * ONE_HOUR
170 };
171
172 /** The minimum allowed values for each index in {@link #DEFAULT_SCREEN_TIME_THRESHOLDS}. */
173 @VisibleForTesting
174 static final long[] MINIMUM_SCREEN_TIME_THRESHOLDS = COMPRESS_TIME
175 ? new long[DEFAULT_SCREEN_TIME_THRESHOLDS.length]
176 : new long[]{
177 0,
178 0,
179 0,
180 30 * ONE_MINUTE,
181 ONE_HOUR
182 };
183
184 /**
185 * The default minimum amount of elapsed time that must have passed before an app can time out
186 * from its current bucket to the next bucket.
187 */
188 @VisibleForTesting
189 static final long[] DEFAULT_ELAPSED_TIME_THRESHOLDS = {
190 0,
191 COMPRESS_TIME ? 1 * ONE_MINUTE : 12 * ONE_HOUR,
192 COMPRESS_TIME ? 4 * ONE_MINUTE : 24 * ONE_HOUR,
193 COMPRESS_TIME ? 16 * ONE_MINUTE : 48 * ONE_HOUR,
194 COMPRESS_TIME ? 32 * ONE_MINUTE : 8 * ONE_DAY
195 };
196
197 /** The minimum allowed values for each index in {@link #DEFAULT_ELAPSED_TIME_THRESHOLDS}. */
198 @VisibleForTesting
199 static final long[] MINIMUM_ELAPSED_TIME_THRESHOLDS = COMPRESS_TIME
200 ? new long[DEFAULT_ELAPSED_TIME_THRESHOLDS.length]
201 : new long[]{
202 0,
203 ONE_HOUR,
204 ONE_HOUR,
205 2 * ONE_HOUR,
206 4 * ONE_HOUR
207 };
208
209 private static final int[] THRESHOLD_BUCKETS = {
210 STANDBY_BUCKET_ACTIVE,
211 STANDBY_BUCKET_WORKING_SET,
212 STANDBY_BUCKET_FREQUENT,
213 STANDBY_BUCKET_RARE,
214 STANDBY_BUCKET_RESTRICTED
215 };
216
217 /** Default expiration time for bucket prediction. After this, use thresholds to downgrade. */
218 private static final long DEFAULT_PREDICTION_TIMEOUT =
219 COMPRESS_TIME ? 10 * ONE_MINUTE : 12 * ONE_HOUR;
220
221 /**
222 * Indicates the maximum wait time for admin data to be available;
223 */
224 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
225
226 private static final int HEADLESS_APP_CHECK_FLAGS =
227 PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
228 | PackageManager.MATCH_DISABLED_COMPONENTS
229 | PackageManager.MATCH_SYSTEM_ONLY;
230
231 private static final int NOTIFICATION_SEEN_PROMOTED_BUCKET_FOR_PRE_T_APPS =
232 STANDBY_BUCKET_WORKING_SET;
233 private static final long NOTIFICATION_SEEN_HOLD_DURATION_FOR_PRE_T_APPS =
234 COMPRESS_TIME ? 12 * ONE_MINUTE : 12 * ONE_HOUR;
235
236 // To name the lock for stack traces
237 static class Lock {}
238
239 /** Lock to protect the app's standby state. Required for calls into AppIdleHistory */
240 private final Object mAppIdleLock = new Lock();
241
242 /** Keeps the history and state for each app. */
243 @GuardedBy("mAppIdleLock")
244 private AppIdleHistory mAppIdleHistory;
245
246 @GuardedBy("mPackageAccessListeners")
247 private final ArrayList<AppIdleStateChangeListener> mPackageAccessListeners = new ArrayList<>();
248
249 /**
250 * Lock specifically for bookkeeping around the carrier-privileged app set.
251 * Do not acquire any other locks while holding this one. Methods that
252 * require this lock to be held are named with a "CPL" suffix.
253 */
254 private final Object mCarrierPrivilegedLock = new Lock();
255
256 /** Whether we've queried the list of carrier privileged apps. */
257 @GuardedBy("mCarrierPrivilegedLock")
258 private boolean mHaveCarrierPrivilegedApps;
259
260 /** List of carrier-privileged apps that should be excluded from standby */
261 @GuardedBy("mCarrierPrivilegedLock")
262 private List<String> mCarrierPrivilegedApps;
263
264 @GuardedBy("mActiveAdminApps")
265 private final SparseArray<Set<String>> mActiveAdminApps = new SparseArray<>();
266
267 /**
268 * Set of system apps that are headless (don't have any "front door" activities, enabled or
269 * disabled). Presence in this map indicates that the app is a headless system app.
270 */
271 @GuardedBy("mHeadlessSystemApps")
272 private final ArraySet<String> mHeadlessSystemApps = new ArraySet<>();
273
274 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
275
276 /**
277 * Set of user IDs and the next time (in the elapsed realtime timebase) when we should check the
278 * apps' idle states.
279 */
280 @GuardedBy("mPendingIdleStateChecks")
281 private final SparseLongArray mPendingIdleStateChecks = new SparseLongArray();
282
283 // Cache the active network scorer queried from the network scorer service
284 private volatile String mCachedNetworkScorer = null;
285 // The last time the network scorer service was queried
286 private volatile long mCachedNetworkScorerAtMillis = 0L;
287 // How long before querying the network scorer again. During this time, subsequent queries will
288 // get the cached value
289 private static final long NETWORK_SCORER_CACHE_DURATION_MILLIS = 5000L;
290
291 // Cache the device provisioning package queried from resource config_deviceProvisioningPackage.
292 // Note that there is no synchronization on this variable which is okay since in the worst case
293 // scenario, they might be a few extra reads from resources.
294 private String mCachedDeviceProvisioningPackage = null;
295
296 // Messages for the handler
297 static final int MSG_INFORM_LISTENERS = 3;
298 static final int MSG_FORCE_IDLE_STATE = 4;
299 static final int MSG_CHECK_IDLE_STATES = 5;
300 static final int MSG_TRIGGER_LISTENER_QUOTA_BUMP = 7;
301 static final int MSG_REPORT_CONTENT_PROVIDER_USAGE = 8;
302 static final int MSG_PAROLE_STATE_CHANGED = 9;
303 static final int MSG_ONE_TIME_CHECK_IDLE_STATES = 10;
304 /** Check the state of one app: arg1 = userId, arg2 = uid, obj = (String) packageName */
305 static final int MSG_CHECK_PACKAGE_IDLE_STATE = 11;
306 static final int MSG_REPORT_SYNC_SCHEDULED = 12;
307 static final int MSG_REPORT_EXEMPTED_SYNC_START = 13;
308
309 long mCheckIdleIntervalMillis = Math.min(DEFAULT_ELAPSED_TIME_THRESHOLDS[1] / 4,
310 ConstantsObserver.DEFAULT_CHECK_IDLE_INTERVAL_MS);
311 /**
312 * The minimum amount of time the screen must have been on before an app can time out from its
313 * current bucket to the next bucket.
314 */
315 long[] mAppStandbyScreenThresholds = DEFAULT_SCREEN_TIME_THRESHOLDS;
316 /**
317 * The minimum amount of elapsed time that must have passed before an app can time out from its
318 * current bucket to the next bucket.
319 */
320 long[] mAppStandbyElapsedThresholds = DEFAULT_ELAPSED_TIME_THRESHOLDS;
321 /** Minimum time a strong usage event should keep the bucket elevated. */
322 long mStrongUsageTimeoutMillis = ConstantsObserver.DEFAULT_STRONG_USAGE_TIMEOUT;
323 /** Minimum time a notification seen event should keep the bucket elevated. */
324 long mNotificationSeenTimeoutMillis = ConstantsObserver.DEFAULT_NOTIFICATION_TIMEOUT;
325 /** Minimum time a slice pinned event should keep the bucket elevated. */
326 long mSlicePinnedTimeoutMillis = ConstantsObserver.DEFAULT_SLICE_PINNED_TIMEOUT;
327 /** The standby bucket that an app will be promoted on a notification-seen event */
328 int mNotificationSeenPromotedBucket =
329 ConstantsObserver.DEFAULT_NOTIFICATION_SEEN_PROMOTED_BUCKET;
330 /**
331 * If {@code true}, tell each {@link AppIdleStateChangeListener} to give quota bump for each
332 * notification seen event.
333 */
334 private boolean mTriggerQuotaBumpOnNotificationSeen =
335 ConstantsObserver.DEFAULT_TRIGGER_QUOTA_BUMP_ON_NOTIFICATION_SEEN;
336 /**
337 * If {@code true}, we will retain the pre-T impact of notification signal on apps targeting
338 * pre-T sdk levels regardless of other flag changes.
339 */
340 boolean mRetainNotificationSeenImpactForPreTApps =
341 ConstantsObserver.DEFAULT_RETAIN_NOTIFICATION_SEEN_IMPACT_FOR_PRE_T_APPS;
342 /** Minimum time a system update event should keep the buckets elevated. */
343 long mSystemUpdateUsageTimeoutMillis = ConstantsObserver.DEFAULT_SYSTEM_UPDATE_TIMEOUT;
344 /** Maximum time to wait for a prediction before using simple timeouts to downgrade buckets. */
345 long mPredictionTimeoutMillis = DEFAULT_PREDICTION_TIMEOUT;
346 /** Maximum time a sync adapter associated with a CP should keep the buckets elevated. */
347 long mSyncAdapterTimeoutMillis = ConstantsObserver.DEFAULT_SYNC_ADAPTER_TIMEOUT;
348 /**
349 * Maximum time an exempted sync should keep the buckets elevated, when sync is scheduled in
350 * non-doze
351 */
352 long mExemptedSyncScheduledNonDozeTimeoutMillis =
353 ConstantsObserver.DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT;
354 /**
355 * Maximum time an exempted sync should keep the buckets elevated, when sync is scheduled in
356 * doze
357 */
358 long mExemptedSyncScheduledDozeTimeoutMillis =
359 ConstantsObserver.DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT;
360 /**
361 * Maximum time an exempted sync should keep the buckets elevated, when sync is started.
362 */
363 long mExemptedSyncStartTimeoutMillis = ConstantsObserver.DEFAULT_EXEMPTED_SYNC_START_TIMEOUT;
364 /**
365 * Maximum time an unexempted sync should keep the buckets elevated, when sync is scheduled
366 */
367 long mUnexemptedSyncScheduledTimeoutMillis =
368 ConstantsObserver.DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT;
369 /** Maximum time a system interaction should keep the buckets elevated. */
370 long mSystemInteractionTimeoutMillis = ConstantsObserver.DEFAULT_SYSTEM_INTERACTION_TIMEOUT;
371 /**
372 * Maximum time a foreground service start should keep the buckets elevated if the service
373 * start is the first usage of the app
374 */
375 long mInitialForegroundServiceStartTimeoutMillis =
376 ConstantsObserver.DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT;
377 /**
378 * User usage that would elevate an app's standby bucket will also elevate the standby bucket of
379 * cross profile connected apps. Explicit standby bucket setting via
380 * {@link #setAppStandbyBucket(String, int, int, int, int)} will not be propagated.
381 */
382 boolean mLinkCrossProfileApps =
383 ConstantsObserver.DEFAULT_CROSS_PROFILE_APPS_SHARE_STANDBY_BUCKETS;
384
385 /**
386 * Duration (in millis) for the window where events occurring will be considered as
387 * broadcast response, starting from the point when an app receives a broadcast.
388 */
389 volatile long mBroadcastResponseWindowDurationMillis =
390 ConstantsObserver.DEFAULT_BROADCAST_RESPONSE_WINDOW_DURATION_MS;
391
392 /**
393 * Process state threshold that is used for deciding whether or not an app is in the background
394 * in the context of recording broadcast response stats. Apps whose process state is higher
395 * than this threshold state will be considered to be in background.
396 */
397 volatile int mBroadcastResponseFgThresholdState =
398 ConstantsObserver.DEFAULT_BROADCAST_RESPONSE_FG_THRESHOLD_STATE;
399
400 /**
401 * Duration (in millis) for the window within which any broadcasts occurred will be
402 * treated as one broadcast session.
403 */
404 volatile long mBroadcastSessionsDurationMs =
405 ConstantsObserver.DEFAULT_BROADCAST_SESSIONS_DURATION_MS;
406
407 /**
408 * Duration (in millis) for the window within which any broadcasts occurred ((with a
409 * corresponding response event) will be treated as one broadcast session. This similar to
410 * {@link #mBroadcastSessionsDurationMs}, except that this duration will be used to group only
411 * broadcasts that have a corresponding response event into sessions.
412 */
413 volatile long mBroadcastSessionsWithResponseDurationMs =
414 ConstantsObserver.DEFAULT_BROADCAST_SESSIONS_WITH_RESPONSE_DURATION_MS;
415
416 /**
417 * Denotes whether the response event should be attributed to all broadcast sessions or not.
418 * If this is {@code true}, then the response event should be attributed to all the broadcast
419 * sessions that occurred within the broadcast response window. Otherwise, the
420 * response event should be attributed to only the earliest broadcast session within the
421 * broadcast response window.
422 */
423 volatile boolean mNoteResponseEventForAllBroadcastSessions =
424 ConstantsObserver.DEFAULT_NOTE_RESPONSE_EVENT_FOR_ALL_BROADCAST_SESSIONS;
425
426 /**
427 * List of roles whose holders are exempted from the requirement of starting
428 * a response event after receiving a broadcast.
429 *
430 * The list of roles will be separated by '|' in the string.
431 */
432 volatile String mBroadcastResponseExemptedRoles =
433 ConstantsObserver.DEFAULT_BROADCAST_RESPONSE_EXEMPTED_ROLES;
434 volatile List<String> mBroadcastResponseExemptedRolesList = Collections.EMPTY_LIST;
435
436 /**
437 * List of permissions whose holders are exempted from the requirement of starting
438 * a response event after receiving a broadcast.
439 *
440 * The list of permissions will be separated by '|' in the string.
441 */
442 volatile String mBroadcastResponseExemptedPermissions =
443 ConstantsObserver.DEFAULT_BROADCAST_RESPONSE_EXEMPTED_PERMISSIONS;
444 volatile List<String> mBroadcastResponseExemptedPermissionsList = Collections.EMPTY_LIST;
445
446 /**
447 * Map of last known values of keys in {@link DeviceConfig#NAMESPACE_APP_STANDBY}.
448 *
449 * Note: We are intentionally not guarding this by any lock since this is only updated on
450 * a handler thread and when querying, if we do end up seeing slightly older values, it is fine
451 * since the values are only used in tests and doesn't need to be queried in any other cases.
452 */
453 private final Map<String, String> mAppStandbyProperties = new ArrayMap<>();
454
455 /**
456 * Set of apps that were restored via backup & restore, per user, that need their
457 * standby buckets to be adjusted when installed.
458 */
459 private final SparseSetArray<String> mAppsToRestoreToRare = new SparseSetArray<>();
460
461 /**
462 * List of app-ids of system packages, populated on boot, when system services are ready.
463 */
464 private final ArrayList<Integer> mSystemPackagesAppIds = new ArrayList<>();
465
466 /**
467 * PackageManager flags to query for all system packages, including those that are disabled
468 * and hidden.
469 */
470 private static final int SYSTEM_PACKAGE_FLAGS = PackageManager.MATCH_UNINSTALLED_PACKAGES
471 | PackageManager.MATCH_SYSTEM_ONLY
472 | PackageManager.MATCH_ANY_USER
473 | PackageManager.MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS
474 | PackageManager.MATCH_DIRECT_BOOT_AWARE
475 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
476
477 /**
478 * Whether we should allow apps into the
479 * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RESTRICTED} bucket or not.
480 * If false, any attempts to put an app into the bucket will put the app into the
481 * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RARE} bucket instead.
482 */
483 private boolean mAllowRestrictedBucket;
484
485 private volatile boolean mAppIdleEnabled;
486 private volatile boolean mIsCharging;
487 private boolean mSystemServicesReady = false;
488 // There was a system update, defaults need to be initialized after services are ready
489 private boolean mPendingInitializeDefaults;
490
491 private volatile boolean mPendingOneTimeCheckIdleStates;
492
493 private final AppStandbyHandler mHandler;
494 private final Context mContext;
495
496 private AppWidgetManager mAppWidgetManager;
497 private PackageManager mPackageManager;
498 Injector mInjector;
499
500 private static class Pool<T> {
501 private final T[] mArray;
502 private int mSize = 0;
503
504 Pool(T[] array) {
505 mArray = array;
506 }
507
508 @Nullable
509 synchronized T obtain() {
510 return mSize > 0 ? mArray[--mSize] : null;
511 }
512
513 synchronized void recycle(T instance) {
514 if (mSize < mArray.length) {
515 mArray[mSize++] = instance;
516 }
517 }
518 }
519
520 private static class StandbyUpdateRecord {
521 private static final Pool<StandbyUpdateRecord> sPool =
522 new Pool<>(new StandbyUpdateRecord[10]);
523
524 // Identity of the app whose standby state has changed
525 String packageName;
526 int userId;
527
528 // What the standby bucket the app is now in
529 int bucket;
530
531 // Whether the bucket change is because the user has started interacting with the app
532 boolean isUserInteraction;
533
534 // Reason for bucket change
535 int reason;
536
537 public static StandbyUpdateRecord obtain(String pkgName, int userId,
538 int bucket, int reason, boolean isInteraction) {
539 StandbyUpdateRecord r = sPool.obtain();
540 if (r == null) {
541 r = new StandbyUpdateRecord();
542 }
543 r.packageName = pkgName;
544 r.userId = userId;
545 r.bucket = bucket;
546 r.reason = reason;
547 r.isUserInteraction = isInteraction;
548 return r;
549
550 }
551
552 public void recycle() {
553 sPool.recycle(this);
554 }
555 }
556
557 private static class ContentProviderUsageRecord {
558 private static final Pool<ContentProviderUsageRecord> sPool =
559 new Pool<>(new ContentProviderUsageRecord[10]);
560
561 public String name;
562 public String packageName;
563 public int userId;
564
565 public static ContentProviderUsageRecord obtain(String name, String packageName,
566 int userId) {
567 ContentProviderUsageRecord r = sPool.obtain();
568 if (r == null) {
569 r = new ContentProviderUsageRecord();
570 }
571 r.name = name;
572 r.packageName = packageName;
573 r.userId = userId;
574 return r;
575 }
576
577 public void recycle() {
578 sPool.recycle(this);
579 }
580 }
581
582 public AppStandbyController(Context context) {
583 this(new Injector(context, JobSchedulerBackgroundThread.get().getLooper()));
584 }
585
586 AppStandbyController(Injector injector) {
587 mInjector = injector;
588 mContext = mInjector.getContext();
589 mHandler = new AppStandbyHandler(mInjector.getLooper());
590 mPackageManager = mContext.getPackageManager();
591
592 DeviceStateReceiver deviceStateReceiver = new DeviceStateReceiver();
593 IntentFilter deviceStates = new IntentFilter(BatteryManager.ACTION_CHARGING);
594 deviceStates.addAction(BatteryManager.ACTION_DISCHARGING);
595 deviceStates.addAction(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
596 mContext.registerReceiver(deviceStateReceiver, deviceStates);
597
598 synchronized (mAppIdleLock) {
599 mAppIdleHistory = new AppIdleHistory(mInjector.getDataSystemDirectory(),
600 mInjector.elapsedRealtime());
601 }
602
603 IntentFilter packageFilter = new IntentFilter();
604 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
605 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
606 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
607 packageFilter.addDataScheme("package");
608
609 mContext.registerReceiverAsUser(new PackageReceiver(), UserHandle.ALL, packageFilter,
610 null, mHandler);
611 }
612
613 @VisibleForTesting
614 void setAppIdleEnabled(boolean enabled) {
615 // Don't call out to USM with the lock held. Also, register the listener before we
616 // change our internal state so no events fall through the cracks.
617 final UsageStatsManagerInternal usmi =
618 LocalServices.getService(UsageStatsManagerInternal.class);
619 if (enabled) {
620 usmi.registerListener(this);
621 } else {
622 usmi.unregisterListener(this);
623 }
624
625 synchronized (mAppIdleLock) {
626 if (mAppIdleEnabled != enabled) {
627 final boolean oldParoleState = isInParole();
628 mAppIdleEnabled = enabled;
629
630 if (isInParole() != oldParoleState) {
631 postParoleStateChanged();
632 }
633 }
634 }
635 }
636
637 @Override
638 public boolean isAppIdleEnabled() {
639 return mAppIdleEnabled;
640 }
641
642 @Override
643 public void onBootPhase(int phase) {
644 mInjector.onBootPhase(phase);
645 if (phase == PHASE_SYSTEM_SERVICES_READY) {
646 Slog.d(TAG, "Setting app idle enabled state");
647
648 if (mAppIdleEnabled) {
649 LocalServices.getService(UsageStatsManagerInternal.class).registerListener(this);
650 }
651
652 // Observe changes to the threshold
653 ConstantsObserver settingsObserver = new ConstantsObserver(mHandler);
654 settingsObserver.start();
655
656 mAppWidgetManager = mContext.getSystemService(AppWidgetManager.class);
657
658 mInjector.registerDisplayListener(mDisplayListener, mHandler);
659 synchronized (mAppIdleLock) {
660 mAppIdleHistory.updateDisplay(isDisplayOn(), mInjector.elapsedRealtime());
661 }
662
663 mSystemServicesReady = true;
664
665 boolean userFileExists;
666 synchronized (mAppIdleLock) {
667 userFileExists = mAppIdleHistory.userFileExists(UserHandle.USER_SYSTEM);
668 }
669
670 if (mPendingInitializeDefaults || !userFileExists) {
671 initializeDefaultsForSystemApps(UserHandle.USER_SYSTEM);
672 }
673
674 if (mPendingOneTimeCheckIdleStates) {
675 postOneTimeCheckIdleStates();
676 }
677
678 // Populate list of system packages and their app-ids.
679 final List<ApplicationInfo> systemApps = mPackageManager.getInstalledApplications(
680 SYSTEM_PACKAGE_FLAGS);
681 for (int i = 0, size = systemApps.size(); i < size; i++) {
682 final ApplicationInfo appInfo = systemApps.get(i);
683 mSystemPackagesAppIds.add(UserHandle.getAppId(appInfo.uid));
684 }
685 } else if (phase == PHASE_BOOT_COMPLETED) {
686 setChargingState(mInjector.isCharging());
687
688 // Offload to handler thread after boot completed to avoid boot time impact. This means
689 // that app standby buckets may be slightly out of date and headless system apps may be
690 // put in a lower bucket until boot has completed.
691 mHandler.post(AppStandbyController.this::updatePowerWhitelistCache);
692 mHandler.post(this::loadHeadlessSystemAppCache);
693 }
694 }
695
696 private void reportContentProviderUsage(String authority, String providerPkgName, int userId) {
697 if (!mAppIdleEnabled) return;
698
699 // Get sync adapters for the authority
700 String[] packages = ContentResolver.getSyncAdapterPackagesForAuthorityAsUser(
701 authority, userId);
702 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
703 final long elapsedRealtime = mInjector.elapsedRealtime();
704 for (String packageName : packages) {
705 // Don't force the sync adapter to active if the provider is in the same APK.
706 if (packageName.equals(providerPkgName)) {
707 continue;
708 }
709
710 final int appId = UserHandle.getAppId(pmi.getPackageUid(packageName, 0, userId));
711 // Elevate the sync adapter to active if it's a system app or
712 // is a non-system app and shares its app id with a system app.
713 if (mSystemPackagesAppIds.contains(appId)) {
714 final List<UserHandle> linkedProfiles = getCrossProfileTargets(packageName,
715 userId);
716 synchronized (mAppIdleLock) {
717 reportNoninteractiveUsageCrossUserLocked(packageName, userId,
718 STANDBY_BUCKET_ACTIVE, REASON_SUB_USAGE_SYNC_ADAPTER,
719 elapsedRealtime, mSyncAdapterTimeoutMillis, linkedProfiles);
720 }
721 }
722 }
723 }
724
725 private void reportExemptedSyncScheduled(String packageName, int userId) {
726 if (!mAppIdleEnabled) return;
727
728 final int bucketToPromote;
729 final int usageReason;
730 final long durationMillis;
731
732 if (!mInjector.isDeviceIdleMode()) {
733 // Not dozing.
734 bucketToPromote = STANDBY_BUCKET_ACTIVE;
735 usageReason = REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
736 durationMillis = mExemptedSyncScheduledNonDozeTimeoutMillis;
737 } else {
738 // Dozing.
739 bucketToPromote = STANDBY_BUCKET_WORKING_SET;
740 usageReason = REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE;
741 durationMillis = mExemptedSyncScheduledDozeTimeoutMillis;
742 }
743
744 final long elapsedRealtime = mInjector.elapsedRealtime();
745 final List<UserHandle> linkedProfiles = getCrossProfileTargets(packageName, userId);
746 synchronized (mAppIdleLock) {
747 reportNoninteractiveUsageCrossUserLocked(packageName, userId, bucketToPromote,
748 usageReason, elapsedRealtime, durationMillis, linkedProfiles);
749 }
750 }
751
752 private void reportUnexemptedSyncScheduled(String packageName, int userId) {
753 if (!mAppIdleEnabled) return;
754
755 final long elapsedRealtime = mInjector.elapsedRealtime();
756 synchronized (mAppIdleLock) {
757 final int currentBucket =
758 mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
759 if (currentBucket == STANDBY_BUCKET_NEVER) {
760 final List<UserHandle> linkedProfiles = getCrossProfileTargets(packageName, userId);
761 // Bring the app out of the never bucket
762 reportNoninteractiveUsageCrossUserLocked(packageName, userId,
763 STANDBY_BUCKET_WORKING_SET, REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED,
764 elapsedRealtime, mUnexemptedSyncScheduledTimeoutMillis, linkedProfiles);
765 }
766 }
767 }
768
769 private void reportExemptedSyncStart(String packageName, int userId) {
770 if (!mAppIdleEnabled) return;
771
772 final long elapsedRealtime = mInjector.elapsedRealtime();
773 final List<UserHandle> linkedProfiles = getCrossProfileTargets(packageName, userId);
774 synchronized (mAppIdleLock) {
775 reportNoninteractiveUsageCrossUserLocked(packageName, userId, STANDBY_BUCKET_ACTIVE,
776 REASON_SUB_USAGE_EXEMPTED_SYNC_START, elapsedRealtime,
777 mExemptedSyncStartTimeoutMillis, linkedProfiles);
778 }
779 }
780
781 /**
782 * Helper method to report indirect user usage of an app and handle reporting the usage
783 * against cross profile connected apps. <br>
784 * Use {@link #reportNoninteractiveUsageLocked(String, int, int, int, long, long)} if
785 * cross profile connected apps do not need to be handled.
786 */
787 private void reportNoninteractiveUsageCrossUserLocked(String packageName, int userId,
788 int bucket, int subReason, long elapsedRealtime, long nextCheckDelay,
789 List<UserHandle> otherProfiles) {
790 reportNoninteractiveUsageLocked(packageName, userId, bucket, subReason, elapsedRealtime,
791 nextCheckDelay);
792 final int size = otherProfiles.size();
793 for (int profileIndex = 0; profileIndex < size; profileIndex++) {
794 final int otherUserId = otherProfiles.get(profileIndex).getIdentifier();
795 reportNoninteractiveUsageLocked(packageName, otherUserId, bucket, subReason,
796 elapsedRealtime, nextCheckDelay);
797 }
798 }
799
800 /**
801 * Helper method to report indirect user usage of an app. <br>
802 * Use
803 * {@link #reportNoninteractiveUsageCrossUserLocked(String, int, int, int, long, long, List)}
804 * if cross profile connected apps need to be handled.
805 */
806 private void reportNoninteractiveUsageLocked(String packageName, int userId, int bucket,
807 int subReason, long elapsedRealtime, long nextCheckDelay) {
808 final AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId, bucket,
809 subReason, 0, elapsedRealtime + nextCheckDelay);
810 mHandler.sendMessageDelayed(
811 mHandler.obtainMessage(MSG_CHECK_PACKAGE_IDLE_STATE, userId, -1, packageName),
812 nextCheckDelay);
813 maybeInformListeners(packageName, userId, elapsedRealtime, appUsage.currentBucket,
814 appUsage.bucketingReason, false);
815 }
816
817 /** Trigger a quota bump in the listeners. */
818 private void triggerListenerQuotaBump(String packageName, int userId) {
819 if (!mAppIdleEnabled) return;
820
821 synchronized (mPackageAccessListeners) {
822 for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
823 listener.triggerTemporaryQuotaBump(packageName, userId);
824 }
825 }
826 }
827
828 @VisibleForTesting
829 void setChargingState(boolean isCharging) {
830 if (mIsCharging != isCharging) {
831 if (DEBUG) Slog.d(TAG, "Setting mIsCharging to " + isCharging);
832 mIsCharging = isCharging;
833 postParoleStateChanged();
834 }
835 }
836
837 @Override
838 public boolean isInParole() {
839 return !mAppIdleEnabled || mIsCharging;
840 }
841
842 private void postParoleStateChanged() {
843 if (DEBUG) Slog.d(TAG, "Posting MSG_PAROLE_STATE_CHANGED");
844 mHandler.removeMessages(MSG_PAROLE_STATE_CHANGED);
845 mHandler.sendEmptyMessage(MSG_PAROLE_STATE_CHANGED);
846 }
847
848 @Override
849 public void postCheckIdleStates(int userId) {
850 if (userId == UserHandle.USER_ALL) {
851 postOneTimeCheckIdleStates();
852 } else {
853 synchronized (mPendingIdleStateChecks) {
854 mPendingIdleStateChecks.put(userId, mInjector.elapsedRealtime());
855 }
856 mHandler.obtainMessage(MSG_CHECK_IDLE_STATES).sendToTarget();
857 }
858 }
859
860 @Override
861 public void postOneTimeCheckIdleStates() {
862 if (mInjector.getBootPhase() < PHASE_SYSTEM_SERVICES_READY) {
863 // Not booted yet; wait for it!
864 mPendingOneTimeCheckIdleStates = true;
865 } else {
866 mHandler.sendEmptyMessage(MSG_ONE_TIME_CHECK_IDLE_STATES);
867 mPendingOneTimeCheckIdleStates = false;
868 }
869 }
870
871 @VisibleForTesting
872 boolean checkIdleStates(int checkUserId) {
873 if (!mAppIdleEnabled) {
874 return false;
875 }
876
877 final int[] runningUserIds;
878 try {
879 runningUserIds = mInjector.getRunningUserIds();
880 if (checkUserId != UserHandle.USER_ALL
881 && !ArrayUtils.contains(runningUserIds, checkUserId)) {
882 return false;
883 }
884 } catch (RemoteException re) {
885 throw re.rethrowFromSystemServer();
886 }
887
888 final long elapsedRealtime = mInjector.elapsedRealtime();
889 for (int i = 0; i < runningUserIds.length; i++) {
890 final int userId = runningUserIds[i];
891 if (checkUserId != UserHandle.USER_ALL && checkUserId != userId) {
892 continue;
893 }
894 if (DEBUG) {
895 Slog.d(TAG, "Checking idle state for user " + userId);
896 }
897 List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
898 PackageManager.MATCH_DISABLED_COMPONENTS,
899 userId);
900 final int packageCount = packages.size();
901 for (int p = 0; p < packageCount; p++) {
902 final PackageInfo pi = packages.get(p);
903 final String packageName = pi.packageName;
904 checkAndUpdateStandbyState(packageName, userId, pi.applicationInfo.uid,
905 elapsedRealtime);
906 }
907 }
908 if (DEBUG) {
909 Slog.d(TAG, "checkIdleStates took "
910 + (mInjector.elapsedRealtime() - elapsedRealtime));
911 }
912 return true;
913 }
914
915 /** Check if we need to update the standby state of a specific app. */
916 private void checkAndUpdateStandbyState(String packageName, @UserIdInt int userId,
917 int uid, long elapsedRealtime) {
918 if (uid <= 0) {
919 try {
920 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
921 } catch (PackageManager.NameNotFoundException e) {
922 // Not a valid package for this user, nothing to do
923 // TODO: Remove any history of removed packages
924 return;
925 }
926 }
927 final int minBucket = getAppMinBucket(packageName,
928 UserHandle.getAppId(uid),
929 userId);
930 if (DEBUG) {
931 Slog.d(TAG, " Checking idle state for " + packageName
932 + " minBucket=" + standbyBucketToString(minBucket));
933 }
934 if (minBucket <= STANDBY_BUCKET_ACTIVE) {
935 // No extra processing needed for ACTIVE or higher since apps can't drop into lower
936 // buckets.
937 synchronized (mAppIdleLock) {
938 mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime,
939 minBucket, REASON_MAIN_DEFAULT);
940 }
941 maybeInformListeners(packageName, userId, elapsedRealtime,
942 minBucket, REASON_MAIN_DEFAULT, false);
943 } else {
944 synchronized (mAppIdleLock) {
945 final AppIdleHistory.AppUsageHistory app =
946 mAppIdleHistory.getAppUsageHistory(packageName,
947 userId, elapsedRealtime);
948 int reason = app.bucketingReason;
949 final int oldMainReason = reason & REASON_MAIN_MASK;
950
951 // If the bucket was forced by the user/developer, leave it alone.
952 // A usage event will be the only way to bring it out of this forced state
953 if (oldMainReason == REASON_MAIN_FORCED_BY_USER) {
954 return;
955 }
956 final int oldBucket = app.currentBucket;
957 if (oldBucket == STANDBY_BUCKET_NEVER) {
958 // None of this should bring an app out of the NEVER bucket.
959 return;
960 }
961 int newBucket = Math.max(oldBucket, STANDBY_BUCKET_ACTIVE); // Undo EXEMPTED
962 boolean predictionLate = predictionTimedOut(app, elapsedRealtime);
963 // Compute age-based bucket
964 if (oldMainReason == REASON_MAIN_DEFAULT
965 || oldMainReason == REASON_MAIN_USAGE
966 || oldMainReason == REASON_MAIN_TIMEOUT
967 || predictionLate) {
968
969 if (!predictionLate && app.lastPredictedBucket >= STANDBY_BUCKET_ACTIVE
970 && app.lastPredictedBucket <= STANDBY_BUCKET_RARE) {
971 newBucket = app.lastPredictedBucket;
972 reason = REASON_MAIN_PREDICTED | REASON_SUB_PREDICTED_RESTORED;
973 if (DEBUG) {
974 Slog.d(TAG, "Restored predicted newBucket = "
975 + standbyBucketToString(newBucket));
976 }
977 } else {
978 // Don't update the standby state for apps that were restored
979 if (!(oldMainReason == REASON_MAIN_DEFAULT
980 && (app.bucketingReason & REASON_SUB_MASK)
981 == REASON_SUB_DEFAULT_APP_RESTORED)) {
982 newBucket = getBucketForLocked(packageName, userId, elapsedRealtime);
983 if (DEBUG) {
984 Slog.d(TAG, "Evaluated AOSP newBucket = "
985 + standbyBucketToString(newBucket));
986 }
987 reason = REASON_MAIN_TIMEOUT;
988 }
989 }
990 }
991
992 // Check if the app is within one of the expiry times for forced bucket elevation
993 final long elapsedTimeAdjusted = mAppIdleHistory.getElapsedTime(elapsedRealtime);
994 final int bucketWithValidExpiryTime = getMinBucketWithValidExpiryTime(app,
995 newBucket, elapsedTimeAdjusted);
996 if (bucketWithValidExpiryTime != STANDBY_BUCKET_UNKNOWN) {
997 newBucket = bucketWithValidExpiryTime;
998 if (newBucket == STANDBY_BUCKET_ACTIVE || app.currentBucket == newBucket) {
999 reason = app.bucketingReason;
1000 } else {
1001 reason = REASON_MAIN_USAGE | REASON_SUB_USAGE_ACTIVE_TIMEOUT;
1002 }
1003 if (DEBUG) {
1004 Slog.d(TAG, " Keeping at " + standbyBucketToString(newBucket)
1005 + " due to min timeout");
1006 }
1007 }
1008
1009 if (app.lastUsedByUserElapsedTime >= 0
1010 && app.lastRestrictAttemptElapsedTime > app.lastUsedByUserElapsedTime
1011 && elapsedTimeAdjusted - app.lastUsedByUserElapsedTime
1012 >= mInjector.getAutoRestrictedBucketDelayMs()) {
1013 newBucket = STANDBY_BUCKET_RESTRICTED;
1014 reason = app.lastRestrictReason;
1015 if (DEBUG) {
1016 Slog.d(TAG, "Bringing down to RESTRICTED due to timeout");
1017 }
1018 }
1019 if (newBucket == STANDBY_BUCKET_RESTRICTED && !mAllowRestrictedBucket) {
1020 newBucket = STANDBY_BUCKET_RARE;
1021 // Leave the reason alone.
1022 if (DEBUG) {
1023 Slog.d(TAG, "Bringing up from RESTRICTED to RARE due to off switch");
1024 }
1025 }
1026 if (newBucket > minBucket) {
1027 newBucket = minBucket;
1028 // Leave the reason alone.
1029 if (DEBUG) {
1030 Slog.d(TAG, "Bringing up from " + standbyBucketToString(newBucket)
1031 + " to " + standbyBucketToString(minBucket)
1032 + " due to min bucketing");
1033 }
1034 }
1035 if (DEBUG) {
1036 Slog.d(TAG, " Old bucket=" + standbyBucketToString(oldBucket)
1037 + ", newBucket=" + standbyBucketToString(newBucket));
1038 }
1039 if (oldBucket != newBucket || predictionLate) {
1040 mAppIdleHistory.setAppStandbyBucket(packageName, userId,
1041 elapsedRealtime, newBucket, reason);
1042 maybeInformListeners(packageName, userId, elapsedRealtime,
1043 newBucket, reason, false);
1044 }
1045 }
1046 }
1047 }
1048
1049 /** Returns true if there hasn't been a prediction for the app in a while. */
1050 private boolean predictionTimedOut(AppIdleHistory.AppUsageHistory app, long elapsedRealtime) {
1051 return app.lastPredictedTime > 0
1052 && mAppIdleHistory.getElapsedTime(elapsedRealtime)
1053 - app.lastPredictedTime > mPredictionTimeoutMillis;
1054 }
1055
1056 /** Inform listeners if the bucket has changed since it was last reported to listeners */
1057 private void maybeInformListeners(String packageName, int userId,
1058 long elapsedRealtime, int bucket, int reason, boolean userStartedInteracting) {
1059 synchronized (mAppIdleLock) {
1060 if (mAppIdleHistory.shouldInformListeners(packageName, userId,
1061 elapsedRealtime, bucket)) {
1062 final StandbyUpdateRecord r = StandbyUpdateRecord.obtain(packageName, userId,
1063 bucket, reason, userStartedInteracting);
1064 if (DEBUG) Slog.d(TAG, "Standby bucket for " + packageName + "=" + bucket);
1065 mHandler.sendMessage(mHandler.obtainMessage(MSG_INFORM_LISTENERS, r));
1066 }
1067 }
1068 }
1069
1070 /**
1071 * Evaluates next bucket based on time since last used and the bucketing thresholds.
1072 * @param packageName the app
1073 * @param userId the user
1074 * @param elapsedRealtime as the name suggests, current elapsed time
1075 * @return the bucket for the app, based on time since last used
1076 */
1077 @GuardedBy("mAppIdleLock")
1078 @StandbyBuckets
1079 private int getBucketForLocked(String packageName, int userId,
1080 long elapsedRealtime) {
1081 int bucketIndex = mAppIdleHistory.getThresholdIndex(packageName, userId,
1082 elapsedRealtime, mAppStandbyScreenThresholds, mAppStandbyElapsedThresholds);
1083 return bucketIndex >= 0 ? THRESHOLD_BUCKETS[bucketIndex] : STANDBY_BUCKET_NEVER;
1084 }
1085
1086 private void notifyBatteryStats(String packageName, int userId, boolean idle) {
1087 try {
1088 final int uid = mPackageManager.getPackageUidAsUser(packageName,
1089 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1090 if (idle) {
1091 mInjector.noteEvent(BatteryStats.HistoryItem.EVENT_PACKAGE_INACTIVE,
1092 packageName, uid);
1093 } else {
1094 mInjector.noteEvent(BatteryStats.HistoryItem.EVENT_PACKAGE_ACTIVE,
1095 packageName, uid);
1096 }
1097 } catch (PackageManager.NameNotFoundException | RemoteException e) {
1098 }
1099 }
1100
1101 /**
1102 * Callback to inform listeners of a new event.
1103 */
1104 public void onUsageEvent(int userId, @NonNull UsageEvents.Event event) {
1105 if (!mAppIdleEnabled) return;
1106 final int eventType = event.getEventType();
1107 if ((eventType == UsageEvents.Event.ACTIVITY_RESUMED
1108 || eventType == UsageEvents.Event.ACTIVITY_PAUSED
1109 || eventType == UsageEvents.Event.SYSTEM_INTERACTION
1110 || eventType == UsageEvents.Event.USER_INTERACTION
1111 || eventType == UsageEvents.Event.NOTIFICATION_SEEN
1112 || eventType == UsageEvents.Event.SLICE_PINNED
1113 || eventType == UsageEvents.Event.SLICE_PINNED_PRIV
1114 || eventType == UsageEvents.Event.FOREGROUND_SERVICE_START)) {
1115 final String pkg = event.getPackageName();
1116 final List<UserHandle> linkedProfiles = getCrossProfileTargets(pkg, userId);
1117 synchronized (mAppIdleLock) {
1118 final long elapsedRealtime = mInjector.elapsedRealtime();
1119 reportEventLocked(pkg, eventType, elapsedRealtime, userId);
1120
1121 final int size = linkedProfiles.size();
1122 for (int profileIndex = 0; profileIndex < size; profileIndex++) {
1123 final int linkedUserId = linkedProfiles.get(profileIndex).getIdentifier();
1124 reportEventLocked(pkg, eventType, elapsedRealtime, linkedUserId);
1125 }
1126 }
1127 }
1128 }
1129
1130 @GuardedBy("mAppIdleLock")
1131 private void reportEventLocked(String pkg, int eventType, long elapsedRealtime, int userId) {
1132 // TODO: Ideally this should call isAppIdleFiltered() to avoid calling back
1133 // about apps that are on some kind of whitelist anyway.
1134 final boolean previouslyIdle = mAppIdleHistory.isIdle(
1135 pkg, userId, elapsedRealtime);
1136
1137 final AppUsageHistory appHistory = mAppIdleHistory.getAppUsageHistory(
1138 pkg, userId, elapsedRealtime);
1139 final int prevBucket = appHistory.currentBucket;
1140 final int prevBucketReason = appHistory.bucketingReason;
1141 final long nextCheckDelay;
1142 final int subReason = usageEventToSubReason(eventType);
1143 final int reason = REASON_MAIN_USAGE | subReason;
1144 if (eventType == UsageEvents.Event.NOTIFICATION_SEEN) {
1145 final int notificationSeenPromotedBucket;
1146 final long notificationSeenTimeoutMillis;
1147 if (mRetainNotificationSeenImpactForPreTApps
1148 && getTargetSdkVersion(pkg) < Build.VERSION_CODES.TIRAMISU) {
1149 notificationSeenPromotedBucket =
1150 NOTIFICATION_SEEN_PROMOTED_BUCKET_FOR_PRE_T_APPS;
1151 notificationSeenTimeoutMillis =
1152 NOTIFICATION_SEEN_HOLD_DURATION_FOR_PRE_T_APPS;
1153 } else {
1154 if (mTriggerQuotaBumpOnNotificationSeen) {
1155 mHandler.obtainMessage(MSG_TRIGGER_LISTENER_QUOTA_BUMP, userId, -1, pkg)
1156 .sendToTarget();
1157 }
1158 notificationSeenPromotedBucket = mNotificationSeenPromotedBucket;
1159 notificationSeenTimeoutMillis = mNotificationSeenTimeoutMillis;
1160 }
1161 // Notification-seen elevates to a higher bucket (depending on
1162 // {@link ConstantsObserver#KEY_NOTIFICATION_SEEN_PROMOTED_BUCKET}) but doesn't
1163 // change usage time.
1164 mAppIdleHistory.reportUsage(appHistory, pkg, userId,
1165 notificationSeenPromotedBucket, subReason,
1166 0, elapsedRealtime + notificationSeenTimeoutMillis);
1167 nextCheckDelay = notificationSeenTimeoutMillis;
1168 } else if (eventType == UsageEvents.Event.SLICE_PINNED) {
1169 // Mild usage elevates to WORKING_SET but doesn't change usage time.
1170 mAppIdleHistory.reportUsage(appHistory, pkg, userId,
1171 STANDBY_BUCKET_WORKING_SET, subReason,
1172 0, elapsedRealtime + mSlicePinnedTimeoutMillis);
1173 nextCheckDelay = mSlicePinnedTimeoutMillis;
1174 } else if (eventType == UsageEvents.Event.SYSTEM_INTERACTION) {
1175 mAppIdleHistory.reportUsage(appHistory, pkg, userId,
1176 STANDBY_BUCKET_ACTIVE, subReason,
1177 0, elapsedRealtime + mSystemInteractionTimeoutMillis);
1178 nextCheckDelay = mSystemInteractionTimeoutMillis;
1179 } else if (eventType == UsageEvents.Event.FOREGROUND_SERVICE_START) {
1180 // Only elevate bucket if this is the first usage of the app
1181 if (prevBucket != STANDBY_BUCKET_NEVER) return;
1182 mAppIdleHistory.reportUsage(appHistory, pkg, userId,
1183 STANDBY_BUCKET_ACTIVE, subReason,
1184 0, elapsedRealtime + mInitialForegroundServiceStartTimeoutMillis);
1185 nextCheckDelay = mInitialForegroundServiceStartTimeoutMillis;
1186 } else {
1187 mAppIdleHistory.reportUsage(appHistory, pkg, userId,
1188 STANDBY_BUCKET_ACTIVE, subReason,
1189 elapsedRealtime, elapsedRealtime + mStrongUsageTimeoutMillis);
1190 nextCheckDelay = mStrongUsageTimeoutMillis;
1191 }
1192 if (appHistory.currentBucket != prevBucket) {
1193 mHandler.sendMessageDelayed(
1194 mHandler.obtainMessage(MSG_CHECK_PACKAGE_IDLE_STATE, userId, -1, pkg),
1195 nextCheckDelay);
1196 final boolean userStartedInteracting =
1197 appHistory.currentBucket == STANDBY_BUCKET_ACTIVE
1198 && (prevBucketReason & REASON_MAIN_MASK) != REASON_MAIN_USAGE;
1199 maybeInformListeners(pkg, userId, elapsedRealtime,
1200 appHistory.currentBucket, reason, userStartedInteracting);
1201 }
1202
1203 if (previouslyIdle) {
1204 notifyBatteryStats(pkg, userId, false);
1205 }
1206 }
1207
1208 private int getTargetSdkVersion(String packageName) {
1209 return mInjector.getPackageManagerInternal().getPackageTargetSdkVersion(packageName);
1210 }
1211
1212 /**
1213 * Returns the lowest standby bucket that is better than {@code targetBucket} and has an
1214 * valid expiry time (i.e. the expiry time is not yet elapsed).
1215 */
1216 private int getMinBucketWithValidExpiryTime(AppUsageHistory usageHistory,
1217 int targetBucket, long elapsedTimeMs) {
1218 if (usageHistory.bucketExpiryTimesMs == null) {
1219 return STANDBY_BUCKET_UNKNOWN;
1220 }
1221 final int size = usageHistory.bucketExpiryTimesMs.size();
1222 for (int i = 0; i < size; ++i) {
1223 final int bucket = usageHistory.bucketExpiryTimesMs.keyAt(i);
1224 if (targetBucket <= bucket) {
1225 break;
1226 }
1227 final long expiryTimeMs = usageHistory.bucketExpiryTimesMs.valueAt(i);
1228 if (expiryTimeMs > elapsedTimeMs) {
1229 return bucket;
1230 }
1231 }
1232 return STANDBY_BUCKET_UNKNOWN;
1233 }
1234
1235 /**
1236 * Note: don't call this with the lock held since it makes calls to other system services.
1237 */
1238 private @NonNull List<UserHandle> getCrossProfileTargets(String pkg, int userId) {
1239 synchronized (mAppIdleLock) {
1240 if (!mLinkCrossProfileApps) return Collections.emptyList();
1241 }
1242 return mInjector.getValidCrossProfileTargets(pkg, userId);
1243 }
1244
1245 private int usageEventToSubReason(int eventType) {
1246 switch (eventType) {
1247 case UsageEvents.Event.ACTIVITY_RESUMED: return REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
1248 case UsageEvents.Event.ACTIVITY_PAUSED: return REASON_SUB_USAGE_MOVE_TO_BACKGROUND;
1249 case UsageEvents.Event.SYSTEM_INTERACTION: return REASON_SUB_USAGE_SYSTEM_INTERACTION;
1250 case UsageEvents.Event.USER_INTERACTION: return REASON_SUB_USAGE_USER_INTERACTION;
1251 case UsageEvents.Event.NOTIFICATION_SEEN: return REASON_SUB_USAGE_NOTIFICATION_SEEN;
1252 case UsageEvents.Event.SLICE_PINNED: return REASON_SUB_USAGE_SLICE_PINNED;
1253 case UsageEvents.Event.SLICE_PINNED_PRIV: return REASON_SUB_USAGE_SLICE_PINNED_PRIV;
1254 case UsageEvents.Event.FOREGROUND_SERVICE_START:
1255 return REASON_SUB_USAGE_FOREGROUND_SERVICE_START;
1256 default: return 0;
1257 }
1258 }
1259
1260 @VisibleForTesting
1261 void forceIdleState(String packageName, int userId, boolean idle) {
1262 if (!mAppIdleEnabled) return;
1263
1264 final int appId = getAppId(packageName);
1265 if (appId < 0) return;
1266 final int minBucket = getAppMinBucket(packageName, appId, userId);
1267 if (idle && minBucket < AppIdleHistory.IDLE_BUCKET_CUTOFF) {
1268 Slog.e(TAG, "Tried to force an app to be idle when its min bucket is "
1269 + standbyBucketToString(minBucket));
1270 return;
1271 }
1272 final long elapsedRealtime = mInjector.elapsedRealtime();
1273
1274 final boolean previouslyIdle = isAppIdleFiltered(packageName, appId,
1275 userId, elapsedRealtime);
1276 final int standbyBucket;
1277 synchronized (mAppIdleLock) {
1278 standbyBucket = mAppIdleHistory.setIdle(packageName, userId, idle, elapsedRealtime);
1279 }
1280 final boolean stillIdle = isAppIdleFiltered(packageName, appId,
1281 userId, elapsedRealtime);
1282 // Inform listeners if necessary
1283 maybeInformListeners(packageName, userId, elapsedRealtime, standbyBucket,
1284 REASON_MAIN_FORCED_BY_USER, false);
1285 if (previouslyIdle != stillIdle) {
1286 notifyBatteryStats(packageName, userId, stillIdle);
1287 }
1288 }
1289
1290 @Override
1291 public void setLastJobRunTime(String packageName, int userId, long elapsedRealtime) {
1292 synchronized (mAppIdleLock) {
1293 mAppIdleHistory.setLastJobRunTime(packageName, userId, elapsedRealtime);
1294 }
1295 }
1296
1297 @Override
1298 public long getTimeSinceLastJobRun(String packageName, int userId) {
1299 final long elapsedRealtime = mInjector.elapsedRealtime();
1300 synchronized (mAppIdleLock) {
1301 return mAppIdleHistory.getTimeSinceLastJobRun(packageName, userId, elapsedRealtime);
1302 }
1303 }
1304
1305 @Override
1306 public void setEstimatedLaunchTime(String packageName, int userId,
1307 @CurrentTimeMillisLong long launchTime) {
1308 final long nowElapsed = mInjector.elapsedRealtime();
1309 synchronized (mAppIdleLock) {
1310 mAppIdleHistory.setEstimatedLaunchTime(packageName, userId, nowElapsed, launchTime);
1311 }
1312 }
1313
1314 @Override
1315 @CurrentTimeMillisLong
1316 public long getEstimatedLaunchTime(String packageName, int userId) {
1317 final long elapsedRealtime = mInjector.elapsedRealtime();
1318 synchronized (mAppIdleLock) {
1319 return mAppIdleHistory.getEstimatedLaunchTime(packageName, userId, elapsedRealtime);
1320 }
1321 }
1322
1323 @Override
1324 public long getTimeSinceLastUsedByUser(String packageName, int userId) {
1325 final long elapsedRealtime = mInjector.elapsedRealtime();
1326 synchronized (mAppIdleLock) {
1327 return mAppIdleHistory.getTimeSinceLastUsedByUser(packageName, userId, elapsedRealtime);
1328 }
1329 }
1330
1331 @Override
1332 public void onUserRemoved(int userId) {
1333 synchronized (mAppIdleLock) {
1334 mAppIdleHistory.onUserRemoved(userId);
1335 synchronized (mActiveAdminApps) {
1336 mActiveAdminApps.remove(userId);
1337 }
1338 }
1339 }
1340
1341 private boolean isAppIdleUnfiltered(String packageName, int userId, long elapsedRealtime) {
1342 synchronized (mAppIdleLock) {
1343 return mAppIdleHistory.isIdle(packageName, userId, elapsedRealtime);
1344 }
1345 }
1346
1347 @Override
1348 public void addListener(AppIdleStateChangeListener listener) {
1349 synchronized (mPackageAccessListeners) {
1350 if (!mPackageAccessListeners.contains(listener)) {
1351 mPackageAccessListeners.add(listener);
1352 }
1353 }
1354 }
1355
1356 @Override
1357 public void removeListener(AppIdleStateChangeListener listener) {
1358 synchronized (mPackageAccessListeners) {
1359 mPackageAccessListeners.remove(listener);
1360 }
1361 }
1362
1363 @Override
1364 public int getAppId(String packageName) {
1365 try {
1366 ApplicationInfo ai = mPackageManager.getApplicationInfo(packageName,
1367 PackageManager.MATCH_ANY_USER
1368 | PackageManager.MATCH_DISABLED_COMPONENTS);
1369 return ai.uid;
1370 } catch (PackageManager.NameNotFoundException re) {
1371 return -1;
1372 }
1373 }
1374
1375 @Override
1376 public boolean isAppIdleFiltered(String packageName, int userId, long elapsedRealtime,
1377 boolean shouldObfuscateInstantApps) {
1378 if (shouldObfuscateInstantApps &&
1379 mInjector.isPackageEphemeral(userId, packageName)) {
1380 return false;
1381 }
1382 return isAppIdleFiltered(packageName, getAppId(packageName), userId, elapsedRealtime);
1383 }
1384
1385 @StandbyBuckets
1386 private int getAppMinBucket(String packageName, int userId) {
1387 try {
1388 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
1389 return getAppMinBucket(packageName, UserHandle.getAppId(uid), userId);
1390 } catch (PackageManager.NameNotFoundException e) {
1391 // Not a valid package for this user, nothing to do
1392 return STANDBY_BUCKET_NEVER;
1393 }
1394 }
1395
1396 /**
1397 * Return the lowest bucket this app should ever enter.
1398 */
1399 @StandbyBuckets
1400 private int getAppMinBucket(String packageName, int appId, int userId) {
1401 if (packageName == null) return STANDBY_BUCKET_NEVER;
1402 // If not enabled at all, of course nobody is ever idle.
1403 if (!mAppIdleEnabled) {
1404 return STANDBY_BUCKET_EXEMPTED;
1405 }
1406 if (appId < Process.FIRST_APPLICATION_UID) {
1407 // System uids never go idle.
1408 return STANDBY_BUCKET_EXEMPTED;
1409 }
1410 if (packageName.equals("android")) {
1411 // Nor does the framework (which should be redundant with the above, but for MR1 we will
1412 // retain this for safety).
1413 return STANDBY_BUCKET_EXEMPTED;
1414 }
1415 if (mSystemServicesReady) {
1416 // We allow all whitelisted apps, including those that don't want to be whitelisted
1417 // for idle mode, because app idle (aka app standby) is really not as big an issue
1418 // for controlling who participates vs. doze mode.
1419 if (mInjector.isNonIdleWhitelisted(packageName)) {
1420 return STANDBY_BUCKET_EXEMPTED;
1421 }
1422
1423 if (isActiveDeviceAdmin(packageName, userId)) {
1424 return STANDBY_BUCKET_EXEMPTED;
1425 }
1426
1427 if (isActiveNetworkScorer(packageName)) {
1428 return STANDBY_BUCKET_EXEMPTED;
1429 }
1430
1431 if (mAppWidgetManager != null
1432 && mInjector.isBoundWidgetPackage(mAppWidgetManager, packageName, userId)) {
1433 return STANDBY_BUCKET_ACTIVE;
1434 }
1435
1436 if (isDeviceProvisioningPackage(packageName)) {
1437 return STANDBY_BUCKET_EXEMPTED;
1438 }
1439
1440 if (mInjector.isWellbeingPackage(packageName)) {
1441 return STANDBY_BUCKET_WORKING_SET;
1442 }
1443
1444 if (mInjector.hasExactAlarmPermission(packageName, UserHandle.getUid(userId, appId))) {
1445 return STANDBY_BUCKET_WORKING_SET;
1446 }
1447 }
1448
1449 // Check this last, as it can be the most expensive check
1450 if (isCarrierApp(packageName)) {
1451 return STANDBY_BUCKET_EXEMPTED;
1452 }
1453
1454 if (isHeadlessSystemApp(packageName)) {
1455 return STANDBY_BUCKET_ACTIVE;
1456 }
1457
1458 if (mPackageManager.checkPermission(android.Manifest.permission.ACCESS_BACKGROUND_LOCATION,
1459 packageName) == PERMISSION_GRANTED) {
1460 return STANDBY_BUCKET_FREQUENT;
1461 }
1462
1463 return STANDBY_BUCKET_NEVER;
1464 }
1465
1466 private boolean isHeadlessSystemApp(String packageName) {
1467 synchronized (mHeadlessSystemApps) {
1468 return mHeadlessSystemApps.contains(packageName);
1469 }
1470 }
1471
1472 @Override
1473 public boolean isAppIdleFiltered(String packageName, int appId, int userId,
1474 long elapsedRealtime) {
1475 if (!mAppIdleEnabled || mIsCharging) {
1476 return false;
1477 }
1478
1479 return isAppIdleUnfiltered(packageName, userId, elapsedRealtime)
1480 && getAppMinBucket(packageName, appId, userId) >= AppIdleHistory.IDLE_BUCKET_CUTOFF;
1481 }
1482
1483 static boolean isUserUsage(int reason) {
1484 if ((reason & REASON_MAIN_MASK) == REASON_MAIN_USAGE) {
1485 final int subReason = reason & REASON_SUB_MASK;
1486 return subReason == REASON_SUB_USAGE_USER_INTERACTION
1487 || subReason == REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
1488 }
1489 return false;
1490 }
1491
1492 @Override
1493 public int[] getIdleUidsForUser(int userId) {
1494 if (!mAppIdleEnabled) {
1495 return EmptyArray.INT;
1496 }
1497
1498 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getIdleUidsForUser");
1499
1500 final long elapsedRealtime = mInjector.elapsedRealtime();
1501
1502 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
1503 final List<ApplicationInfo> apps = pmi.getInstalledApplications(0, userId, Process.myUid());
1504 if (apps == null) {
1505 return EmptyArray.INT;
1506 }
1507
1508 // State of each uid: Key is the uid, value is whether all the apps in that uid are idle.
1509 final SparseBooleanArray uidIdleStates = new SparseBooleanArray();
1510 int notIdleCount = 0;
1511 for (int i = apps.size() - 1; i >= 0; i--) {
1512 final ApplicationInfo ai = apps.get(i);
1513 final int index = uidIdleStates.indexOfKey(ai.uid);
1514
1515 final boolean currentIdle = (index < 0) ? true : uidIdleStates.valueAt(index);
1516
1517 final boolean newIdle = currentIdle && isAppIdleFiltered(ai.packageName,
1518 UserHandle.getAppId(ai.uid), userId, elapsedRealtime);
1519
1520 if (currentIdle && !newIdle) {
1521 // This transition from true to false can happen at most once per uid in this loop.
1522 notIdleCount++;
1523 }
1524 if (index < 0) {
1525 uidIdleStates.put(ai.uid, newIdle);
1526 } else {
1527 uidIdleStates.setValueAt(index, newIdle);
1528 }
1529 }
1530
1531 int numIdleUids = uidIdleStates.size() - notIdleCount;
1532 final int[] idleUids = new int[numIdleUids];
1533 for (int i = uidIdleStates.size() - 1; i >= 0; i--) {
1534 if (uidIdleStates.valueAt(i)) {
1535 idleUids[--numIdleUids] = uidIdleStates.keyAt(i);
1536 }
1537 }
1538 if (DEBUG) {
1539 Slog.d(TAG, "getIdleUids took " + (mInjector.elapsedRealtime() - elapsedRealtime));
1540 }
1541 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1542
1543 return idleUids;
1544 }
1545
1546 @Override
1547 public void setAppIdleAsync(String packageName, boolean idle, int userId) {
1548 if (packageName == null || !mAppIdleEnabled) return;
1549
1550 mHandler.obtainMessage(MSG_FORCE_IDLE_STATE, userId, idle ? 1 : 0, packageName)
1551 .sendToTarget();
1552 }
1553
1554 @Override
1555 @StandbyBuckets public int getAppStandbyBucket(String packageName, int userId,
1556 long elapsedRealtime, boolean shouldObfuscateInstantApps) {
1557 if (!mAppIdleEnabled || (shouldObfuscateInstantApps
1558 && mInjector.isPackageEphemeral(userId, packageName))) {
1559 return STANDBY_BUCKET_ACTIVE;
1560 }
1561
1562 synchronized (mAppIdleLock) {
1563 return mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
1564 }
1565 }
1566
1567 @Override
1568 public int getAppStandbyBucketReason(String packageName, int userId, long elapsedRealtime) {
1569 synchronized (mAppIdleLock) {
1570 return mAppIdleHistory.getAppStandbyReason(packageName, userId, elapsedRealtime);
1571 }
1572 }
1573
1574 @Override
1575 public List<AppStandbyInfo> getAppStandbyBuckets(int userId) {
1576 synchronized (mAppIdleLock) {
1577 return mAppIdleHistory.getAppStandbyBuckets(userId, mAppIdleEnabled);
1578 }
1579 }
1580
1581 @Override
1582 @StandbyBuckets
1583 public int getAppMinStandbyBucket(String packageName, int appId, int userId,
1584 boolean shouldObfuscateInstantApps) {
1585 if (shouldObfuscateInstantApps && mInjector.isPackageEphemeral(userId, packageName)) {
1586 return STANDBY_BUCKET_NEVER;
1587 }
1588 synchronized (mAppIdleLock) {
1589 return getAppMinBucket(packageName, appId, userId);
1590 }
1591 }
1592
1593 @Override
1594 public void restrictApp(@NonNull String packageName, int userId,
1595 @ForcedReasons int restrictReason) {
1596 restrictApp(packageName, userId, REASON_MAIN_FORCED_BY_SYSTEM, restrictReason);
1597 }
1598
1599 @Override
1600 public void restrictApp(@NonNull String packageName, int userId, int mainReason,
1601 @ForcedReasons int restrictReason) {
1602 if (mainReason != REASON_MAIN_FORCED_BY_SYSTEM
1603 && mainReason != REASON_MAIN_FORCED_BY_USER) {
1604 Slog.e(TAG, "Tried to restrict app " + packageName + " for an unsupported reason");
1605 return;
1606 }
1607 // If the package is not installed, don't allow the bucket to be set.
1608 if (!mInjector.isPackageInstalled(packageName, 0, userId)) {
1609 Slog.e(TAG, "Tried to restrict uninstalled app: " + packageName);
1610 return;
1611 }
1612
1613 final int reason = (REASON_MAIN_MASK & mainReason) | (REASON_SUB_MASK & restrictReason);
1614 final long nowElapsed = mInjector.elapsedRealtime();
1615 final int bucket = mAllowRestrictedBucket ? STANDBY_BUCKET_RESTRICTED : STANDBY_BUCKET_RARE;
1616 setAppStandbyBucket(packageName, userId, bucket, reason, nowElapsed, false);
1617 }
1618
1619 @Override
1620 public void restoreAppsToRare(Set<String> restoredApps, int userId) {
1621 final int reason = REASON_MAIN_DEFAULT | REASON_SUB_DEFAULT_APP_RESTORED;
1622 final long nowElapsed = mInjector.elapsedRealtime();
1623 for (String packageName : restoredApps) {
1624 // If the package is not installed, don't allow the bucket to be set. Instead, add it
1625 // to a list of all packages whose buckets need to be adjusted when installed.
1626 if (!mInjector.isPackageInstalled(packageName, 0, userId)) {
1627 Slog.i(TAG, "Tried to restore bucket for uninstalled app: " + packageName);
1628 mAppsToRestoreToRare.add(userId, packageName);
1629 continue;
1630 }
1631
1632 restoreAppToRare(packageName, userId, nowElapsed, reason);
1633 }
1634 // Clear out the list of restored apps that need to have their standby buckets adjusted
1635 // if they still haven't been installed eight hours after restore.
1636 // Note: if the device reboots within these first 8 hours, this list will be lost since it's
1637 // not persisted - this is the expected behavior for now and may be updated in the future.
1638 mHandler.postDelayed(() -> mAppsToRestoreToRare.remove(userId), 8 * ONE_HOUR);
1639 }
1640
1641 /** Adjust the standby bucket of the given package for the user to RARE. */
1642 private void restoreAppToRare(String pkgName, int userId, long nowElapsed, int reason) {
1643 final int standbyBucket = getAppStandbyBucket(pkgName, userId, nowElapsed, false);
1644 // Only update the standby bucket to RARE if the app is still in the NEVER bucket.
1645 if (standbyBucket == STANDBY_BUCKET_NEVER) {
1646 setAppStandbyBucket(pkgName, userId, STANDBY_BUCKET_RARE, reason, nowElapsed, false);
1647 }
1648 }
1649
1650 @Override
1651 public void setAppStandbyBucket(@NonNull String packageName, int bucket, int userId,
1652 int callingUid, int callingPid) {
1653 setAppStandbyBuckets(
1654 Collections.singletonList(new AppStandbyInfo(packageName, bucket)),
1655 userId, callingUid, callingPid);
1656 }
1657
1658 @Override
1659 public void setAppStandbyBuckets(@NonNull List<AppStandbyInfo> appBuckets, int userId,
1660 int callingUid, int callingPid) {
1661 userId = ActivityManager.handleIncomingUser(
1662 callingPid, callingUid, userId, false, true, "setAppStandbyBucket", null);
1663 final boolean shellCaller = callingUid == Process.ROOT_UID
1664 || callingUid == Process.SHELL_UID;
1665 final int reason;
1666 // The Settings app runs in the system UID but in a separate process. Assume
1667 // things coming from other processes are due to the user.
1668 if ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) && callingPid != Process.myPid())
1669 || shellCaller) {
1670 reason = REASON_MAIN_FORCED_BY_USER;
1671 } else if (UserHandle.isCore(callingUid)) {
1672 reason = REASON_MAIN_FORCED_BY_SYSTEM;
1673 } else {
1674 reason = REASON_MAIN_PREDICTED;
1675 }
1676 final int packageFlags = PackageManager.MATCH_ANY_USER
1677 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
1678 | PackageManager.MATCH_DIRECT_BOOT_AWARE;
1679 final int numApps = appBuckets.size();
1680 final long elapsedRealtime = mInjector.elapsedRealtime();
1681 for (int i = 0; i < numApps; ++i) {
1682 final AppStandbyInfo bucketInfo = appBuckets.get(i);
1683 final String packageName = bucketInfo.mPackageName;
1684 final int bucket = bucketInfo.mStandbyBucket;
1685 if (bucket < STANDBY_BUCKET_ACTIVE || bucket > STANDBY_BUCKET_NEVER) {
1686 throw new IllegalArgumentException("Cannot set the standby bucket to " + bucket);
1687 }
1688 final int packageUid = mInjector.getPackageManagerInternal()
1689 .getPackageUid(packageName, packageFlags, userId);
1690 // Caller cannot set their own standby state
1691 if (packageUid == callingUid) {
1692 throw new IllegalArgumentException("Cannot set your own standby bucket");
1693 }
1694 if (packageUid < 0) {
1695 throw new IllegalArgumentException(
1696 "Cannot set standby bucket for non existent package (" + packageName + ")");
1697 }
1698 setAppStandbyBucket(packageName, userId, bucket, reason, elapsedRealtime, shellCaller);
1699 }
1700 }
1701
1702 @VisibleForTesting
1703 void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
1704 int reason) {
1705 setAppStandbyBucket(
1706 packageName, userId, newBucket, reason, mInjector.elapsedRealtime(), false);
1707 }
1708
1709 private void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
1710 int reason, long elapsedRealtime, boolean resetTimeout) {
1711 if (!mAppIdleEnabled) return;
1712
1713 synchronized (mAppIdleLock) {
1714 // If the package is not installed, don't allow the bucket to be set.
1715 if (!mInjector.isPackageInstalled(packageName, 0, userId)) {
1716 Slog.e(TAG, "Tried to set bucket of uninstalled app: " + packageName);
1717 return;
1718 }
1719 if (newBucket == STANDBY_BUCKET_RESTRICTED && !mAllowRestrictedBucket) {
1720 newBucket = STANDBY_BUCKET_RARE;
1721 }
1722 AppIdleHistory.AppUsageHistory app = mAppIdleHistory.getAppUsageHistory(packageName,
1723 userId, elapsedRealtime);
1724 boolean predicted = (reason & REASON_MAIN_MASK) == REASON_MAIN_PREDICTED;
1725
1726 // Don't allow changing bucket if higher than ACTIVE
1727 if (app.currentBucket < STANDBY_BUCKET_ACTIVE) return;
1728
1729 // Don't allow prediction to change from/to NEVER.
1730 if ((app.currentBucket == STANDBY_BUCKET_NEVER || newBucket == STANDBY_BUCKET_NEVER)
1731 && predicted) {
1732 return;
1733 }
1734
1735 final boolean wasForcedBySystem =
1736 (app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_SYSTEM;
1737
1738 // If the bucket was forced, don't allow prediction to override
1739 if (predicted
1740 && ((app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_USER
1741 || wasForcedBySystem)) {
1742 return;
1743 }
1744
1745 final boolean isForcedBySystem =
1746 (reason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_SYSTEM;
1747
1748 if (app.currentBucket == newBucket && wasForcedBySystem && isForcedBySystem) {
1749 if (newBucket == STANDBY_BUCKET_RESTRICTED) {
1750 mAppIdleHistory
1751 .noteRestrictionAttempt(packageName, userId, elapsedRealtime, reason);
1752 }
1753 // Keep track of all restricting reasons
1754 reason = REASON_MAIN_FORCED_BY_SYSTEM
1755 | (app.bucketingReason & REASON_SUB_MASK)
1756 | (reason & REASON_SUB_MASK);
1757 mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime,
1758 newBucket, reason, resetTimeout);
1759 return;
1760 }
1761
1762 final boolean isForcedByUser =
1763 (reason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_USER;
1764
1765 if (app.currentBucket == STANDBY_BUCKET_RESTRICTED) {
1766 if ((app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_TIMEOUT) {
1767 if (predicted && newBucket >= STANDBY_BUCKET_RARE) {
1768 // Predicting into RARE or below means we don't expect the user to use the
1769 // app anytime soon, so don't elevate it from RESTRICTED.
1770 return;
1771 }
1772 } else if (!isUserUsage(reason) && !isForcedByUser) {
1773 // If the current bucket is RESTRICTED, only user force or usage should bring
1774 // it out, unless the app was put into the bucket due to timing out.
1775 return;
1776 }
1777 }
1778
1779 if (newBucket == STANDBY_BUCKET_RESTRICTED) {
1780 mAppIdleHistory
1781 .noteRestrictionAttempt(packageName, userId, elapsedRealtime, reason);
1782
1783 if (isForcedByUser) {
1784 // Only user force can bypass the delay restriction. If the user forced the
1785 // app into the RESTRICTED bucket, then a toast confirming the action
1786 // shouldn't be surprising.
1787 // Exclude REASON_SUB_FORCED_USER_FLAG_INTERACTION since the RESTRICTED bucket
1788 // isn't directly visible in that flow.
1789 if (Build.IS_DEBUGGABLE
1790 && (reason & REASON_SUB_MASK)
1791 != REASON_SUB_FORCED_USER_FLAG_INTERACTION) {
1792 Toast.makeText(mContext,
1793 // Since AppStandbyController sits low in the lock hierarchy,
1794 // make sure not to call out with the lock held.
1795 mHandler.getLooper(),
1796 mContext.getResources().getString(
1797 R.string.as_app_forced_to_restricted_bucket, packageName),
1798 Toast.LENGTH_SHORT)
1799 .show();
1800 } else {
1801 Slog.i(TAG, packageName + " restricted by user");
1802 }
1803 } else {
1804 final long timeUntilRestrictPossibleMs = app.lastUsedByUserElapsedTime
1805 + mInjector.getAutoRestrictedBucketDelayMs() - elapsedRealtime;
1806 if (timeUntilRestrictPossibleMs > 0) {
1807 Slog.w(TAG, "Tried to restrict recently used app: " + packageName
1808 + " due to " + reason);
1809 mHandler.sendMessageDelayed(
1810 mHandler.obtainMessage(
1811 MSG_CHECK_PACKAGE_IDLE_STATE, userId, -1, packageName),
1812 timeUntilRestrictPossibleMs);
1813 return;
1814 }
1815 }
1816 }
1817
1818 // If the bucket is required to stay in a higher state for a specified duration, don't
1819 // override unless the duration has passed
1820 if (predicted) {
1821 // Check if the app is within one of the timeouts for forced bucket elevation
1822 final long elapsedTimeAdjusted = mAppIdleHistory.getElapsedTime(elapsedRealtime);
1823 // In case of not using the prediction, just keep track of it for applying after
1824 // ACTIVE or WORKING_SET timeout.
1825 mAppIdleHistory.updateLastPrediction(app, elapsedTimeAdjusted, newBucket);
1826
1827 final int bucketWithValidExpiryTime = getMinBucketWithValidExpiryTime(app,
1828 newBucket, elapsedTimeAdjusted);
1829 if (bucketWithValidExpiryTime != STANDBY_BUCKET_UNKNOWN) {
1830 newBucket = bucketWithValidExpiryTime;
1831 if (newBucket == STANDBY_BUCKET_ACTIVE || app.currentBucket == newBucket) {
1832 reason = app.bucketingReason;
1833 } else {
1834 reason = REASON_MAIN_USAGE | REASON_SUB_USAGE_ACTIVE_TIMEOUT;
1835 }
1836 if (DEBUG) {
1837 Slog.d(TAG, " Keeping at " + standbyBucketToString(newBucket)
1838 + " due to min timeout");
1839 }
1840 } else if (newBucket == STANDBY_BUCKET_RARE
1841 && mAllowRestrictedBucket
1842 && getBucketForLocked(packageName, userId, elapsedRealtime)
1843 == STANDBY_BUCKET_RESTRICTED) {
1844 // Prediction doesn't think the app will be used anytime soon and
1845 // it's been long enough that it could just time out into restricted,
1846 // so time it out there instead. Using TIMEOUT will allow prediction
1847 // to raise the bucket when it needs to.
1848 newBucket = STANDBY_BUCKET_RESTRICTED;
1849 reason = REASON_MAIN_TIMEOUT;
1850 if (DEBUG) {
1851 Slog.d(TAG,
1852 "Prediction to RARE overridden by timeout into RESTRICTED");
1853 }
1854 }
1855 }
1856
1857 // Make sure we don't put the app in a lower bucket than it's supposed to be in.
1858 newBucket = Math.min(newBucket, getAppMinBucket(packageName, userId));
1859 mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime, newBucket,
1860 reason, resetTimeout);
1861 }
1862 maybeInformListeners(packageName, userId, elapsedRealtime, newBucket, reason, false);
1863 }
1864
1865 @VisibleForTesting
1866 @Override
1867 public boolean isActiveDeviceAdmin(String packageName, int userId) {
1868 synchronized (mActiveAdminApps) {
1869 final Set<String> adminPkgs = mActiveAdminApps.get(userId);
1870 return adminPkgs != null && adminPkgs.contains(packageName);
1871 }
1872 }
1873
1874 @Override
1875 public void addActiveDeviceAdmin(String adminPkg, int userId) {
1876 synchronized (mActiveAdminApps) {
1877 Set<String> adminPkgs = mActiveAdminApps.get(userId);
1878 if (adminPkgs == null) {
1879 adminPkgs = new ArraySet<>();
1880 mActiveAdminApps.put(userId, adminPkgs);
1881 }
1882 adminPkgs.add(adminPkg);
1883 }
1884 }
1885
1886 @Override
1887 public void setActiveAdminApps(Set<String> adminPkgs, int userId) {
1888 synchronized (mActiveAdminApps) {
1889 if (adminPkgs == null) {
1890 mActiveAdminApps.remove(userId);
1891 } else {
1892 mActiveAdminApps.put(userId, adminPkgs);
1893 }
1894 }
1895 }
1896
1897 @Override
1898 public void onAdminDataAvailable() {
1899 mAdminDataAvailableLatch.countDown();
1900 }
1901
1902 /**
1903 * This will only ever be called once - during device boot.
1904 */
1905 private void waitForAdminData() {
1906 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
1907 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
1908 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
1909 }
1910 }
1911
1912 @VisibleForTesting
1913 Set<String> getActiveAdminAppsForTest(int userId) {
1914 synchronized (mActiveAdminApps) {
1915 return mActiveAdminApps.get(userId);
1916 }
1917 }
1918
1919 /**
1920 * Returns {@code true} if the supplied package is the device provisioning app. Otherwise,
1921 * returns {@code false}.
1922 */
1923 private boolean isDeviceProvisioningPackage(String packageName) {
1924 if (mCachedDeviceProvisioningPackage == null) {
1925 mCachedDeviceProvisioningPackage = mContext.getResources().getString(
1926 com.android.internal.R.string.config_deviceProvisioningPackage);
1927 }
1928 return mCachedDeviceProvisioningPackage.equals(packageName);
1929 }
1930
1931 private boolean isCarrierApp(String packageName) {
1932 synchronized (mCarrierPrivilegedLock) {
1933 if (!mHaveCarrierPrivilegedApps) {
1934 fetchCarrierPrivilegedAppsCPL();
1935 }
1936 if (mCarrierPrivilegedApps != null) {
1937 return mCarrierPrivilegedApps.contains(packageName);
1938 }
1939 return false;
1940 }
1941 }
1942
1943 @Override
1944 public void clearCarrierPrivilegedApps() {
1945 if (DEBUG) {
1946 Slog.i(TAG, "Clearing carrier privileged apps list");
1947 }
1948 synchronized (mCarrierPrivilegedLock) {
1949 mHaveCarrierPrivilegedApps = false;
1950 mCarrierPrivilegedApps = null; // Need to be refetched.
1951 }
1952 }
1953
1954 @GuardedBy("mCarrierPrivilegedLock")
1955 private void fetchCarrierPrivilegedAppsCPL() {
1956 TelephonyManager telephonyManager =
1957 mContext.getSystemService(TelephonyManager.class);
1958 mCarrierPrivilegedApps =
1959 telephonyManager.getCarrierPrivilegedPackagesForAllActiveSubscriptions();
1960 mHaveCarrierPrivilegedApps = true;
1961 if (DEBUG) {
1962 Slog.d(TAG, "apps with carrier privilege " + mCarrierPrivilegedApps);
1963 }
1964 }
1965
1966 private boolean isActiveNetworkScorer(@NonNull String packageName) {
1967 // Validity of network scorer cache is limited to a few seconds. Fetch it again
1968 // if longer since query.
1969 // This is a temporary optimization until there's a callback mechanism for changes to network scorer.
1970 final long now = SystemClock.elapsedRealtime();
1971 if (mCachedNetworkScorer == null
1972 || mCachedNetworkScorerAtMillis < now - NETWORK_SCORER_CACHE_DURATION_MILLIS) {
1973 mCachedNetworkScorer = mInjector.getActiveNetworkScorer();
1974 mCachedNetworkScorerAtMillis = now;
1975 }
1976 return packageName.equals(mCachedNetworkScorer);
1977 }
1978
1979 private void informListeners(String packageName, int userId, int bucket, int reason,
1980 boolean userInteraction) {
1981 final boolean idle = bucket >= STANDBY_BUCKET_RARE;
1982 synchronized (mPackageAccessListeners) {
1983 for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
1984 listener.onAppIdleStateChanged(packageName, userId, idle, bucket, reason);
1985 if (userInteraction) {
1986 listener.onUserInteractionStarted(packageName, userId);
1987 }
1988 }
1989 }
1990 }
1991
1992 private void informParoleStateChanged() {
1993 final boolean paroled = isInParole();
1994 synchronized (mPackageAccessListeners) {
1995 for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
1996 listener.onParoleStateChanged(paroled);
1997 }
1998 }
1999 }
2000
2001 @Override
2002 public long getBroadcastResponseWindowDurationMs() {
2003 return mBroadcastResponseWindowDurationMillis;
2004 }
2005
2006 @Override
2007 public int getBroadcastResponseFgThresholdState() {
2008 return mBroadcastResponseFgThresholdState;
2009 }
2010
2011 @Override
2012 public long getBroadcastSessionsDurationMs() {
2013 return mBroadcastSessionsDurationMs;
2014 }
2015
2016 @Override
2017 public long getBroadcastSessionsWithResponseDurationMs() {
2018 return mBroadcastSessionsWithResponseDurationMs;
2019 }
2020
2021 @Override
2022 public boolean shouldNoteResponseEventForAllBroadcastSessions() {
2023 return mNoteResponseEventForAllBroadcastSessions;
2024 }
2025
2026 @Override
2027 @NonNull
2028 public List<String> getBroadcastResponseExemptedRoles() {
2029 return mBroadcastResponseExemptedRolesList;
2030 }
2031
2032 @Override
2033 @NonNull
2034 public List<String> getBroadcastResponseExemptedPermissions() {
2035 return mBroadcastResponseExemptedPermissionsList;
2036 }
2037
2038 @Override
2039 @Nullable
2040 public String getAppStandbyConstant(@NonNull String key) {
2041 return mAppStandbyProperties.get(key);
2042 }
2043
2044 @Override
2045 public void clearLastUsedTimestampsForTest(@NonNull String packageName, @UserIdInt int userId) {
2046 synchronized (mAppIdleLock) {
2047 mAppIdleHistory.clearLastUsedTimestamps(packageName, userId);
2048 }
2049 }
2050
2051 @Override
2052 public void flushToDisk() {
2053 synchronized (mAppIdleLock) {
2054 mAppIdleHistory.writeAppIdleTimes(mInjector.elapsedRealtime());
2055 mAppIdleHistory.writeAppIdleDurations();
2056 }
2057 }
2058
2059 private boolean isDisplayOn() {
2060 return mInjector.isDefaultDisplayOn();
2061 }
2062
2063 @VisibleForTesting
2064 void clearAppIdleForPackage(String packageName, int userId) {
2065 synchronized (mAppIdleLock) {
2066 mAppIdleHistory.clearUsage(packageName, userId);
2067 }
2068 }
2069
2070 /**
2071 * Remove an app from the {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RESTRICTED}
2072 * bucket if it was forced into the bucket by the system because it was buggy.
2073 */
2074 @VisibleForTesting
2075 void maybeUnrestrictBuggyApp(@NonNull String packageName, int userId) {
2076 maybeUnrestrictApp(packageName, userId,
2077 REASON_MAIN_FORCED_BY_SYSTEM, REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY,
2078 REASON_MAIN_DEFAULT, REASON_SUB_DEFAULT_APP_UPDATE);
2079 }
2080
2081 @Override
2082 public void maybeUnrestrictApp(@NonNull String packageName, int userId,
2083 int prevMainReasonRestrict, int prevSubReasonRestrict,
2084 int mainReasonUnrestrict, int subReasonUnrestrict) {
2085 synchronized (mAppIdleLock) {
2086 final long elapsedRealtime = mInjector.elapsedRealtime();
2087 final AppIdleHistory.AppUsageHistory app =
2088 mAppIdleHistory.getAppUsageHistory(packageName, userId, elapsedRealtime);
2089 if (app.currentBucket != STANDBY_BUCKET_RESTRICTED
2090 || (app.bucketingReason & REASON_MAIN_MASK) != prevMainReasonRestrict) {
2091 return;
2092 }
2093
2094 final int newBucket;
2095 final int newReason;
2096 if ((app.bucketingReason & REASON_SUB_MASK) == prevSubReasonRestrict) {
2097 // If it was the only reason the app should be restricted, then lift it out.
2098 newBucket = STANDBY_BUCKET_RARE;
2099 newReason = mainReasonUnrestrict | subReasonUnrestrict;
2100 } else {
2101 // There's another reason the app was restricted. Remove the subreason bit and call
2102 // it a day.
2103 newBucket = STANDBY_BUCKET_RESTRICTED;
2104 newReason = app.bucketingReason & ~prevSubReasonRestrict;
2105 }
2106 mAppIdleHistory.setAppStandbyBucket(
2107 packageName, userId, elapsedRealtime, newBucket, newReason);
2108 maybeInformListeners(packageName, userId, elapsedRealtime, newBucket,
2109 newReason, false);
2110 }
2111 }
2112
2113 private void updatePowerWhitelistCache() {
2114 if (mInjector.getBootPhase() < PHASE_SYSTEM_SERVICES_READY) {
2115 return;
2116 }
2117 mInjector.updatePowerWhitelistCache();
2118 postCheckIdleStates(UserHandle.USER_ALL);
2119 }
2120
2121 private class PackageReceiver extends BroadcastReceiver {
2122 @Override
2123 public void onReceive(Context context, Intent intent) {
2124 final String action = intent.getAction();
2125 final String pkgName = intent.getData().getSchemeSpecificPart();
2126 final int userId = getSendingUserId();
2127 if (Intent.ACTION_PACKAGE_ADDED.equals(action)
2128 || Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
2129 final String[] cmpList = intent.getStringArrayExtra(
2130 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
2131 // If this is PACKAGE_ADDED (cmpList == null), or if it's a whole-package
2132 // enable/disable event (cmpList is just the package name itself), drop
2133 // our carrier privileged app & system-app caches and let them refresh
2134 if (cmpList == null
2135 || (cmpList.length == 1 && pkgName.equals(cmpList[0]))) {
2136 clearCarrierPrivilegedApps();
2137 evaluateSystemAppException(pkgName, userId);
2138 }
2139 // component-level enable/disable can affect bucketing, so we always
2140 // reevaluate that for any PACKAGE_CHANGED
2141 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
2142 mHandler.obtainMessage(MSG_CHECK_PACKAGE_IDLE_STATE, userId, -1, pkgName)
2143 .sendToTarget();
2144 }
2145 }
2146 if ((Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
2147 Intent.ACTION_PACKAGE_ADDED.equals(action))) {
2148 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2149 maybeUnrestrictBuggyApp(pkgName, userId);
2150 } else if (!Intent.ACTION_PACKAGE_ADDED.equals(action)) {
2151 clearAppIdleForPackage(pkgName, userId);
2152 } else {
2153 // Package was just added and it's not being replaced.
2154 if (mAppsToRestoreToRare.contains(userId, pkgName)) {
2155 restoreAppToRare(pkgName, userId, mInjector.elapsedRealtime(),
2156 REASON_MAIN_DEFAULT | REASON_SUB_DEFAULT_APP_RESTORED);
2157 mAppsToRestoreToRare.remove(userId, pkgName);
2158 }
2159 }
2160 }
2161 }
2162 }
2163
2164 private void evaluateSystemAppException(String packageName, int userId) {
2165 if (!mSystemServicesReady) {
2166 // The app will be evaluated in when services are ready.
2167 return;
2168 }
2169 try {
2170 PackageInfo pi = mPackageManager.getPackageInfoAsUser(
2171 packageName, HEADLESS_APP_CHECK_FLAGS, userId);
2172 maybeUpdateHeadlessSystemAppCache(pi);
2173 } catch (PackageManager.NameNotFoundException e) {
2174 synchronized (mHeadlessSystemApps) {
2175 mHeadlessSystemApps.remove(packageName);
2176 }
2177 }
2178 }
2179
2180 /**
2181 * Update the "headless system app" cache.
2182 *
2183 * @return true if the cache is updated.
2184 */
2185 private boolean maybeUpdateHeadlessSystemAppCache(@Nullable PackageInfo pkgInfo) {
2186 if (pkgInfo == null || pkgInfo.applicationInfo == null
2187 || (!pkgInfo.applicationInfo.isSystemApp()
2188 && !pkgInfo.applicationInfo.isUpdatedSystemApp())) {
2189 return false;
2190 }
2191 final Intent frontDoorActivityIntent = new Intent(Intent.ACTION_MAIN)
2192 .addCategory(Intent.CATEGORY_LAUNCHER)
2193 .setPackage(pkgInfo.packageName);
2194 List<ResolveInfo> res = mPackageManager.queryIntentActivitiesAsUser(frontDoorActivityIntent,
2195 HEADLESS_APP_CHECK_FLAGS, UserHandle.USER_SYSTEM);
2196 return updateHeadlessSystemAppCache(pkgInfo.packageName, ArrayUtils.isEmpty(res));
2197 }
2198
2199 private boolean updateHeadlessSystemAppCache(String packageName, boolean add) {
2200 synchronized (mHeadlessSystemApps) {
2201 if (add) {
2202 return mHeadlessSystemApps.add(packageName);
2203 } else {
2204 return mHeadlessSystemApps.remove(packageName);
2205 }
2206 }
2207 }
2208
2209 /** Call on a system version update to temporarily reset system app buckets. */
2210 @Override
2211 public void initializeDefaultsForSystemApps(int userId) {
2212 if (!mSystemServicesReady) {
2213 // Do it later, since SettingsProvider wasn't queried yet for app_standby_enabled
2214 mPendingInitializeDefaults = true;
2215 return;
2216 }
2217 Slog.d(TAG, "Initializing defaults for system apps on user " + userId + ", "
2218 + "appIdleEnabled=" + mAppIdleEnabled);
2219 final long elapsedRealtime = mInjector.elapsedRealtime();
2220 List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
2221 PackageManager.MATCH_DISABLED_COMPONENTS,
2222 userId);
2223 final int packageCount = packages.size();
2224 synchronized (mAppIdleLock) {
2225 for (int i = 0; i < packageCount; i++) {
2226 final PackageInfo pi = packages.get(i);
2227 String packageName = pi.packageName;
2228 if (pi.applicationInfo != null && pi.applicationInfo.isSystemApp()) {
2229 // Mark app as used for 2 hours. After that it can timeout to whatever the
2230 // past usage pattern was.
2231 mAppIdleHistory.reportUsage(packageName, userId, STANDBY_BUCKET_ACTIVE,
2232 REASON_SUB_USAGE_SYSTEM_UPDATE, 0,
2233 elapsedRealtime + mSystemUpdateUsageTimeoutMillis);
2234 }
2235 }
2236 // Immediately persist defaults to disk
2237 mAppIdleHistory.writeAppIdleTimes(userId, elapsedRealtime);
2238 }
2239 }
2240
2241 /** Returns the packages that have launcher icons. */
2242 private Set<String> getSystemPackagesWithLauncherActivities() {
2243 final Intent intent = new Intent(Intent.ACTION_MAIN)
2244 .addCategory(Intent.CATEGORY_LAUNCHER);
2245 List<ResolveInfo> activities = mPackageManager.queryIntentActivitiesAsUser(intent,
2246 HEADLESS_APP_CHECK_FLAGS, UserHandle.USER_SYSTEM);
2247 final ArraySet<String> ret = new ArraySet<>();
2248 for (ResolveInfo ri : activities) {
2249 ret.add(ri.activityInfo.packageName);
2250 }
2251 return ret;
2252 }
2253
2254 /** Call on system boot to get the initial set of headless system apps. */
2255 private void loadHeadlessSystemAppCache() {
2256 final long start = SystemClock.uptimeMillis();
2257 final List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
2258 HEADLESS_APP_CHECK_FLAGS, UserHandle.USER_SYSTEM);
2259
2260 final Set<String> systemLauncherActivities = getSystemPackagesWithLauncherActivities();
2261
2262 final int packageCount = packages.size();
2263 for (int i = 0; i < packageCount; i++) {
2264 final PackageInfo pkgInfo = packages.get(i);
2265 if (pkgInfo == null) {
2266 continue;
2267 }
2268 final String pkg = pkgInfo.packageName;
2269 final boolean isHeadLess = !systemLauncherActivities.contains(pkg);
2270
2271 if (updateHeadlessSystemAppCache(pkg, isHeadLess)) {
2272 mHandler.obtainMessage(MSG_CHECK_PACKAGE_IDLE_STATE,
2273 UserHandle.USER_SYSTEM, -1, pkg)
2274 .sendToTarget();
2275 }
2276 }
2277 final long end = SystemClock.uptimeMillis();
2278 Slog.d(TAG, "Loaded headless system app cache in " + (end - start) + " ms:"
2279 + " appIdleEnabled=" + mAppIdleEnabled);
2280 }
2281
2282 @Override
2283 public void postReportContentProviderUsage(String name, String packageName, int userId) {
2284 ContentProviderUsageRecord record = ContentProviderUsageRecord.obtain(name, packageName,
2285 userId);
2286 mHandler.obtainMessage(MSG_REPORT_CONTENT_PROVIDER_USAGE, record)
2287 .sendToTarget();
2288 }
2289
2290 @Override
2291 public void postReportSyncScheduled(String packageName, int userId, boolean exempted) {
2292 mHandler.obtainMessage(MSG_REPORT_SYNC_SCHEDULED, userId, exempted ? 1 : 0, packageName)
2293 .sendToTarget();
2294 }
2295
2296 @Override
2297 public void postReportExemptedSyncStart(String packageName, int userId) {
2298 mHandler.obtainMessage(MSG_REPORT_EXEMPTED_SYNC_START, userId, 0, packageName)
2299 .sendToTarget();
2300 }
2301
2302 @VisibleForTesting
2303 AppIdleHistory getAppIdleHistoryForTest() {
2304 synchronized (mAppIdleLock) {
2305 return mAppIdleHistory;
2306 }
2307 }
2308
2309 @Override
2310 public void dumpUsers(IndentingPrintWriter idpw, int[] userIds, List<String> pkgs) {
2311 synchronized (mAppIdleLock) {
2312 mAppIdleHistory.dumpUsers(idpw, userIds, pkgs);
2313 }
2314 }
2315
2316 @Override
2317 public void dumpState(String[] args, PrintWriter pw) {
2318 synchronized (mCarrierPrivilegedLock) {
2319 pw.println("Carrier privileged apps (have=" + mHaveCarrierPrivilegedApps
2320 + "): " + mCarrierPrivilegedApps);
2321 }
2322
2323 pw.println();
2324 pw.println("Settings:");
2325
2326 pw.print(" mCheckIdleIntervalMillis=");
2327 TimeUtils.formatDuration(mCheckIdleIntervalMillis, pw);
2328 pw.println();
2329
2330 pw.print(" mStrongUsageTimeoutMillis=");
2331 TimeUtils.formatDuration(mStrongUsageTimeoutMillis, pw);
2332 pw.println();
2333 pw.print(" mNotificationSeenTimeoutMillis=");
2334 TimeUtils.formatDuration(mNotificationSeenTimeoutMillis, pw);
2335 pw.println();
2336 pw.print(" mNotificationSeenPromotedBucket=");
2337 pw.print(standbyBucketToString(mNotificationSeenPromotedBucket));
2338 pw.println();
2339 pw.print(" mTriggerQuotaBumpOnNotificationSeen=");
2340 pw.print(mTriggerQuotaBumpOnNotificationSeen);
2341 pw.println();
2342 pw.print(" mRetainNotificationSeenImpactForPreTApps=");
2343 pw.print(mRetainNotificationSeenImpactForPreTApps);
2344 pw.println();
2345 pw.print(" mSlicePinnedTimeoutMillis=");
2346 TimeUtils.formatDuration(mSlicePinnedTimeoutMillis, pw);
2347 pw.println();
2348 pw.print(" mSyncAdapterTimeoutMillis=");
2349 TimeUtils.formatDuration(mSyncAdapterTimeoutMillis, pw);
2350 pw.println();
2351 pw.print(" mSystemInteractionTimeoutMillis=");
2352 TimeUtils.formatDuration(mSystemInteractionTimeoutMillis, pw);
2353 pw.println();
2354 pw.print(" mInitialForegroundServiceStartTimeoutMillis=");
2355 TimeUtils.formatDuration(mInitialForegroundServiceStartTimeoutMillis, pw);
2356 pw.println();
2357
2358 pw.print(" mPredictionTimeoutMillis=");
2359 TimeUtils.formatDuration(mPredictionTimeoutMillis, pw);
2360 pw.println();
2361
2362 pw.print(" mExemptedSyncScheduledNonDozeTimeoutMillis=");
2363 TimeUtils.formatDuration(mExemptedSyncScheduledNonDozeTimeoutMillis, pw);
2364 pw.println();
2365 pw.print(" mExemptedSyncScheduledDozeTimeoutMillis=");
2366 TimeUtils.formatDuration(mExemptedSyncScheduledDozeTimeoutMillis, pw);
2367 pw.println();
2368 pw.print(" mExemptedSyncStartTimeoutMillis=");
2369 TimeUtils.formatDuration(mExemptedSyncStartTimeoutMillis, pw);
2370 pw.println();
2371 pw.print(" mUnexemptedSyncScheduledTimeoutMillis=");
2372 TimeUtils.formatDuration(mUnexemptedSyncScheduledTimeoutMillis, pw);
2373 pw.println();
2374
2375 pw.print(" mSystemUpdateUsageTimeoutMillis=");
2376 TimeUtils.formatDuration(mSystemUpdateUsageTimeoutMillis, pw);
2377 pw.println();
2378
2379 pw.print(" mBroadcastResponseWindowDurationMillis=");
2380 TimeUtils.formatDuration(mBroadcastResponseWindowDurationMillis, pw);
2381 pw.println();
2382
2383 pw.print(" mBroadcastResponseFgThresholdState=");
2384 pw.print(ActivityManager.procStateToString(mBroadcastResponseFgThresholdState));
2385 pw.println();
2386
2387 pw.print(" mBroadcastSessionsDurationMs=");
2388 TimeUtils.formatDuration(mBroadcastSessionsDurationMs, pw);
2389 pw.println();
2390
2391 pw.print(" mBroadcastSessionsWithResponseDurationMs=");
2392 TimeUtils.formatDuration(mBroadcastSessionsWithResponseDurationMs, pw);
2393 pw.println();
2394
2395 pw.print(" mNoteResponseEventForAllBroadcastSessions=");
2396 pw.print(mNoteResponseEventForAllBroadcastSessions);
2397 pw.println();
2398
2399 pw.print(" mBroadcastResponseExemptedRoles");
2400 pw.print(mBroadcastResponseExemptedRoles);
2401 pw.println();
2402
2403 pw.print(" mBroadcastResponseExemptedPermissions");
2404 pw.print(mBroadcastResponseExemptedPermissions);
2405 pw.println();
2406
2407 pw.println();
2408 pw.print("mAppIdleEnabled="); pw.print(mAppIdleEnabled);
2409 pw.print(" mAllowRestrictedBucket=");
2410 pw.print(mAllowRestrictedBucket);
2411 pw.print(" mIsCharging=");
2412 pw.print(mIsCharging);
2413 pw.println();
2414 pw.print("mScreenThresholds="); pw.println(Arrays.toString(mAppStandbyScreenThresholds));
2415 pw.print("mElapsedThresholds="); pw.println(Arrays.toString(mAppStandbyElapsedThresholds));
2416 pw.println();
2417
2418 pw.println("mHeadlessSystemApps=[");
2419 synchronized (mHeadlessSystemApps) {
2420 for (int i = mHeadlessSystemApps.size() - 1; i >= 0; --i) {
2421 pw.print(" ");
2422 pw.print(mHeadlessSystemApps.valueAt(i));
2423 if (i != 0) pw.println(",");
2424 }
2425 }
2426 pw.println("]");
2427 pw.println();
2428
2429 pw.println("mSystemPackagesAppIds=[");
2430 synchronized (mSystemPackagesAppIds) {
2431 for (int i = mSystemPackagesAppIds.size() - 1; i >= 0; --i) {
2432 pw.print(" ");
2433 pw.print(mSystemPackagesAppIds.get(i));
2434 if (i != 0) pw.println(",");
2435 }
2436 }
2437 pw.println("]");
2438 pw.println();
2439
2440 mInjector.dump(pw);
2441 }
2442
2443 /**
2444 * Injector for interaction with external code. Override methods to provide a mock
2445 * implementation for tests.
2446 * onBootPhase() must be called with at least the PHASE_SYSTEM_SERVICES_READY
2447 */
2448 static class Injector {
2449
2450 private final Context mContext;
2451 private final Looper mLooper;
2452 private IBatteryStats mBatteryStats;
2453 private BatteryManager mBatteryManager;
2454 private PackageManagerInternal mPackageManagerInternal;
2455 private DisplayManager mDisplayManager;
2456 private PowerManager mPowerManager;
2457 private IDeviceIdleController mDeviceIdleController;
2458 private CrossProfileAppsInternal mCrossProfileAppsInternal;
2459 private AlarmManagerInternal mAlarmManagerInternal;
2460 int mBootPhase;
2461 /**
2462 * The minimum amount of time required since the last user interaction before an app can be
2463 * automatically placed in the RESTRICTED bucket.
2464 */
2465 long mAutoRestrictedBucketDelayMs =
2466 ConstantsObserver.DEFAULT_AUTO_RESTRICTED_BUCKET_DELAY_MS;
2467 /**
2468 * Cached set of apps that are power whitelisted, including those not whitelisted from idle.
2469 */
2470 @GuardedBy("mPowerWhitelistedApps")
2471 private final ArraySet<String> mPowerWhitelistedApps = new ArraySet<>();
2472 private String mWellbeingApp = null;
2473
2474 Injector(Context context, Looper looper) {
2475 mContext = context;
2476 mLooper = looper;
2477 }
2478
2479 Context getContext() {
2480 return mContext;
2481 }
2482
2483 Looper getLooper() {
2484 return mLooper;
2485 }
2486
2487 void onBootPhase(int phase) {
2488 if (phase == PHASE_SYSTEM_SERVICES_READY) {
2489 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(
2490 ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
2491 mBatteryStats = IBatteryStats.Stub.asInterface(
2492 ServiceManager.getService(BatteryStats.SERVICE_NAME));
2493 mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
2494 mDisplayManager = (DisplayManager) mContext.getSystemService(
2495 Context.DISPLAY_SERVICE);
2496 mPowerManager = mContext.getSystemService(PowerManager.class);
2497 mBatteryManager = mContext.getSystemService(BatteryManager.class);
2498 mCrossProfileAppsInternal = LocalServices.getService(
2499 CrossProfileAppsInternal.class);
2500 mAlarmManagerInternal = LocalServices.getService(AlarmManagerInternal.class);
2501
2502 final ActivityManager activityManager =
2503 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2504 if (activityManager.isLowRamDevice() || ActivityManager.isSmallBatteryDevice()) {
2505 mAutoRestrictedBucketDelayMs = 12 * ONE_HOUR;
2506 }
2507 } else if (phase == PHASE_BOOT_COMPLETED) {
2508 // mWellbeingApp needs to be initialized lazily after boot to allow for roles to be
2509 // parsed and the wellbeing role-holder to be assigned
2510 final PackageManager packageManager = mContext.getPackageManager();
2511 mWellbeingApp = packageManager.getWellbeingPackageName();
2512 }
2513 mBootPhase = phase;
2514 }
2515
2516 int getBootPhase() {
2517 return mBootPhase;
2518 }
2519
2520 /**
2521 * Returns the elapsed realtime since the device started. Override this
2522 * to control the clock.
2523 * @return elapsed realtime
2524 */
2525 long elapsedRealtime() {
2526 return SystemClock.elapsedRealtime();
2527 }
2528
2529 long currentTimeMillis() {
2530 return System.currentTimeMillis();
2531 }
2532
2533 boolean isAppIdleEnabled() {
2534 final boolean buildFlag = mContext.getResources().getBoolean(
2535 com.android.internal.R.bool.config_enableAutoPowerModes);
2536 final boolean runtimeFlag = Global.getInt(mContext.getContentResolver(),
2537 Global.APP_STANDBY_ENABLED, 1) == 1
2538 && Global.getInt(mContext.getContentResolver(),
2539 Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED, 1) == 1;
2540 return buildFlag && runtimeFlag;
2541 }
2542
2543 boolean isCharging() {
2544 return mBatteryManager.isCharging();
2545 }
2546
2547 boolean isNonIdleWhitelisted(String packageName) {
2548 if (mBootPhase < PHASE_SYSTEM_SERVICES_READY) {
2549 return false;
2550 }
2551 synchronized (mPowerWhitelistedApps) {
2552 return mPowerWhitelistedApps.contains(packageName);
2553 }
2554 }
2555
2556 /**
2557 * Returns {@code true} if the supplied package is the wellbeing app. Otherwise,
2558 * returns {@code false}.
2559 */
2560 boolean isWellbeingPackage(@NonNull String packageName) {
2561 return packageName.equals(mWellbeingApp);
2562 }
2563
2564 boolean hasExactAlarmPermission(String packageName, int uid) {
2565 return mAlarmManagerInternal.hasExactAlarmPermission(packageName, uid);
2566 }
2567
2568 void updatePowerWhitelistCache() {
2569 try {
2570 // Don't call out to DeviceIdleController with the lock held.
2571 final String[] whitelistedPkgs =
2572 mDeviceIdleController.getFullPowerWhitelistExceptIdle();
2573 synchronized (mPowerWhitelistedApps) {
2574 mPowerWhitelistedApps.clear();
2575 final int len = whitelistedPkgs.length;
2576 for (int i = 0; i < len; ++i) {
2577 mPowerWhitelistedApps.add(whitelistedPkgs[i]);
2578 }
2579 }
2580 } catch (RemoteException e) {
2581 // Should not happen.
2582 Slog.wtf(TAG, "Failed to get power whitelist", e);
2583 }
2584 }
2585
2586 boolean isRestrictedBucketEnabled() {
2587 return Global.getInt(mContext.getContentResolver(),
2588 Global.ENABLE_RESTRICTED_BUCKET,
2589 Global.DEFAULT_ENABLE_RESTRICTED_BUCKET) == 1;
2590 }
2591
2592 File getDataSystemDirectory() {
2593 return Environment.getDataSystemDirectory();
2594 }
2595
2596 /**
2597 * Return the minimum amount of time that must have passed since the last user usage before
2598 * an app can be automatically put into the
2599 * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RESTRICTED} bucket.
2600 */
2601 long getAutoRestrictedBucketDelayMs() {
2602 return mAutoRestrictedBucketDelayMs;
2603 }
2604
2605 void noteEvent(int event, String packageName, int uid) throws RemoteException {
2606 mBatteryStats.noteEvent(event, packageName, uid);
2607 }
2608
2609 PackageManagerInternal getPackageManagerInternal() {
2610 return mPackageManagerInternal;
2611 }
2612
2613 boolean isPackageEphemeral(int userId, String packageName) {
2614 return mPackageManagerInternal.isPackageEphemeral(userId, packageName);
2615 }
2616
2617 boolean isPackageInstalled(String packageName, int flags, int userId) {
2618 return mPackageManagerInternal.getPackageUid(packageName, flags, userId) >= 0;
2619 }
2620
2621 int[] getRunningUserIds() throws RemoteException {
2622 return ActivityManager.getService().getRunningUserIds();
2623 }
2624
2625 boolean isDefaultDisplayOn() {
2626 return mDisplayManager
2627 .getDisplay(Display.DEFAULT_DISPLAY).getState() == Display.STATE_ON;
2628 }
2629
2630 void registerDisplayListener(DisplayManager.DisplayListener listener, Handler handler) {
2631 mDisplayManager.registerDisplayListener(listener, handler);
2632 }
2633
2634 String getActiveNetworkScorer() {
2635 NetworkScoreManager nsm = (NetworkScoreManager) mContext.getSystemService(
2636 Context.NETWORK_SCORE_SERVICE);
2637 return nsm.getActiveScorerPackage();
2638 }
2639
2640 public boolean isBoundWidgetPackage(AppWidgetManager appWidgetManager, String packageName,
2641 int userId) {
2642 return appWidgetManager.isBoundWidgetPackage(packageName, userId);
2643 }
2644
2645 @NonNull
2646 DeviceConfig.Properties getDeviceConfigProperties(String... keys) {
2647 return DeviceConfig.getProperties(DeviceConfig.NAMESPACE_APP_STANDBY, keys);
2648 }
2649
2650 /** Whether the device is in doze or not. */
2651 public boolean isDeviceIdleMode() {
2652 return mPowerManager.isDeviceIdleMode();
2653 }
2654
2655 public List<UserHandle> getValidCrossProfileTargets(String pkg, int userId) {
2656 final int uid = mPackageManagerInternal.getPackageUid(pkg, /* flags= */ 0, userId);
2657 final AndroidPackage aPkg = mPackageManagerInternal.getPackage(uid);
2658 if (uid < 0
2659 || aPkg == null
2660 || !aPkg.isCrossProfile()
2661 || !mCrossProfileAppsInternal
2662 .verifyUidHasInteractAcrossProfilePermission(pkg, uid)) {
2663 if (uid >= 0 && aPkg == null) {
2664 Slog.wtf(TAG, "Null package retrieved for UID " + uid);
2665 }
2666 return Collections.emptyList();
2667 }
2668 return mCrossProfileAppsInternal.getTargetUserProfiles(pkg, userId);
2669 }
2670
2671 void registerDeviceConfigPropertiesChangedListener(
2672 @NonNull DeviceConfig.OnPropertiesChangedListener listener) {
2673 DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_STANDBY,
2674 JobSchedulerBackgroundThread.getExecutor(), listener);
2675 }
2676
2677 void dump(PrintWriter pw) {
2678 pw.println("mPowerWhitelistedApps=[");
2679 synchronized (mPowerWhitelistedApps) {
2680 for (int i = mPowerWhitelistedApps.size() - 1; i >= 0; --i) {
2681 pw.print(" ");
2682 pw.print(mPowerWhitelistedApps.valueAt(i));
2683 pw.println(",");
2684 }
2685 }
2686 pw.println("]");
2687 pw.println();
2688 }
2689 }
2690
2691 class AppStandbyHandler extends Handler {
2692
2693 AppStandbyHandler(Looper looper) {
2694 super(looper);
2695 }
2696
2697 @Override
2698 public void handleMessage(Message msg) {
2699 switch (msg.what) {
2700 case MSG_INFORM_LISTENERS:
2701 // TODO(230875908): Properly notify BatteryStats when apps change from active to
2702 // idle, and vice versa
2703 StandbyUpdateRecord r = (StandbyUpdateRecord) msg.obj;
2704 informListeners(r.packageName, r.userId, r.bucket, r.reason,
2705 r.isUserInteraction);
2706 r.recycle();
2707 break;
2708
2709 case MSG_FORCE_IDLE_STATE:
2710 forceIdleState((String) msg.obj, msg.arg1, msg.arg2 == 1);
2711 break;
2712
2713 case MSG_CHECK_IDLE_STATES:
2714 removeMessages(MSG_CHECK_IDLE_STATES);
2715
2716 long earliestCheck = Long.MAX_VALUE;
2717 final long nowElapsed = mInjector.elapsedRealtime();
2718 synchronized (mPendingIdleStateChecks) {
2719 for (int i = mPendingIdleStateChecks.size() - 1; i >= 0; --i) {
2720 long expirationTime = mPendingIdleStateChecks.valueAt(i);
2721
2722 if (expirationTime <= nowElapsed) {
2723 final int userId = mPendingIdleStateChecks.keyAt(i);
2724 if (checkIdleStates(userId) && mAppIdleEnabled) {
2725 expirationTime = nowElapsed + mCheckIdleIntervalMillis;
2726 mPendingIdleStateChecks.put(userId, expirationTime);
2727 } else {
2728 mPendingIdleStateChecks.removeAt(i);
2729 continue;
2730 }
2731 }
2732
2733 earliestCheck = Math.min(earliestCheck, expirationTime);
2734 }
2735 }
2736 if (earliestCheck != Long.MAX_VALUE) {
2737 mHandler.sendMessageDelayed(
2738 mHandler.obtainMessage(MSG_CHECK_IDLE_STATES),
2739 earliestCheck - nowElapsed);
2740 }
2741 break;
2742
2743 case MSG_ONE_TIME_CHECK_IDLE_STATES:
2744 mHandler.removeMessages(MSG_ONE_TIME_CHECK_IDLE_STATES);
2745 waitForAdminData();
2746 checkIdleStates(UserHandle.USER_ALL);
2747 break;
2748
2749 case MSG_TRIGGER_LISTENER_QUOTA_BUMP:
2750 triggerListenerQuotaBump((String) msg.obj, msg.arg1);
2751 break;
2752
2753 case MSG_REPORT_CONTENT_PROVIDER_USAGE:
2754 ContentProviderUsageRecord record = (ContentProviderUsageRecord) msg.obj;
2755 reportContentProviderUsage(record.name, record.packageName, record.userId);
2756 record.recycle();
2757 break;
2758
2759 case MSG_PAROLE_STATE_CHANGED:
2760 if (DEBUG) Slog.d(TAG, "Parole state: " + isInParole());
2761 informParoleStateChanged();
2762 break;
2763
2764 case MSG_CHECK_PACKAGE_IDLE_STATE:
2765 checkAndUpdateStandbyState((String) msg.obj, msg.arg1, msg.arg2,
2766 mInjector.elapsedRealtime());
2767 break;
2768
2769 case MSG_REPORT_SYNC_SCHEDULED:
2770 final boolean exempted = msg.arg2 > 0 ? true : false;
2771 if (exempted) {
2772 reportExemptedSyncScheduled((String) msg.obj, msg.arg1);
2773 } else {
2774 reportUnexemptedSyncScheduled((String) msg.obj, msg.arg1);
2775 }
2776 break;
2777
2778 case MSG_REPORT_EXEMPTED_SYNC_START:
2779 reportExemptedSyncStart((String) msg.obj, msg.arg1);
2780 break;
2781
2782 default:
2783 super.handleMessage(msg);
2784 break;
2785
2786 }
2787 }
2788 };
2789
2790 private class DeviceStateReceiver extends BroadcastReceiver {
2791 @Override
2792 public void onReceive(Context context, Intent intent) {
2793 switch (intent.getAction()) {
2794 case BatteryManager.ACTION_CHARGING:
2795 setChargingState(true);
2796 break;
2797 case BatteryManager.ACTION_DISCHARGING:
2798 setChargingState(false);
2799 break;
2800 case PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED:
2801 if (mSystemServicesReady) {
2802 mHandler.post(AppStandbyController.this::updatePowerWhitelistCache);
2803 }
2804 break;
2805 }
2806 }
2807 }
2808
2809 private final DisplayManager.DisplayListener mDisplayListener
2810 = new DisplayManager.DisplayListener() {
2811
2812 @Override public void onDisplayAdded(int displayId) {
2813 }
2814
2815 @Override public void onDisplayRemoved(int displayId) {
2816 }
2817
2818 @Override public void onDisplayChanged(int displayId) {
2819 if (displayId == Display.DEFAULT_DISPLAY) {
2820 final boolean displayOn = isDisplayOn();
2821 synchronized (mAppIdleLock) {
2822 mAppIdleHistory.updateDisplay(displayOn, mInjector.elapsedRealtime());
2823 }
2824 }
2825 }
2826 };
2827
2828 /**
2829 * Observe changes for {@link DeviceConfig#NAMESPACE_APP_STANDBY} and other standby related
2830 * Settings constants.
2831 */
2832 private class ConstantsObserver extends ContentObserver implements
2833 DeviceConfig.OnPropertiesChangedListener {
2834 private static final String KEY_STRONG_USAGE_HOLD_DURATION = "strong_usage_duration";
2835 private static final String KEY_NOTIFICATION_SEEN_HOLD_DURATION =
2836 "notification_seen_duration";
2837 private static final String KEY_NOTIFICATION_SEEN_PROMOTED_BUCKET =
2838 "notification_seen_promoted_bucket";
2839 private static final String KEY_RETAIN_NOTIFICATION_SEEN_IMPACT_FOR_PRE_T_APPS =
2840 "retain_notification_seen_impact_for_pre_t_apps";
2841 private static final String KEY_TRIGGER_QUOTA_BUMP_ON_NOTIFICATION_SEEN =
2842 "trigger_quota_bump_on_notification_seen";
2843 private static final String KEY_SLICE_PINNED_HOLD_DURATION =
2844 "slice_pinned_duration";
2845 private static final String KEY_SYSTEM_UPDATE_HOLD_DURATION =
2846 "system_update_usage_duration";
2847 private static final String KEY_PREDICTION_TIMEOUT = "prediction_timeout";
2848 private static final String KEY_SYNC_ADAPTER_HOLD_DURATION = "sync_adapter_duration";
2849 private static final String KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION =
2850 "exempted_sync_scheduled_nd_duration";
2851 private static final String KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION =
2852 "exempted_sync_scheduled_d_duration";
2853 private static final String KEY_EXEMPTED_SYNC_START_HOLD_DURATION =
2854 "exempted_sync_start_duration";
2855 private static final String KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION =
2856 "unexempted_sync_scheduled_duration";
2857 private static final String KEY_SYSTEM_INTERACTION_HOLD_DURATION =
2858 "system_interaction_duration";
2859 private static final String KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION =
2860 "initial_foreground_service_start_duration";
2861 private static final String KEY_AUTO_RESTRICTED_BUCKET_DELAY_MS =
2862 "auto_restricted_bucket_delay_ms";
2863 private static final String KEY_CROSS_PROFILE_APPS_SHARE_STANDBY_BUCKETS =
2864 "cross_profile_apps_share_standby_buckets";
2865 private static final String KEY_PREFIX_SCREEN_TIME_THRESHOLD = "screen_threshold_";
2866 private final String[] KEYS_SCREEN_TIME_THRESHOLDS = {
2867 KEY_PREFIX_SCREEN_TIME_THRESHOLD + "active",
2868 KEY_PREFIX_SCREEN_TIME_THRESHOLD + "working_set",
2869 KEY_PREFIX_SCREEN_TIME_THRESHOLD + "frequent",
2870 KEY_PREFIX_SCREEN_TIME_THRESHOLD + "rare",
2871 KEY_PREFIX_SCREEN_TIME_THRESHOLD + "restricted"
2872 };
2873 private static final String KEY_PREFIX_ELAPSED_TIME_THRESHOLD = "elapsed_threshold_";
2874 private final String[] KEYS_ELAPSED_TIME_THRESHOLDS = {
2875 KEY_PREFIX_ELAPSED_TIME_THRESHOLD + "active",
2876 KEY_PREFIX_ELAPSED_TIME_THRESHOLD + "working_set",
2877 KEY_PREFIX_ELAPSED_TIME_THRESHOLD + "frequent",
2878 KEY_PREFIX_ELAPSED_TIME_THRESHOLD + "rare",
2879 KEY_PREFIX_ELAPSED_TIME_THRESHOLD + "restricted"
2880 };
2881 private static final String KEY_BROADCAST_RESPONSE_WINDOW_DURATION_MS =
2882 "broadcast_response_window_timeout_ms";
2883 private static final String KEY_BROADCAST_RESPONSE_FG_THRESHOLD_STATE =
2884 "broadcast_response_fg_threshold_state";
2885 private static final String KEY_BROADCAST_SESSIONS_DURATION_MS =
2886 "broadcast_sessions_duration_ms";
2887 private static final String KEY_BROADCAST_SESSIONS_WITH_RESPONSE_DURATION_MS =
2888 "broadcast_sessions_with_response_duration_ms";
2889 private static final String KEY_NOTE_RESPONSE_EVENT_FOR_ALL_BROADCAST_SESSIONS =
2890 "note_response_event_for_all_broadcast_sessions";
2891 private static final String KEY_BROADCAST_RESPONSE_EXEMPTED_ROLES =
2892 "brodacast_response_exempted_roles";
2893 private static final String KEY_BROADCAST_RESPONSE_EXEMPTED_PERMISSIONS =
2894 "brodacast_response_exempted_permissions";
2895
2896 public static final long DEFAULT_CHECK_IDLE_INTERVAL_MS =
2897 COMPRESS_TIME ? ONE_MINUTE : 4 * ONE_HOUR;
2898 public static final long DEFAULT_STRONG_USAGE_TIMEOUT =
2899 COMPRESS_TIME ? ONE_MINUTE : 1 * ONE_HOUR;
2900 public static final long DEFAULT_NOTIFICATION_TIMEOUT =
2901 COMPRESS_TIME ? 12 * ONE_MINUTE : 12 * ONE_HOUR;
2902 public static final long DEFAULT_SLICE_PINNED_TIMEOUT =
2903 COMPRESS_TIME ? 12 * ONE_MINUTE : 12 * ONE_HOUR;
2904 public static final int DEFAULT_NOTIFICATION_SEEN_PROMOTED_BUCKET =
2905 STANDBY_BUCKET_WORKING_SET;
2906 public static final boolean DEFAULT_RETAIN_NOTIFICATION_SEEN_IMPACT_FOR_PRE_T_APPS = false;
2907 public static final boolean DEFAULT_TRIGGER_QUOTA_BUMP_ON_NOTIFICATION_SEEN = false;
2908 public static final long DEFAULT_SYSTEM_UPDATE_TIMEOUT =
2909 COMPRESS_TIME ? 2 * ONE_MINUTE : 2 * ONE_HOUR;
2910 public static final long DEFAULT_SYSTEM_INTERACTION_TIMEOUT =
2911 COMPRESS_TIME ? ONE_MINUTE : 10 * ONE_MINUTE;
2912 public static final long DEFAULT_SYNC_ADAPTER_TIMEOUT =
2913 COMPRESS_TIME ? ONE_MINUTE : 10 * ONE_MINUTE;
2914 public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT =
2915 COMPRESS_TIME ? (ONE_MINUTE / 2) : 10 * ONE_MINUTE;
2916 public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT =
2917 COMPRESS_TIME ? ONE_MINUTE : 4 * ONE_HOUR;
2918 public static final long DEFAULT_EXEMPTED_SYNC_START_TIMEOUT =
2919 COMPRESS_TIME ? ONE_MINUTE : 10 * ONE_MINUTE;
2920 public static final long DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT =
2921 COMPRESS_TIME ? ONE_MINUTE : 10 * ONE_MINUTE;
2922 public static final long DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT =
2923 COMPRESS_TIME ? ONE_MINUTE : 30 * ONE_MINUTE;
2924 public static final long DEFAULT_AUTO_RESTRICTED_BUCKET_DELAY_MS =
2925 COMPRESS_TIME ? ONE_MINUTE : ONE_DAY;
2926 public static final boolean DEFAULT_CROSS_PROFILE_APPS_SHARE_STANDBY_BUCKETS = true;
2927 public static final long DEFAULT_BROADCAST_RESPONSE_WINDOW_DURATION_MS =
2928 2 * ONE_MINUTE;
2929 public static final int DEFAULT_BROADCAST_RESPONSE_FG_THRESHOLD_STATE =
2930 ActivityManager.PROCESS_STATE_TOP;
2931 public static final long DEFAULT_BROADCAST_SESSIONS_DURATION_MS =
2932 2 * ONE_MINUTE;
2933 public static final long DEFAULT_BROADCAST_SESSIONS_WITH_RESPONSE_DURATION_MS =
2934 2 * ONE_MINUTE;
2935 public static final boolean DEFAULT_NOTE_RESPONSE_EVENT_FOR_ALL_BROADCAST_SESSIONS =
2936 true;
2937 private static final String DEFAULT_BROADCAST_RESPONSE_EXEMPTED_ROLES = "";
2938 private static final String DEFAULT_BROADCAST_RESPONSE_EXEMPTED_PERMISSIONS = "";
2939
2940 private final TextUtils.SimpleStringSplitter mStringPipeSplitter =
2941 new TextUtils.SimpleStringSplitter('|');
2942
2943 ConstantsObserver(Handler handler) {
2944 super(handler);
2945 }
2946
2947 public void start() {
2948 final ContentResolver cr = mContext.getContentResolver();
2949 // APP_STANDBY_ENABLED is a SystemApi that some apps may be watching, so best to
2950 // leave it in Settings.
2951 cr.registerContentObserver(Global.getUriFor(Global.APP_STANDBY_ENABLED), false, this);
2952 // Leave ENABLE_RESTRICTED_BUCKET as a user-controlled setting which will stay in
2953 // Settings.
2954 // TODO: make setting user-specific
2955 cr.registerContentObserver(Global.getUriFor(Global.ENABLE_RESTRICTED_BUCKET),
2956 false, this);
2957 // ADAPTIVE_BATTERY_MANAGEMENT_ENABLED is a user setting, so it has to stay in Settings.
2958 cr.registerContentObserver(Global.getUriFor(Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED),
2959 false, this);
2960 mInjector.registerDeviceConfigPropertiesChangedListener(this);
2961 // Load all the constants.
2962 // postOneTimeCheckIdleStates() doesn't need to be called on boot.
2963 processProperties(mInjector.getDeviceConfigProperties());
2964 updateSettings();
2965 }
2966
2967 @Override
2968 public void onChange(boolean selfChange) {
2969 updateSettings();
2970 postOneTimeCheckIdleStates();
2971 }
2972
2973 @Override
2974 public void onPropertiesChanged(DeviceConfig.Properties properties) {
2975 processProperties(properties);
2976 postOneTimeCheckIdleStates();
2977 }
2978
2979 private void processProperties(DeviceConfig.Properties properties) {
2980 boolean timeThresholdsUpdated = false;
2981 synchronized (mAppIdleLock) {
2982 for (String name : properties.getKeyset()) {
2983 if (name == null) {
2984 continue;
2985 }
2986 switch (name) {
2987 case KEY_AUTO_RESTRICTED_BUCKET_DELAY_MS:
2988 mInjector.mAutoRestrictedBucketDelayMs = Math.max(
2989 COMPRESS_TIME ? ONE_MINUTE : 4 * ONE_HOUR,
2990 properties.getLong(KEY_AUTO_RESTRICTED_BUCKET_DELAY_MS,
2991 DEFAULT_AUTO_RESTRICTED_BUCKET_DELAY_MS));
2992 break;
2993 case KEY_CROSS_PROFILE_APPS_SHARE_STANDBY_BUCKETS:
2994 mLinkCrossProfileApps = properties.getBoolean(
2995 KEY_CROSS_PROFILE_APPS_SHARE_STANDBY_BUCKETS,
2996 DEFAULT_CROSS_PROFILE_APPS_SHARE_STANDBY_BUCKETS);
2997 break;
2998 case KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION:
2999 mInitialForegroundServiceStartTimeoutMillis = properties.getLong(
3000 KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION,
3001 DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT);
3002 break;
3003 case KEY_NOTIFICATION_SEEN_HOLD_DURATION:
3004 mNotificationSeenTimeoutMillis = properties.getLong(
3005 KEY_NOTIFICATION_SEEN_HOLD_DURATION,
3006 DEFAULT_NOTIFICATION_TIMEOUT);
3007 break;
3008 case KEY_NOTIFICATION_SEEN_PROMOTED_BUCKET:
3009 mNotificationSeenPromotedBucket = properties.getInt(
3010 KEY_NOTIFICATION_SEEN_PROMOTED_BUCKET,
3011 DEFAULT_NOTIFICATION_SEEN_PROMOTED_BUCKET);
3012 break;
3013 case KEY_RETAIN_NOTIFICATION_SEEN_IMPACT_FOR_PRE_T_APPS:
3014 mRetainNotificationSeenImpactForPreTApps = properties.getBoolean(
3015 KEY_RETAIN_NOTIFICATION_SEEN_IMPACT_FOR_PRE_T_APPS,
3016 DEFAULT_RETAIN_NOTIFICATION_SEEN_IMPACT_FOR_PRE_T_APPS);
3017 break;
3018 case KEY_TRIGGER_QUOTA_BUMP_ON_NOTIFICATION_SEEN:
3019 mTriggerQuotaBumpOnNotificationSeen = properties.getBoolean(
3020 KEY_TRIGGER_QUOTA_BUMP_ON_NOTIFICATION_SEEN,
3021 DEFAULT_TRIGGER_QUOTA_BUMP_ON_NOTIFICATION_SEEN);
3022 break;
3023 case KEY_SLICE_PINNED_HOLD_DURATION:
3024 mSlicePinnedTimeoutMillis = properties.getLong(
3025 KEY_SLICE_PINNED_HOLD_DURATION,
3026 DEFAULT_SLICE_PINNED_TIMEOUT);
3027 break;
3028 case KEY_STRONG_USAGE_HOLD_DURATION:
3029 mStrongUsageTimeoutMillis = properties.getLong(
3030 KEY_STRONG_USAGE_HOLD_DURATION, DEFAULT_STRONG_USAGE_TIMEOUT);
3031 break;
3032 case KEY_PREDICTION_TIMEOUT:
3033 mPredictionTimeoutMillis = properties.getLong(
3034 KEY_PREDICTION_TIMEOUT, DEFAULT_PREDICTION_TIMEOUT);
3035 break;
3036 case KEY_SYSTEM_INTERACTION_HOLD_DURATION:
3037 mSystemInteractionTimeoutMillis = properties.getLong(
3038 KEY_SYSTEM_INTERACTION_HOLD_DURATION,
3039 DEFAULT_SYSTEM_INTERACTION_TIMEOUT);
3040 break;
3041 case KEY_SYSTEM_UPDATE_HOLD_DURATION:
3042 mSystemUpdateUsageTimeoutMillis = properties.getLong(
3043 KEY_SYSTEM_UPDATE_HOLD_DURATION, DEFAULT_SYSTEM_UPDATE_TIMEOUT);
3044 break;
3045 case KEY_SYNC_ADAPTER_HOLD_DURATION:
3046 mSyncAdapterTimeoutMillis = properties.getLong(
3047 KEY_SYNC_ADAPTER_HOLD_DURATION, DEFAULT_SYNC_ADAPTER_TIMEOUT);
3048 break;
3049 case KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION:
3050 mExemptedSyncScheduledDozeTimeoutMillis = properties.getLong(
3051 KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
3052 DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT);
3053 break;
3054 case KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION:
3055 mExemptedSyncScheduledNonDozeTimeoutMillis = properties.getLong(
3056 KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION,
3057 DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT);
3058 break;
3059 case KEY_EXEMPTED_SYNC_START_HOLD_DURATION:
3060 mExemptedSyncStartTimeoutMillis = properties.getLong(
3061 KEY_EXEMPTED_SYNC_START_HOLD_DURATION,
3062 DEFAULT_EXEMPTED_SYNC_START_TIMEOUT);
3063 break;
3064 case KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION:
3065 mUnexemptedSyncScheduledTimeoutMillis = properties.getLong(
3066 KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION,
3067 DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT);
3068 break;
3069 case KEY_BROADCAST_RESPONSE_WINDOW_DURATION_MS:
3070 mBroadcastResponseWindowDurationMillis = properties.getLong(
3071 KEY_BROADCAST_RESPONSE_WINDOW_DURATION_MS,
3072 DEFAULT_BROADCAST_RESPONSE_WINDOW_DURATION_MS);
3073 break;
3074 case KEY_BROADCAST_RESPONSE_FG_THRESHOLD_STATE:
3075 mBroadcastResponseFgThresholdState = properties.getInt(
3076 KEY_BROADCAST_RESPONSE_FG_THRESHOLD_STATE,
3077 DEFAULT_BROADCAST_RESPONSE_FG_THRESHOLD_STATE);
3078 break;
3079 case KEY_BROADCAST_SESSIONS_DURATION_MS:
3080 mBroadcastSessionsDurationMs = properties.getLong(
3081 KEY_BROADCAST_SESSIONS_DURATION_MS,
3082 DEFAULT_BROADCAST_SESSIONS_DURATION_MS);
3083 break;
3084 case KEY_BROADCAST_SESSIONS_WITH_RESPONSE_DURATION_MS:
3085 mBroadcastSessionsWithResponseDurationMs = properties.getLong(
3086 KEY_BROADCAST_SESSIONS_WITH_RESPONSE_DURATION_MS,
3087 DEFAULT_BROADCAST_SESSIONS_WITH_RESPONSE_DURATION_MS);
3088 break;
3089 case KEY_NOTE_RESPONSE_EVENT_FOR_ALL_BROADCAST_SESSIONS:
3090 mNoteResponseEventForAllBroadcastSessions = properties.getBoolean(
3091 KEY_NOTE_RESPONSE_EVENT_FOR_ALL_BROADCAST_SESSIONS,
3092 DEFAULT_NOTE_RESPONSE_EVENT_FOR_ALL_BROADCAST_SESSIONS);
3093 break;
3094 case KEY_BROADCAST_RESPONSE_EXEMPTED_ROLES:
3095 mBroadcastResponseExemptedRoles = properties.getString(
3096 KEY_BROADCAST_RESPONSE_EXEMPTED_ROLES,
3097 DEFAULT_BROADCAST_RESPONSE_EXEMPTED_ROLES);
3098 mBroadcastResponseExemptedRolesList = splitPipeSeparatedString(
3099 mBroadcastResponseExemptedRoles);
3100 break;
3101 case KEY_BROADCAST_RESPONSE_EXEMPTED_PERMISSIONS:
3102 mBroadcastResponseExemptedPermissions = properties.getString(
3103 KEY_BROADCAST_RESPONSE_EXEMPTED_PERMISSIONS,
3104 DEFAULT_BROADCAST_RESPONSE_EXEMPTED_PERMISSIONS);
3105 mBroadcastResponseExemptedPermissionsList = splitPipeSeparatedString(
3106 mBroadcastResponseExemptedPermissions);
3107 break;
3108 default:
3109 if (!timeThresholdsUpdated
3110 && (name.startsWith(KEY_PREFIX_SCREEN_TIME_THRESHOLD)
3111 || name.startsWith(KEY_PREFIX_ELAPSED_TIME_THRESHOLD))) {
3112 updateTimeThresholds();
3113 timeThresholdsUpdated = true;
3114 }
3115 break;
3116 }
3117 mAppStandbyProperties.put(name, properties.getString(name, null));
3118 }
3119 }
3120 }
3121
3122 private List<String> splitPipeSeparatedString(String string) {
3123 final List<String> values = new ArrayList<>();
3124 mStringPipeSplitter.setString(string);
3125 while (mStringPipeSplitter.hasNext()) {
3126 values.add(mStringPipeSplitter.next());
3127 }
3128 return values;
3129 }
3130
3131 private void updateTimeThresholds() {
3132 // Query the values as an atomic set.
3133 final DeviceConfig.Properties screenThresholdProperties =
3134 mInjector.getDeviceConfigProperties(KEYS_SCREEN_TIME_THRESHOLDS);
3135 final DeviceConfig.Properties elapsedThresholdProperties =
3136 mInjector.getDeviceConfigProperties(KEYS_ELAPSED_TIME_THRESHOLDS);
3137 mAppStandbyScreenThresholds = generateThresholdArray(
3138 screenThresholdProperties, KEYS_SCREEN_TIME_THRESHOLDS,
3139 DEFAULT_SCREEN_TIME_THRESHOLDS, MINIMUM_SCREEN_TIME_THRESHOLDS);
3140 mAppStandbyElapsedThresholds = generateThresholdArray(
3141 elapsedThresholdProperties, KEYS_ELAPSED_TIME_THRESHOLDS,
3142 DEFAULT_ELAPSED_TIME_THRESHOLDS, MINIMUM_ELAPSED_TIME_THRESHOLDS);
3143 mCheckIdleIntervalMillis = Math.min(mAppStandbyElapsedThresholds[1] / 4,
3144 DEFAULT_CHECK_IDLE_INTERVAL_MS);
3145 }
3146
3147 void updateSettings() {
3148 if (DEBUG) {
3149 Slog.d(TAG,
3150 "appidle=" + Global.getString(mContext.getContentResolver(),
3151 Global.APP_STANDBY_ENABLED));
3152 Slog.d(TAG,
3153 "adaptivebat=" + Global.getString(mContext.getContentResolver(),
3154 Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED));
3155 }
3156
3157 synchronized (mAppIdleLock) {
3158 mAllowRestrictedBucket = mInjector.isRestrictedBucketEnabled();
3159 }
3160
3161 setAppIdleEnabled(mInjector.isAppIdleEnabled());
3162 }
3163
3164 long[] generateThresholdArray(@NonNull DeviceConfig.Properties properties,
3165 @NonNull String[] keys, long[] defaults, long[] minValues) {
3166 if (properties.getKeyset().isEmpty()) {
3167 // Reset to defaults
3168 return defaults;
3169 }
3170 if (keys.length != THRESHOLD_BUCKETS.length) {
3171 // This should only happen in development.
3172 throw new IllegalStateException(
3173 "# keys (" + keys.length + ") != # buckets ("
3174 + THRESHOLD_BUCKETS.length + ")");
3175 }
3176 if (defaults.length != THRESHOLD_BUCKETS.length) {
3177 // This should only happen in development.
3178 throw new IllegalStateException(
3179 "# defaults (" + defaults.length + ") != # buckets ("
3180 + THRESHOLD_BUCKETS.length + ")");
3181 }
3182 if (minValues.length != THRESHOLD_BUCKETS.length) {
3183 Slog.wtf(TAG, "minValues array is the wrong size");
3184 // Use zeroes as the minimums.
3185 minValues = new long[THRESHOLD_BUCKETS.length];
3186 }
3187 long[] array = new long[THRESHOLD_BUCKETS.length];
3188 for (int i = 0; i < THRESHOLD_BUCKETS.length; i++) {
3189 array[i] = Math.max(minValues[i], properties.getLong(keys[i], defaults[i]));
3190 }
3191 return array;
3192 }
3193 }
3194 }