• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.am;
18 
19 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED;
20 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE;
21 
22 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER_QUICK;
23 
24 import android.app.ActivityThread;
25 import android.content.ComponentName;
26 import android.content.ContentResolver;
27 import android.content.Context;
28 import android.database.ContentObserver;
29 import android.net.Uri;
30 import android.os.Build;
31 import android.os.Handler;
32 import android.os.Message;
33 import android.os.PowerExemptionManager;
34 import android.provider.DeviceConfig;
35 import android.provider.DeviceConfig.OnPropertiesChangedListener;
36 import android.provider.DeviceConfig.Properties;
37 import android.provider.Settings;
38 import android.text.TextUtils;
39 import android.util.ArraySet;
40 import android.util.KeyValueListParser;
41 import android.util.Slog;
42 
43 import java.io.PrintWriter;
44 import java.util.Arrays;
45 import java.util.List;
46 import java.util.stream.Collectors;
47 
48 /**
49  * Settings constants that can modify the activity manager's behavior.
50  */
51 final class ActivityManagerConstants extends ContentObserver {
52     private static final String TAG = "ActivityManagerConstants";
53 
54     // Key names stored in the settings value.
55     private static final String KEY_BACKGROUND_SETTLE_TIME = "background_settle_time";
56     private static final String KEY_FGSERVICE_MIN_SHOWN_TIME
57             = "fgservice_min_shown_time";
58     private static final String KEY_FGSERVICE_MIN_REPORT_TIME
59             = "fgservice_min_report_time";
60     private static final String KEY_FGSERVICE_SCREEN_ON_BEFORE_TIME
61             = "fgservice_screen_on_before_time";
62     private static final String KEY_FGSERVICE_SCREEN_ON_AFTER_TIME
63             = "fgservice_screen_on_after_time";
64     private static final String KEY_CONTENT_PROVIDER_RETAIN_TIME = "content_provider_retain_time";
65     private static final String KEY_GC_TIMEOUT = "gc_timeout";
66     private static final String KEY_GC_MIN_INTERVAL = "gc_min_interval";
67     private static final String KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS =
68             "force_bg_check_on_restricted";
69     private static final String KEY_FULL_PSS_MIN_INTERVAL = "full_pss_min_interval";
70     private static final String KEY_FULL_PSS_LOWERED_INTERVAL = "full_pss_lowered_interval";
71     private static final String KEY_POWER_CHECK_INTERVAL = "power_check_interval";
72     private static final String KEY_POWER_CHECK_MAX_CPU_1 = "power_check_max_cpu_1";
73     private static final String KEY_POWER_CHECK_MAX_CPU_2 = "power_check_max_cpu_2";
74     private static final String KEY_POWER_CHECK_MAX_CPU_3 = "power_check_max_cpu_3";
75     private static final String KEY_POWER_CHECK_MAX_CPU_4 = "power_check_max_cpu_4";
76     /** Used for all apps on R and earlier versions. */
77     private static final String KEY_SERVICE_USAGE_INTERACTION_TIME_PRE_S =
78             "service_usage_interaction_time";
79     private static final String KEY_SERVICE_USAGE_INTERACTION_TIME_POST_S =
80             "service_usage_interaction_time_post_s";
81     /** Used for all apps on R and earlier versions. */
82     private static final String KEY_USAGE_STATS_INTERACTION_INTERVAL_PRE_S =
83             "usage_stats_interaction_interval";
84     private static final String KEY_USAGE_STATS_INTERACTION_INTERVAL_POST_S =
85             "usage_stats_interaction_interval_post_s";
86     private static final String KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES =
87             "imperceptible_kill_exempt_packages";
88     private static final String KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES =
89             "imperceptible_kill_exempt_proc_states";
90     static final String KEY_SERVICE_RESTART_DURATION = "service_restart_duration";
91     static final String KEY_SERVICE_RESET_RUN_DURATION = "service_reset_run_duration";
92     static final String KEY_SERVICE_RESTART_DURATION_FACTOR = "service_restart_duration_factor";
93     static final String KEY_SERVICE_MIN_RESTART_TIME_BETWEEN = "service_min_restart_time_between";
94     static final String KEY_MAX_SERVICE_INACTIVITY = "service_max_inactivity";
95     static final String KEY_BG_START_TIMEOUT = "service_bg_start_timeout";
96     static final String KEY_SERVICE_BG_ACTIVITY_START_TIMEOUT = "service_bg_activity_start_timeout";
97     static final String KEY_BOUND_SERVICE_CRASH_RESTART_DURATION = "service_crash_restart_duration";
98     static final String KEY_BOUND_SERVICE_CRASH_MAX_RETRY = "service_crash_max_retry";
99     static final String KEY_PROCESS_START_ASYNC = "process_start_async";
100     static final String KEY_MEMORY_INFO_THROTTLE_TIME = "memory_info_throttle_time";
101     static final String KEY_TOP_TO_FGS_GRACE_DURATION = "top_to_fgs_grace_duration";
102     static final String KEY_PENDINGINTENT_WARNING_THRESHOLD = "pendingintent_warning_threshold";
103     static final String KEY_MIN_CRASH_INTERVAL = "min_crash_interval";
104     static final String KEY_PROCESS_CRASH_COUNT_RESET_INTERVAL =
105             "process_crash_count_reset_interval";
106     static final String KEY_PROCESS_CRASH_COUNT_LIMIT = "process_crash_count_limit";
107     static final String KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION = "boot_time_temp_allowlist_duration";
108     static final String KEY_FG_TO_BG_FGS_GRACE_DURATION = "fg_to_bg_fgs_grace_duration";
109     static final String KEY_FGS_START_FOREGROUND_TIMEOUT = "fgs_start_foreground_timeout";
110     static final String KEY_FGS_ATOM_SAMPLE_RATE = "fgs_atom_sample_rate";
111     static final String KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE = "fgs_start_allowed_log_sample_rate";
112     static final String KEY_FGS_START_DENIED_LOG_SAMPLE_RATE = "fgs_start_denied_log_sample_rate";
113     static final String KEY_FGS_ALLOW_OPT_OUT = "fgs_allow_opt_out";
114 
115     private static final int DEFAULT_MAX_CACHED_PROCESSES = 32;
116     private static final long DEFAULT_BACKGROUND_SETTLE_TIME = 60*1000;
117     private static final long DEFAULT_FGSERVICE_MIN_SHOWN_TIME = 2*1000;
118     private static final long DEFAULT_FGSERVICE_MIN_REPORT_TIME = 3*1000;
119     private static final long DEFAULT_FGSERVICE_SCREEN_ON_BEFORE_TIME = 1*1000;
120     private static final long DEFAULT_FGSERVICE_SCREEN_ON_AFTER_TIME = 5*1000;
121     private static final long DEFAULT_CONTENT_PROVIDER_RETAIN_TIME = 20*1000;
122     private static final long DEFAULT_GC_TIMEOUT = 5*1000;
123     private static final long DEFAULT_GC_MIN_INTERVAL = 60*1000;
124     private static final long DEFAULT_FULL_PSS_MIN_INTERVAL = 20*60*1000;
125     private static final boolean DEFAULT_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS = true;
126     private static final long DEFAULT_FULL_PSS_LOWERED_INTERVAL = 5*60*1000;
127     private static final long DEFAULT_POWER_CHECK_INTERVAL = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
128     private static final int DEFAULT_POWER_CHECK_MAX_CPU_1 = 25;
129     private static final int DEFAULT_POWER_CHECK_MAX_CPU_2 = 25;
130     private static final int DEFAULT_POWER_CHECK_MAX_CPU_3 = 10;
131     private static final int DEFAULT_POWER_CHECK_MAX_CPU_4 = 2;
132     private static final long DEFAULT_SERVICE_USAGE_INTERACTION_TIME_PRE_S = 30 * 60 * 1000;
133     private static final long DEFAULT_SERVICE_USAGE_INTERACTION_TIME_POST_S = 60 * 1000;
134     private static final long DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_PRE_S = 2 * 60 * 60 * 1000;
135     private static final long DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_POST_S = 10 * 60 * 1000;
136     private static final long DEFAULT_SERVICE_RESTART_DURATION = 1*1000;
137     private static final long DEFAULT_SERVICE_RESET_RUN_DURATION = 60*1000;
138     private static final int DEFAULT_SERVICE_RESTART_DURATION_FACTOR = 4;
139     private static final long DEFAULT_SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
140     private static final long DEFAULT_MAX_SERVICE_INACTIVITY = 30*60*1000;
141     private static final long DEFAULT_BG_START_TIMEOUT = 15*1000;
142     private static final long DEFAULT_SERVICE_BG_ACTIVITY_START_TIMEOUT = 10_000;
143     private static final long DEFAULT_BOUND_SERVICE_CRASH_RESTART_DURATION = 30*60_000;
144     private static final int DEFAULT_BOUND_SERVICE_CRASH_MAX_RETRY = 16;
145     private static final boolean DEFAULT_PROCESS_START_ASYNC = true;
146     private static final long DEFAULT_MEMORY_INFO_THROTTLE_TIME = 5*60*1000;
147     private static final long DEFAULT_TOP_TO_FGS_GRACE_DURATION = 15 * 1000;
148     private static final int DEFAULT_PENDINGINTENT_WARNING_THRESHOLD = 2000;
149     private static final int DEFAULT_MIN_CRASH_INTERVAL = 2 * 60 * 1000;
150     private static final int DEFAULT_MAX_PHANTOM_PROCESSES = 32;
151     private static final int DEFAULT_PROCESS_CRASH_COUNT_RESET_INTERVAL = 12 * 60 * 60 * 1000;
152     private static final int DEFAULT_PROCESS_CRASH_COUNT_LIMIT = 12;
153     private static final int DEFAULT_BOOT_TIME_TEMP_ALLOWLIST_DURATION = 20 * 1000;
154     private static final long DEFAULT_FG_TO_BG_FGS_GRACE_DURATION = 5 * 1000;
155     private static final int DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS = 10 * 1000;
156     private static final float DEFAULT_FGS_ATOM_SAMPLE_RATE = 1; // 100 %
157     private static final float DEFAULT_FGS_START_ALLOWED_LOG_SAMPLE_RATE = 0.25f; // 25%
158     private static final float DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE = 1; // 100%
159     /**
160      * Same as {@link TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED}
161      */
162     private static final int
163             DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR = 1;
164     private static final boolean DEFAULT_FGS_ALLOW_OPT_OUT = false;
165 
166     // Flag stored in the DeviceConfig API.
167     /**
168      * Maximum number of cached processes.
169      */
170     private static final String KEY_MAX_CACHED_PROCESSES = "max_cached_processes";
171 
172     /**
173      * Maximum number of cached processes.
174      */
175     private static final String KEY_MAX_PHANTOM_PROCESSES = "max_phantom_processes";
176 
177     /**
178      * Default value for mFlagBackgroundActivityStartsEnabled if not explicitly set in
179      * Settings.Global. This allows it to be set experimentally unless it has been
180      * enabled/disabled in developer options. Defaults to false.
181      */
182     private static final String KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED =
183             "default_background_activity_starts_enabled";
184 
185     /**
186      * Default value for mFlagBackgroundFgsStartRestrictionEnabled if not explicitly set in
187      * Settings.Global.
188      */
189     private static final String KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED =
190             "default_background_fgs_starts_restriction_enabled";
191 
192     /**
193      * Default value for mFlagFgsStartRestrictionEnabled if not explicitly set in
194      * Settings.Global.
195      */
196     private static final String KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED =
197             "default_fgs_starts_restriction_enabled";
198 
199     /**
200      * Default value for mFgsStartRestrictionNotificationEnabled if not explicitly set in
201      * Settings.Global.
202      */
203     private static final String KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED =
204             "default_fgs_starts_restriction_notification_enabled";
205 
206     /**
207      * Default value for mFgsStartRestrictionCheckCallerTargetSdk if not explicitly set in
208      * Settings.Global.
209      */
210     private static final String KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK =
211             "default_fgs_starts_restriction_check_caller_target_sdk";
212 
213     /**
214      * Whether FGS notification display is deferred following the transition into
215      * the foreground state.  Default behavior is {@code true} unless overridden.
216      */
217     private static final String KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED =
218             "deferred_fgs_notifications_enabled";
219 
220     /** Whether FGS notification deferral applies only to those apps targeting
221      * API version S or higher.  Default is {@code true} unless overidden.
222      */
223     private static final String KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED =
224             "deferred_fgs_notifications_api_gated";
225 
226     /**
227      * Time in milliseconds to defer display of FGS notifications following the
228      * transition into the foreground state.  Default is 10_000 (ten seconds)
229      * unless overridden.
230      */
231     private static final String KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL =
232             "deferred_fgs_notification_interval";
233 
234     /**
235      * Time in milliseconds; once an FGS notification for a given uid has been
236      * deferred, no subsequent FGS notification from that uid will be deferred
237      * until this amount of time has passed.  Default is two minutes
238      * (2 * 60 * 1000) unless overridden.
239      */
240     private static final String KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME =
241             "deferred_fgs_notification_exclusion_time";
242 
243     /**
244      * Default value for mPushMessagingOverQuotaBehavior if not explicitly set in
245      * Settings.Global.
246      */
247     private static final String KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR =
248             "push_messaging_over_quota_behavior";
249 
250     // Maximum number of cached processes we will allow.
251     public int MAX_CACHED_PROCESSES = DEFAULT_MAX_CACHED_PROCESSES;
252 
253     // This is the amount of time we allow an app to settle after it goes into the background,
254     // before we start restricting what it can do.
255     public long BACKGROUND_SETTLE_TIME = DEFAULT_BACKGROUND_SETTLE_TIME;
256 
257     // The minimum time we allow a foreground service to run with a notification and the
258     // screen on without otherwise telling the user about it.  (If it runs for less than this,
259     // it will still be reported to the user as a running app for at least this amount of time.)
260     public long FGSERVICE_MIN_SHOWN_TIME = DEFAULT_FGSERVICE_MIN_SHOWN_TIME;
261 
262     // If a foreground service is shown for less than FGSERVICE_MIN_SHOWN_TIME, we will display
263     // the background app running notification about it for at least this amount of time (if it
264     // is larger than the remaining shown time).
265     public long FGSERVICE_MIN_REPORT_TIME = DEFAULT_FGSERVICE_MIN_REPORT_TIME;
266 
267     // The minimum amount of time the foreground service needs to have remain being shown
268     // before the screen goes on for us to consider it not worth showing to the user.  That is
269     // if an app has a foreground service that stops itself this amount of time or more before
270     // the user turns on the screen, we will just let it go without the user being told about it.
271     public long FGSERVICE_SCREEN_ON_BEFORE_TIME = DEFAULT_FGSERVICE_SCREEN_ON_BEFORE_TIME;
272 
273     // The minimum amount of time a foreground service should remain reported to the user if
274     // it is stopped when the screen turns on.  This is the time from when the screen turns
275     // on until we will stop reporting it.
276     public long FGSERVICE_SCREEN_ON_AFTER_TIME = DEFAULT_FGSERVICE_SCREEN_ON_AFTER_TIME;
277 
278     // How long we will retain processes hosting content providers in the "last activity"
279     // state before allowing them to drop down to the regular cached LRU list.  This is
280     // to avoid thrashing of provider processes under low memory situations.
281     long CONTENT_PROVIDER_RETAIN_TIME = DEFAULT_CONTENT_PROVIDER_RETAIN_TIME;
282 
283     // How long to wait after going idle before forcing apps to GC.
284     long GC_TIMEOUT = DEFAULT_GC_TIMEOUT;
285 
286     // The minimum amount of time between successive GC requests for a process.
287     long GC_MIN_INTERVAL = DEFAULT_GC_MIN_INTERVAL;
288 
289     /**
290      * Whether or not Background Check should be forced on any apps in the
291      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RESTRICTED} bucket,
292      * regardless of target SDK version.
293      */
294     boolean FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS =
295             DEFAULT_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS;
296 
297     // The minimum amount of time between successive PSS requests for a process.
298     long FULL_PSS_MIN_INTERVAL = DEFAULT_FULL_PSS_MIN_INTERVAL;
299 
300     // The minimum amount of time between successive PSS requests for a process
301     // when the request is due to the memory state being lowered.
302     long FULL_PSS_LOWERED_INTERVAL = DEFAULT_FULL_PSS_LOWERED_INTERVAL;
303 
304     // The minimum sample duration we will allow before deciding we have
305     // enough data on CPU usage to start killing things.
306     long POWER_CHECK_INTERVAL = DEFAULT_POWER_CHECK_INTERVAL;
307 
308     // The maximum CPU (as a percentage) a process is allowed to use over the first
309     // power check interval that it is cached.
310     int POWER_CHECK_MAX_CPU_1 = DEFAULT_POWER_CHECK_MAX_CPU_1;
311 
312     // The maximum CPU (as a percentage) a process is allowed to use over the second
313     // power check interval that it is cached.  The home app will never check for less
314     // CPU than this (it will not test against the 3 or 4 levels).
315     int POWER_CHECK_MAX_CPU_2 = DEFAULT_POWER_CHECK_MAX_CPU_2;
316 
317     // The maximum CPU (as a percentage) a process is allowed to use over the third
318     // power check interval that it is cached.
319     int POWER_CHECK_MAX_CPU_3 = DEFAULT_POWER_CHECK_MAX_CPU_3;
320 
321     // The maximum CPU (as a percentage) a process is allowed to use over the fourth
322     // power check interval that it is cached.
323     int POWER_CHECK_MAX_CPU_4 = DEFAULT_POWER_CHECK_MAX_CPU_4;
324 
325     // This is the amount of time an app needs to be running a foreground service before
326     // we will consider it to be doing interaction for usage stats.
327     // Only used for apps targeting pre-S versions.
328     long SERVICE_USAGE_INTERACTION_TIME_PRE_S = DEFAULT_SERVICE_USAGE_INTERACTION_TIME_PRE_S;
329 
330     // This is the amount of time an app needs to be running a foreground service before
331     // we will consider it to be doing interaction for usage stats.
332     // Only used for apps targeting versions S and above.
333     long SERVICE_USAGE_INTERACTION_TIME_POST_S = DEFAULT_SERVICE_USAGE_INTERACTION_TIME_POST_S;
334 
335     // Maximum amount of time we will allow to elapse before re-reporting usage stats
336     // interaction with foreground processes.
337     // Only used for apps targeting pre-S versions.
338     long USAGE_STATS_INTERACTION_INTERVAL_PRE_S = DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_PRE_S;
339 
340     // Maximum amount of time we will allow to elapse before re-reporting usage stats
341     // interaction with foreground processes.
342     // Only used for apps targeting versions S and above.
343     long USAGE_STATS_INTERACTION_INTERVAL_POST_S = DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_POST_S;
344 
345     // How long a service needs to be running until restarting its process
346     // is no longer considered to be a relaunch of the service.
347     public long SERVICE_RESTART_DURATION = DEFAULT_SERVICE_RESTART_DURATION;
348 
349     // How long a service needs to be running until it will start back at
350     // SERVICE_RESTART_DURATION after being killed.
351     public long SERVICE_RESET_RUN_DURATION = DEFAULT_SERVICE_RESET_RUN_DURATION;
352 
353     // Multiplying factor to increase restart duration time by, for each time
354     // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
355     public int SERVICE_RESTART_DURATION_FACTOR = DEFAULT_SERVICE_RESTART_DURATION_FACTOR;
356 
357     // The minimum amount of time between restarting services that we allow.
358     // That is, when multiple services are restarting, we won't allow each
359     // to restart less than this amount of time from the last one.
360     public long SERVICE_MIN_RESTART_TIME_BETWEEN = DEFAULT_SERVICE_MIN_RESTART_TIME_BETWEEN;
361 
362     // Maximum amount of time for there to be no activity on a service before
363     // we consider it non-essential and allow its process to go on the
364     // LRU background list.
365     public long MAX_SERVICE_INACTIVITY = DEFAULT_MAX_SERVICE_INACTIVITY;
366 
367     // How long we wait for a background started service to stop itself before
368     // allowing the next pending start to run.
369     public long BG_START_TIMEOUT = DEFAULT_BG_START_TIMEOUT;
370 
371     // For a service that has been allowed to start background activities, how long after it started
372     // its process can start a background activity.
373     public long SERVICE_BG_ACTIVITY_START_TIMEOUT = DEFAULT_SERVICE_BG_ACTIVITY_START_TIMEOUT;
374 
375     // Initial backoff delay for retrying bound foreground services
376     public long BOUND_SERVICE_CRASH_RESTART_DURATION = DEFAULT_BOUND_SERVICE_CRASH_RESTART_DURATION;
377 
378     // Maximum number of retries for bound foreground services that crash soon after start
379     public long BOUND_SERVICE_MAX_CRASH_RETRY = DEFAULT_BOUND_SERVICE_CRASH_MAX_RETRY;
380 
381     // Indicates if the processes need to be started asynchronously.
382     public boolean FLAG_PROCESS_START_ASYNC = DEFAULT_PROCESS_START_ASYNC;
383 
384     // The minimum time we allow between requests for the MemoryInfo of a process to
385     // throttle requests from apps.
386     public long MEMORY_INFO_THROTTLE_TIME = DEFAULT_MEMORY_INFO_THROTTLE_TIME;
387 
388     // Allow app just moving from TOP to FOREGROUND_SERVICE to stay in a higher adj value for
389     // this long.
390     public long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION;
391 
392     /**
393      * The minimum time we allow between crashes, for us to consider this
394      * application to be bad and stop its services and reject broadcasts.
395      * A reasonable interval here would be anything between 1-3 minutes.
396      */
397     public static int MIN_CRASH_INTERVAL = DEFAULT_MIN_CRASH_INTERVAL;
398 
399     /**
400      * We will allow for a maximum number of {@link PROCESS_CRASH_COUNT_LIMIT} crashes within this
401      * time period before we consider the application to be bad and stop services and reject
402      * broadcasts.
403      * A reasonable reset interval here would be anything between 10-20 hours along with a crash
404      * count limit of 10-20 crashes.
405      */
406     static long PROCESS_CRASH_COUNT_RESET_INTERVAL = DEFAULT_PROCESS_CRASH_COUNT_RESET_INTERVAL;
407 
408     /**
409      * The maximum number of crashes allowed within {@link PROCESS_CRASH_COUNT_RESET_INTERVAL_MS}
410      * before we consider the application to be bad and stop services and reject broadcasts.
411      * A reasonable crash count limit here would be anything between 10-20 crashes along with a
412      * reset interval of 10-20 hours.
413      */
414     static int PROCESS_CRASH_COUNT_LIMIT = DEFAULT_PROCESS_CRASH_COUNT_LIMIT;
415 
416     // Indicates whether the activity starts logging is enabled.
417     // Controlled by Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED
418     volatile boolean mFlagActivityStartsLoggingEnabled;
419 
420     // Indicates whether the background activity starts is enabled.
421     // Controlled by Settings.Global.BACKGROUND_ACTIVITY_STARTS_ENABLED.
422     // If not set explicitly the default is controlled by DeviceConfig.
423     volatile boolean mFlagBackgroundActivityStartsEnabled;
424 
425     // Indicates whether foreground service starts logging is enabled.
426     // Controlled by Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED
427     volatile boolean mFlagForegroundServiceStartsLoggingEnabled;
428 
429     // Indicates whether the foreground service background start restriction is enabled.
430     // When the restriction is enabled, foreground service started from background will not have
431     // while-in-use permissions like location, camera and microphone. (The foreground service can be
432     // started, the restriction is on while-in-use permissions.)
433     volatile boolean mFlagBackgroundFgsStartRestrictionEnabled = true;
434 
435     // Indicates whether the foreground service background start restriction is enabled for
436     // apps targeting S+.
437     // When the restriction is enabled, service is not allowed to startForeground from background
438     // at all.
439     volatile boolean mFlagFgsStartRestrictionEnabled = true;
440 
441     // Whether to display a notification when a service is restricted from startForeground due to
442     // foreground service background start restriction.
443     volatile boolean mFgsStartRestrictionNotificationEnabled = false;
444 
445     /**
446      * Indicates whether the foreground service background start restriction is enabled for
447      * caller app that is targeting S+.
448      * This is in addition to check of {@link #mFlagFgsStartRestrictionEnabled} flag.
449      */
450     volatile boolean mFgsStartRestrictionCheckCallerTargetSdk = true;
451 
452     // Whether we defer FGS notifications a few seconds following their transition to
453     // the foreground state.  Applies only to S+ apps; enabled by default.
454     volatile boolean mFlagFgsNotificationDeferralEnabled = true;
455 
456     // Restrict FGS notification deferral policy to only those apps that target
457     // API version S or higher.  Disabled by default; set to "true" to force
458     // legacy app FGS notifications to display immediately in all cases.
459     volatile boolean mFlagFgsNotificationDeferralApiGated = false;
460 
461     // Time in milliseconds to defer FGS notifications after their transition to
462     // the foreground state.
463     volatile long mFgsNotificationDeferralInterval = 10_000;
464 
465     // Rate limit: minimum time after an app's FGS notification is deferred
466     // before another FGS notification from that app can be deferred.
467     volatile long mFgsNotificationDeferralExclusionTime = 2 * 60 * 1000L;
468 
469     /**
470      * When server pushing message is over the quote, select one of the temp allow list type as
471      * defined in {@link PowerExemptionManager.TempAllowListType}
472      */
473     volatile @PowerExemptionManager.TempAllowListType int mPushMessagingOverQuotaBehavior =
474             DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR;
475 
476     /*
477      * At boot time, broadcast receiver ACTION_BOOT_COMPLETED, ACTION_LOCKED_BOOT_COMPLETED and
478      * ACTION_PRE_BOOT_COMPLETED are temp allowlisted to start FGS for a duration of time in
479      * milliseconds.
480      */
481     volatile long mBootTimeTempAllowlistDuration = DEFAULT_BOOT_TIME_TEMP_ALLOWLIST_DURATION;
482 
483     /**
484      * The grace period in milliseconds to allow a process to start FGS from background after
485      * switching from foreground to background; currently it's only applicable to its activities.
486      */
487     volatile long mFgToBgFgsGraceDuration = DEFAULT_FG_TO_BG_FGS_GRACE_DURATION;
488 
489     /**
490      * When service started from background, before the timeout it can be promoted to FGS by calling
491      * Service.startForeground().
492      */
493     volatile long mFgsStartForegroundTimeoutMs = DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS;
494 
495     /**
496      * Sample rate for the FGS atom.
497      *
498      * If the value is 0.1, 10% of the installed packages would be sampled.
499      */
500     volatile float mFgsAtomSampleRate = DEFAULT_FGS_ATOM_SAMPLE_RATE;
501 
502     /**
503      * Sample rate for the allowed FGS start WTF logs.
504      *
505      * If the value is 0.1, 10% of the logs would be sampled.
506      */
507     volatile float mFgsStartAllowedLogSampleRate = DEFAULT_FGS_START_ALLOWED_LOG_SAMPLE_RATE;
508 
509     /**
510      * Sample rate for the denied FGS start WTF logs.
511      *
512      * If the value is 0.1, 10% of the logs would be sampled.
513      */
514     volatile float mFgsStartDeniedLogSampleRate = DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE;
515 
516     /**
517      * Whether to allow "opt-out" from the foreground service restrictions.
518      * (https://developer.android.com/about/versions/12/foreground-services)
519      */
520     volatile boolean mFgsAllowOptOut = DEFAULT_FGS_ALLOW_OPT_OUT;
521 
522     private final ActivityManagerService mService;
523     private ContentResolver mResolver;
524     private final KeyValueListParser mParser = new KeyValueListParser(',');
525 
526     private int mOverrideMaxCachedProcesses = -1;
527     private final int mCustomizedMaxCachedProcesses;
528 
529     // The maximum number of cached processes we will keep around before killing them.
530     // NOTE: this constant is *only* a control to not let us go too crazy with
531     // keeping around processes on devices with large amounts of RAM.  For devices that
532     // are tighter on RAM, the out of memory killer is responsible for killing background
533     // processes as RAM is needed, and we should *never* be relying on this limit to
534     // kill them.  Also note that this limit only applies to cached background processes;
535     // we have no limit on the number of service, visible, foreground, or other such
536     // processes and the number of those processes does not count against the cached
537     // process limit. This will be initialized in the constructor.
538     public int CUR_MAX_CACHED_PROCESSES;
539 
540     // The maximum number of empty app processes we will let sit around.  This will be
541     // initialized in the constructor.
542     public int CUR_MAX_EMPTY_PROCESSES;
543 
544     // The number of empty apps at which we don't consider it necessary to do
545     // memory trimming.
546     public int CUR_TRIM_EMPTY_PROCESSES = computeEmptyProcessLimit(MAX_CACHED_PROCESSES) / 2;
547 
548     // The number of cached at which we don't consider it necessary to do
549     // memory trimming.
550     public int CUR_TRIM_CACHED_PROCESSES =
551             (MAX_CACHED_PROCESSES - computeEmptyProcessLimit(MAX_CACHED_PROCESSES)) / 3;
552 
553     /**
554      * Packages that can't be killed even if it's requested to be killed on imperceptible.
555      */
556     public ArraySet<String> IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES = new ArraySet<String>();
557 
558     /**
559      * Proc State that can't be killed even if it's requested to be killed on imperceptible.
560      */
561     public ArraySet<Integer> IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES = new ArraySet<Integer>();
562 
563     /**
564      * The threshold for the amount of PendingIntent for each UID, there will be
565      * warning logs if the number goes beyond this threshold.
566      */
567     public int PENDINGINTENT_WARNING_THRESHOLD =  DEFAULT_PENDINGINTENT_WARNING_THRESHOLD;
568 
569     /**
570      * Component names of the services which will keep critical code path of the host warm
571      */
572     public final ArraySet<ComponentName> KEEP_WARMING_SERVICES = new ArraySet<ComponentName>();
573 
574     /**
575      * Maximum number of phantom processes.
576      */
577     public int MAX_PHANTOM_PROCESSES = DEFAULT_MAX_PHANTOM_PROCESSES;
578 
579     private List<String> mDefaultImperceptibleKillExemptPackages;
580     private List<Integer> mDefaultImperceptibleKillExemptProcStates;
581 
582     @SuppressWarnings("unused")
583     private static final int OOMADJ_UPDATE_POLICY_SLOW = 0;
584     private static final int OOMADJ_UPDATE_POLICY_QUICK = 1;
585     private static final int DEFAULT_OOMADJ_UPDATE_POLICY = OOMADJ_UPDATE_POLICY_QUICK;
586 
587     private static final String KEY_OOMADJ_UPDATE_POLICY = "oomadj_update_policy";
588 
589     // Indicate if the oom adjuster should take the quick path to update the oom adj scores,
590     // in which no futher actions will be performed if there are no significant adj/proc state
591     // changes for the specific process; otherwise, use the traditonal slow path which would
592     // keep updating all processes in the LRU list.
593     public boolean OOMADJ_UPDATE_QUICK = DEFAULT_OOMADJ_UPDATE_POLICY == OOMADJ_UPDATE_POLICY_QUICK;
594 
595     private static final long MIN_AUTOMATIC_HEAP_DUMP_PSS_THRESHOLD_BYTES = 100 * 1024; // 100 KB
596 
597     private final boolean mSystemServerAutomaticHeapDumpEnabled;
598 
599     /** Package to report to when the memory usage exceeds the limit. */
600     private final String mSystemServerAutomaticHeapDumpPackageName;
601 
602     /** Byte limit for dump heap monitoring. */
603     private long mSystemServerAutomaticHeapDumpPssThresholdBytes;
604 
605     private static final Uri ACTIVITY_MANAGER_CONSTANTS_URI = Settings.Global.getUriFor(
606                 Settings.Global.ACTIVITY_MANAGER_CONSTANTS);
607 
608     private static final Uri ACTIVITY_STARTS_LOGGING_ENABLED_URI = Settings.Global.getUriFor(
609                 Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED);
610 
611     private static final Uri FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI =
612                 Settings.Global.getUriFor(
613                         Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED);
614 
615     private static final Uri ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI =
616             Settings.Global.getUriFor(Settings.Global.ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS);
617 
618     /**
619      * The threshold to decide if a given association should be dumped into metrics.
620      */
621     private static final long DEFAULT_MIN_ASSOC_LOG_DURATION = 5 * 60 * 1000; // 5 mins
622 
623     private static final String KEY_MIN_ASSOC_LOG_DURATION = "min_assoc_log_duration";
624 
625     public static long MIN_ASSOC_LOG_DURATION = DEFAULT_MIN_ASSOC_LOG_DURATION;
626 
627     private static final String KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED =
628             "binder_heavy_hitter_watcher_enabled";
629     private static final String KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE =
630             "binder_heavy_hitter_watcher_batchsize";
631     private static final String KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD =
632             "binder_heavy_hitter_watcher_threshold";
633     private static final String KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED =
634             "binder_heavy_hitter_auto_sampler_enabled";
635     private static final String KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE =
636             "binder_heavy_hitter_auto_sampler_batchsize";
637     private static final String KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD =
638             "binder_heavy_hitter_auto_sampler_threshold";
639 
640     private final boolean mDefaultBinderHeavyHitterWatcherEnabled;
641     private final int mDefaultBinderHeavyHitterWatcherBatchSize;
642     private final float mDefaultBinderHeavyHitterWatcherThreshold;
643     private final boolean mDefaultBinderHeavyHitterAutoSamplerEnabled;
644     private final int mDefaultBinderHeavyHitterAutoSamplerBatchSize;
645     private final float mDefaultBinderHeavyHitterAutoSamplerThreshold;
646 
647     public static boolean BINDER_HEAVY_HITTER_WATCHER_ENABLED;
648     public static int BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE;
649     public static float BINDER_HEAVY_HITTER_WATCHER_THRESHOLD;
650     public static boolean BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED;
651     public static int BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
652     public static float BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
653 
654     private final OnPropertiesChangedListener mOnDeviceConfigChangedListener =
655             new OnPropertiesChangedListener() {
656                 @Override
657                 public void onPropertiesChanged(Properties properties) {
658                     for (String name : properties.getKeyset()) {
659                         if (name == null) {
660                             return;
661                         }
662                         switch (name) {
663                             case KEY_MAX_CACHED_PROCESSES:
664                                 updateMaxCachedProcesses();
665                                 break;
666                             case KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED:
667                                 updateBackgroundActivityStarts();
668                                 break;
669                             case KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED:
670                                 updateBackgroundFgsStartsRestriction();
671                                 break;
672                             case KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED:
673                                 updateFgsStartsRestriction();
674                                 break;
675                             case KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED:
676                                 updateFgsStartsRestrictionNotification();
677                                 break;
678                             case KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK:
679                                 updateFgsStartsRestrictionCheckCallerTargetSdk();
680                                 break;
681                             case KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED:
682                                 updateFgsNotificationDeferralEnable();
683                                 break;
684                             case KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED:
685                                 updateFgsNotificationDeferralApiGated();
686                                 break;
687                             case KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL:
688                                 updateFgsNotificationDeferralInterval();
689                                 break;
690                             case KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME:
691                                 updateFgsNotificationDeferralExclusionTime();
692                                 break;
693                             case KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR:
694                                 updatePushMessagingOverQuotaBehavior();
695                                 break;
696                             case KEY_OOMADJ_UPDATE_POLICY:
697                                 updateOomAdjUpdatePolicy();
698                                 break;
699                             case KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES:
700                             case KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES:
701                                 updateImperceptibleKillExemptions();
702                                 break;
703                             case KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS:
704                                 updateForceRestrictedBackgroundCheck();
705                                 break;
706                             case KEY_MIN_ASSOC_LOG_DURATION:
707                                 updateMinAssocLogDuration();
708                                 break;
709                             case KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED:
710                             case KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE:
711                             case KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD:
712                             case KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED:
713                             case KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE:
714                             case KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD:
715                                 updateBinderHeavyHitterWatcher();
716                                 break;
717                             case KEY_MAX_PHANTOM_PROCESSES:
718                                 updateMaxPhantomProcesses();
719                                 break;
720                             case KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION:
721                                 updateBootTimeTempAllowListDuration();
722                                 break;
723                             case KEY_FG_TO_BG_FGS_GRACE_DURATION:
724                                 updateFgToBgFgsGraceDuration();
725                                 break;
726                             case KEY_FGS_START_FOREGROUND_TIMEOUT:
727                                 updateFgsStartForegroundTimeout();
728                                 break;
729                             case KEY_FGS_ATOM_SAMPLE_RATE:
730                                 updateFgsAtomSamplePercent();
731                                 break;
732                             case KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE:
733                                 updateFgsStartAllowedLogSamplePercent();
734                                 break;
735                             case KEY_FGS_START_DENIED_LOG_SAMPLE_RATE:
736                                 updateFgsStartDeniedLogSamplePercent();
737                                 break;
738                             case KEY_FGS_ALLOW_OPT_OUT:
739                                 updateFgsAllowOptOut();
740                                 break;
741                             default:
742                                 break;
743                         }
744                     }
745                 }
746             };
747 
ActivityManagerConstants(Context context, ActivityManagerService service, Handler handler)748     ActivityManagerConstants(Context context, ActivityManagerService service, Handler handler) {
749         super(handler);
750         mService = service;
751         mSystemServerAutomaticHeapDumpEnabled = Build.IS_DEBUGGABLE
752                 && context.getResources().getBoolean(
753                 com.android.internal.R.bool.config_debugEnableAutomaticSystemServerHeapDumps);
754         mSystemServerAutomaticHeapDumpPackageName = context.getPackageName();
755         mSystemServerAutomaticHeapDumpPssThresholdBytes = Math.max(
756                 MIN_AUTOMATIC_HEAP_DUMP_PSS_THRESHOLD_BYTES,
757                 context.getResources().getInteger(
758                         com.android.internal.R.integer.config_debugSystemServerPssThresholdBytes));
759         mDefaultImperceptibleKillExemptPackages = Arrays.asList(
760                 context.getResources().getStringArray(
761                 com.android.internal.R.array.config_defaultImperceptibleKillingExemptionPkgs));
762         mDefaultImperceptibleKillExemptProcStates = Arrays.stream(
763                 context.getResources().getIntArray(
764                 com.android.internal.R.array.config_defaultImperceptibleKillingExemptionProcStates))
765                 .boxed().collect(Collectors.toList());
766         IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.addAll(mDefaultImperceptibleKillExemptPackages);
767         IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.addAll(mDefaultImperceptibleKillExemptProcStates);
768         mDefaultBinderHeavyHitterWatcherEnabled = context.getResources().getBoolean(
769                 com.android.internal.R.bool.config_defaultBinderHeavyHitterWatcherEnabled);
770         mDefaultBinderHeavyHitterWatcherBatchSize = context.getResources().getInteger(
771                 com.android.internal.R.integer.config_defaultBinderHeavyHitterWatcherBatchSize);
772         mDefaultBinderHeavyHitterWatcherThreshold = context.getResources().getFloat(
773                 com.android.internal.R.dimen.config_defaultBinderHeavyHitterWatcherThreshold);
774         mDefaultBinderHeavyHitterAutoSamplerEnabled = context.getResources().getBoolean(
775                 com.android.internal.R.bool.config_defaultBinderHeavyHitterAutoSamplerEnabled);
776         mDefaultBinderHeavyHitterAutoSamplerBatchSize = context.getResources().getInteger(
777                 com.android.internal.R.integer.config_defaultBinderHeavyHitterAutoSamplerBatchSize);
778         mDefaultBinderHeavyHitterAutoSamplerThreshold = context.getResources().getFloat(
779                 com.android.internal.R.dimen.config_defaultBinderHeavyHitterAutoSamplerThreshold);
780         BINDER_HEAVY_HITTER_WATCHER_ENABLED = mDefaultBinderHeavyHitterWatcherEnabled;
781         BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE = mDefaultBinderHeavyHitterWatcherBatchSize;
782         BINDER_HEAVY_HITTER_WATCHER_THRESHOLD = mDefaultBinderHeavyHitterWatcherThreshold;
783         BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED = mDefaultBinderHeavyHitterAutoSamplerEnabled;
784         BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE = mDefaultBinderHeavyHitterAutoSamplerBatchSize;
785         BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD = mDefaultBinderHeavyHitterAutoSamplerThreshold;
786         service.scheduleUpdateBinderHeavyHitterWatcherConfig();
787         KEEP_WARMING_SERVICES.addAll(Arrays.stream(
788                 context.getResources().getStringArray(
789                         com.android.internal.R.array.config_keep_warming_services))
790                 .map(ComponentName::unflattenFromString).collect(Collectors.toSet()));
791         mCustomizedMaxCachedProcesses = context.getResources().getInteger(
792                 com.android.internal.R.integer.config_customizedMaxCachedProcesses);
793         CUR_MAX_CACHED_PROCESSES = mCustomizedMaxCachedProcesses;
794         CUR_MAX_EMPTY_PROCESSES = computeEmptyProcessLimit(CUR_MAX_CACHED_PROCESSES);
795     }
796 
start(ContentResolver resolver)797     public void start(ContentResolver resolver) {
798         mResolver = resolver;
799         mResolver.registerContentObserver(ACTIVITY_MANAGER_CONSTANTS_URI, false, this);
800         mResolver.registerContentObserver(ACTIVITY_STARTS_LOGGING_ENABLED_URI, false, this);
801         mResolver.registerContentObserver(FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI,
802                 false, this);
803         if (mSystemServerAutomaticHeapDumpEnabled) {
804             mResolver.registerContentObserver(ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI,
805                     false, this);
806         }
807         updateConstants();
808         if (mSystemServerAutomaticHeapDumpEnabled) {
809             updateEnableAutomaticSystemServerHeapDumps();
810         }
811         DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
812                 ActivityThread.currentApplication().getMainExecutor(),
813                 mOnDeviceConfigChangedListener);
814         loadDeviceConfigConstants();
815         // The following read from Settings.
816         updateActivityStartsLoggingEnabled();
817         updateForegroundServiceStartsLoggingEnabled();
818     }
819 
loadDeviceConfigConstants()820     private void loadDeviceConfigConstants() {
821         mOnDeviceConfigChangedListener.onPropertiesChanged(
822                 DeviceConfig.getProperties(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER));
823     }
824 
setOverrideMaxCachedProcesses(int value)825     public void setOverrideMaxCachedProcesses(int value) {
826         mOverrideMaxCachedProcesses = value;
827         updateMaxCachedProcesses();
828     }
829 
getOverrideMaxCachedProcesses()830     public int getOverrideMaxCachedProcesses() {
831         return mOverrideMaxCachedProcesses;
832     }
833 
computeEmptyProcessLimit(int totalProcessLimit)834     public static int computeEmptyProcessLimit(int totalProcessLimit) {
835         return totalProcessLimit/2;
836     }
837 
838     @Override
onChange(boolean selfChange, Uri uri)839     public void onChange(boolean selfChange, Uri uri) {
840         if (uri == null) return;
841         if (ACTIVITY_MANAGER_CONSTANTS_URI.equals(uri)) {
842             updateConstants();
843         } else if (ACTIVITY_STARTS_LOGGING_ENABLED_URI.equals(uri)) {
844             updateActivityStartsLoggingEnabled();
845         } else if (FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI.equals(uri)) {
846             updateForegroundServiceStartsLoggingEnabled();
847         } else if (ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI.equals(uri)) {
848             updateEnableAutomaticSystemServerHeapDumps();
849         }
850     }
851 
updateConstants()852     private void updateConstants() {
853         final String setting = Settings.Global.getString(mResolver,
854                 Settings.Global.ACTIVITY_MANAGER_CONSTANTS);
855         synchronized (mService) {
856             try {
857                 mParser.setString(setting);
858             } catch (IllegalArgumentException e) {
859                 // Failed to parse the settings string, log this and move on
860                 // with defaults.
861                 Slog.e("ActivityManagerConstants", "Bad activity manager config settings", e);
862             }
863             final long currentPowerCheckInterval = POWER_CHECK_INTERVAL;
864 
865             BACKGROUND_SETTLE_TIME = mParser.getLong(KEY_BACKGROUND_SETTLE_TIME,
866                     DEFAULT_BACKGROUND_SETTLE_TIME);
867             FGSERVICE_MIN_SHOWN_TIME = mParser.getLong(KEY_FGSERVICE_MIN_SHOWN_TIME,
868                     DEFAULT_FGSERVICE_MIN_SHOWN_TIME);
869             FGSERVICE_MIN_REPORT_TIME = mParser.getLong(KEY_FGSERVICE_MIN_REPORT_TIME,
870                     DEFAULT_FGSERVICE_MIN_REPORT_TIME);
871             FGSERVICE_SCREEN_ON_BEFORE_TIME = mParser.getLong(KEY_FGSERVICE_SCREEN_ON_BEFORE_TIME,
872                     DEFAULT_FGSERVICE_SCREEN_ON_BEFORE_TIME);
873             FGSERVICE_SCREEN_ON_AFTER_TIME = mParser.getLong(KEY_FGSERVICE_SCREEN_ON_AFTER_TIME,
874                     DEFAULT_FGSERVICE_SCREEN_ON_AFTER_TIME);
875             CONTENT_PROVIDER_RETAIN_TIME = mParser.getLong(KEY_CONTENT_PROVIDER_RETAIN_TIME,
876                     DEFAULT_CONTENT_PROVIDER_RETAIN_TIME);
877             GC_TIMEOUT = mParser.getLong(KEY_GC_TIMEOUT,
878                     DEFAULT_GC_TIMEOUT);
879             GC_MIN_INTERVAL = mParser.getLong(KEY_GC_MIN_INTERVAL,
880                     DEFAULT_GC_MIN_INTERVAL);
881             FULL_PSS_MIN_INTERVAL = mParser.getLong(KEY_FULL_PSS_MIN_INTERVAL,
882                     DEFAULT_FULL_PSS_MIN_INTERVAL);
883             FULL_PSS_LOWERED_INTERVAL = mParser.getLong(KEY_FULL_PSS_LOWERED_INTERVAL,
884                     DEFAULT_FULL_PSS_LOWERED_INTERVAL);
885             POWER_CHECK_INTERVAL = mParser.getLong(KEY_POWER_CHECK_INTERVAL,
886                     DEFAULT_POWER_CHECK_INTERVAL);
887             POWER_CHECK_MAX_CPU_1 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_1,
888                     DEFAULT_POWER_CHECK_MAX_CPU_1);
889             POWER_CHECK_MAX_CPU_2 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_2,
890                     DEFAULT_POWER_CHECK_MAX_CPU_2);
891             POWER_CHECK_MAX_CPU_3 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_3,
892                     DEFAULT_POWER_CHECK_MAX_CPU_3);
893             POWER_CHECK_MAX_CPU_4 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_4,
894                     DEFAULT_POWER_CHECK_MAX_CPU_4);
895             SERVICE_USAGE_INTERACTION_TIME_PRE_S = mParser.getLong(
896                     KEY_SERVICE_USAGE_INTERACTION_TIME_PRE_S,
897                     DEFAULT_SERVICE_USAGE_INTERACTION_TIME_PRE_S);
898             SERVICE_USAGE_INTERACTION_TIME_POST_S = mParser.getLong(
899                     KEY_SERVICE_USAGE_INTERACTION_TIME_POST_S,
900                     DEFAULT_SERVICE_USAGE_INTERACTION_TIME_POST_S);
901             USAGE_STATS_INTERACTION_INTERVAL_PRE_S = mParser.getLong(
902                     KEY_USAGE_STATS_INTERACTION_INTERVAL_PRE_S,
903                     DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_PRE_S);
904             USAGE_STATS_INTERACTION_INTERVAL_POST_S = mParser.getLong(
905                     KEY_USAGE_STATS_INTERACTION_INTERVAL_POST_S,
906                     DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_POST_S);
907             SERVICE_RESTART_DURATION = mParser.getLong(KEY_SERVICE_RESTART_DURATION,
908                     DEFAULT_SERVICE_RESTART_DURATION);
909             SERVICE_RESET_RUN_DURATION = mParser.getLong(KEY_SERVICE_RESET_RUN_DURATION,
910                     DEFAULT_SERVICE_RESET_RUN_DURATION);
911             SERVICE_RESTART_DURATION_FACTOR = mParser.getInt(KEY_SERVICE_RESTART_DURATION_FACTOR,
912                     DEFAULT_SERVICE_RESTART_DURATION_FACTOR);
913             SERVICE_MIN_RESTART_TIME_BETWEEN = mParser.getLong(KEY_SERVICE_MIN_RESTART_TIME_BETWEEN,
914                     DEFAULT_SERVICE_MIN_RESTART_TIME_BETWEEN);
915             MAX_SERVICE_INACTIVITY = mParser.getLong(KEY_MAX_SERVICE_INACTIVITY,
916                     DEFAULT_MAX_SERVICE_INACTIVITY);
917             BG_START_TIMEOUT = mParser.getLong(KEY_BG_START_TIMEOUT,
918                     DEFAULT_BG_START_TIMEOUT);
919             SERVICE_BG_ACTIVITY_START_TIMEOUT = mParser.getLong(
920                     KEY_SERVICE_BG_ACTIVITY_START_TIMEOUT,
921                     DEFAULT_SERVICE_BG_ACTIVITY_START_TIMEOUT);
922             BOUND_SERVICE_CRASH_RESTART_DURATION = mParser.getLong(
923                 KEY_BOUND_SERVICE_CRASH_RESTART_DURATION,
924                 DEFAULT_BOUND_SERVICE_CRASH_RESTART_DURATION);
925             BOUND_SERVICE_MAX_CRASH_RETRY = mParser.getInt(KEY_BOUND_SERVICE_CRASH_MAX_RETRY,
926                 DEFAULT_BOUND_SERVICE_CRASH_MAX_RETRY);
927             FLAG_PROCESS_START_ASYNC = mParser.getBoolean(KEY_PROCESS_START_ASYNC,
928                     DEFAULT_PROCESS_START_ASYNC);
929             MEMORY_INFO_THROTTLE_TIME = mParser.getLong(KEY_MEMORY_INFO_THROTTLE_TIME,
930                     DEFAULT_MEMORY_INFO_THROTTLE_TIME);
931             TOP_TO_FGS_GRACE_DURATION = mParser.getDurationMillis(KEY_TOP_TO_FGS_GRACE_DURATION,
932                     DEFAULT_TOP_TO_FGS_GRACE_DURATION);
933             MIN_CRASH_INTERVAL = mParser.getInt(KEY_MIN_CRASH_INTERVAL,
934                     DEFAULT_MIN_CRASH_INTERVAL);
935             PENDINGINTENT_WARNING_THRESHOLD = mParser.getInt(KEY_PENDINGINTENT_WARNING_THRESHOLD,
936                     DEFAULT_PENDINGINTENT_WARNING_THRESHOLD);
937             PROCESS_CRASH_COUNT_RESET_INTERVAL = mParser.getInt(
938                     KEY_PROCESS_CRASH_COUNT_RESET_INTERVAL,
939                     DEFAULT_PROCESS_CRASH_COUNT_RESET_INTERVAL);
940             PROCESS_CRASH_COUNT_LIMIT = mParser.getInt(KEY_PROCESS_CRASH_COUNT_LIMIT,
941                     DEFAULT_PROCESS_CRASH_COUNT_LIMIT);
942 
943             if (POWER_CHECK_INTERVAL != currentPowerCheckInterval) {
944                 mService.mHandler.removeMessages(
945                         ActivityManagerService.CHECK_EXCESSIVE_POWER_USE_MSG);
946                 final Message msg = mService.mHandler.obtainMessage(
947                         ActivityManagerService.CHECK_EXCESSIVE_POWER_USE_MSG);
948                 mService.mHandler.sendMessageDelayed(msg, POWER_CHECK_INTERVAL);
949             }
950             // For new flags that are intended for server-side experiments, please use the new
951             // DeviceConfig package.
952         }
953     }
954 
updateActivityStartsLoggingEnabled()955     private void updateActivityStartsLoggingEnabled() {
956         mFlagActivityStartsLoggingEnabled = Settings.Global.getInt(mResolver,
957                 Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED, 1) == 1;
958     }
959 
updateBackgroundActivityStarts()960     private void updateBackgroundActivityStarts() {
961         mFlagBackgroundActivityStartsEnabled = DeviceConfig.getBoolean(
962                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
963                 KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED,
964                 /*defaultValue*/ false);
965     }
966 
updateForegroundServiceStartsLoggingEnabled()967     private void updateForegroundServiceStartsLoggingEnabled() {
968         mFlagForegroundServiceStartsLoggingEnabled = Settings.Global.getInt(mResolver,
969                 Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED, 1) == 1;
970     }
971 
updateBackgroundFgsStartsRestriction()972     private void updateBackgroundFgsStartsRestriction() {
973         mFlagBackgroundFgsStartRestrictionEnabled = DeviceConfig.getBoolean(
974                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
975                 KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED,
976                 /*defaultValue*/ true);
977     }
978 
updateFgsStartsRestriction()979     private void updateFgsStartsRestriction() {
980         mFlagFgsStartRestrictionEnabled = DeviceConfig.getBoolean(
981                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
982                 KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED,
983                 /*defaultValue*/ true);
984     }
985 
updateFgsStartsRestrictionNotification()986     private void updateFgsStartsRestrictionNotification() {
987         mFgsStartRestrictionNotificationEnabled = DeviceConfig.getBoolean(
988                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
989                 KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED,
990                 /*defaultValue*/ false);
991     }
992 
updateFgsStartsRestrictionCheckCallerTargetSdk()993     private void updateFgsStartsRestrictionCheckCallerTargetSdk() {
994         mFgsStartRestrictionCheckCallerTargetSdk = DeviceConfig.getBoolean(
995                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
996                 KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK,
997                 /*defaultValue*/ true);
998     }
999 
updateFgsNotificationDeferralEnable()1000     private void updateFgsNotificationDeferralEnable() {
1001         mFlagFgsNotificationDeferralEnabled = DeviceConfig.getBoolean(
1002                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1003                 KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED,
1004                 /*default value*/ true);
1005     }
1006 
updateFgsNotificationDeferralApiGated()1007     private void updateFgsNotificationDeferralApiGated() {
1008         mFlagFgsNotificationDeferralApiGated = DeviceConfig.getBoolean(
1009                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1010                 KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED,
1011                 /*default value*/ false);
1012     }
1013 
updateFgsNotificationDeferralInterval()1014     private void updateFgsNotificationDeferralInterval() {
1015         mFgsNotificationDeferralInterval = DeviceConfig.getLong(
1016                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1017                 KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL,
1018                 /*default value*/ 10_000L);
1019     }
1020 
updateFgsNotificationDeferralExclusionTime()1021     private void updateFgsNotificationDeferralExclusionTime() {
1022         mFgsNotificationDeferralExclusionTime = DeviceConfig.getLong(
1023                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1024                 KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME,
1025                 /*default value*/ 2 * 60 * 1000L);
1026     }
1027 
updatePushMessagingOverQuotaBehavior()1028     private void updatePushMessagingOverQuotaBehavior() {
1029         mPushMessagingOverQuotaBehavior = DeviceConfig.getInt(
1030                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1031                 KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR,
1032                 DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR);
1033         if (mPushMessagingOverQuotaBehavior < TEMPORARY_ALLOW_LIST_TYPE_NONE
1034                 || mPushMessagingOverQuotaBehavior
1035                 > TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED) {
1036             mPushMessagingOverQuotaBehavior =
1037                     DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR;
1038         }
1039     }
1040 
updateOomAdjUpdatePolicy()1041     private void updateOomAdjUpdatePolicy() {
1042         OOMADJ_UPDATE_QUICK = DeviceConfig.getInt(
1043                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1044                 KEY_OOMADJ_UPDATE_POLICY,
1045                 /* defaultValue */ DEFAULT_OOMADJ_UPDATE_POLICY)
1046                 == OOMADJ_UPDATE_POLICY_QUICK;
1047     }
1048 
updateForceRestrictedBackgroundCheck()1049     private void updateForceRestrictedBackgroundCheck() {
1050         FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS = DeviceConfig.getBoolean(
1051                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1052                 KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS,
1053                 DEFAULT_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS);
1054     }
1055 
updateBootTimeTempAllowListDuration()1056     private void updateBootTimeTempAllowListDuration() {
1057         mBootTimeTempAllowlistDuration = DeviceConfig.getLong(
1058                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1059                 KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION,
1060                 DEFAULT_BOOT_TIME_TEMP_ALLOWLIST_DURATION);
1061     }
1062 
updateFgToBgFgsGraceDuration()1063     private void updateFgToBgFgsGraceDuration() {
1064         mFgToBgFgsGraceDuration = DeviceConfig.getLong(
1065                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1066                 KEY_FG_TO_BG_FGS_GRACE_DURATION,
1067                 DEFAULT_FG_TO_BG_FGS_GRACE_DURATION);
1068     }
1069 
updateFgsStartForegroundTimeout()1070     private void updateFgsStartForegroundTimeout() {
1071         mFgsStartForegroundTimeoutMs = DeviceConfig.getLong(
1072                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1073                 KEY_FGS_START_FOREGROUND_TIMEOUT,
1074                 DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS);
1075     }
1076 
updateFgsAtomSamplePercent()1077     private void updateFgsAtomSamplePercent() {
1078         mFgsAtomSampleRate = DeviceConfig.getFloat(
1079                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1080                 KEY_FGS_ATOM_SAMPLE_RATE,
1081                 DEFAULT_FGS_ATOM_SAMPLE_RATE);
1082     }
1083 
updateFgsStartAllowedLogSamplePercent()1084     private void updateFgsStartAllowedLogSamplePercent() {
1085         mFgsStartAllowedLogSampleRate = DeviceConfig.getFloat(
1086                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1087                 KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE,
1088                 DEFAULT_FGS_START_ALLOWED_LOG_SAMPLE_RATE);
1089     }
1090 
updateFgsStartDeniedLogSamplePercent()1091     private void updateFgsStartDeniedLogSamplePercent() {
1092         mFgsStartDeniedLogSampleRate = DeviceConfig.getFloat(
1093                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1094                 KEY_FGS_START_DENIED_LOG_SAMPLE_RATE,
1095                 DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE);
1096     }
1097 
updateFgsAllowOptOut()1098     private void updateFgsAllowOptOut() {
1099         mFgsAllowOptOut = DeviceConfig.getBoolean(
1100                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1101                 KEY_FGS_ALLOW_OPT_OUT,
1102                 DEFAULT_FGS_ALLOW_OPT_OUT);
1103     }
1104 
updateImperceptibleKillExemptions()1105     private void updateImperceptibleKillExemptions() {
1106         IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.clear();
1107         IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.addAll(mDefaultImperceptibleKillExemptPackages);
1108         String val = DeviceConfig.getString(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1109                 KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES, null);
1110         if (!TextUtils.isEmpty(val)) {
1111             IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.addAll(Arrays.asList(val.split(",")));
1112         }
1113 
1114         IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.clear();
1115         IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.addAll(mDefaultImperceptibleKillExemptProcStates);
1116         val = DeviceConfig.getString(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1117                 KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES, null);
1118         if (!TextUtils.isEmpty(val)) {
1119             Arrays.asList(val.split(",")).stream().forEach((v) -> {
1120                 try {
1121                     IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.add(Integer.parseInt(v));
1122                 } catch (NumberFormatException e) {
1123                 }
1124             });
1125         }
1126     }
1127 
updateEnableAutomaticSystemServerHeapDumps()1128     private void updateEnableAutomaticSystemServerHeapDumps() {
1129         if (!mSystemServerAutomaticHeapDumpEnabled) {
1130             Slog.wtf(TAG,
1131                     "updateEnableAutomaticSystemServerHeapDumps called when leak detection "
1132                             + "disabled");
1133             return;
1134         }
1135         // Monitoring is on by default, so if the setting hasn't been set by the user,
1136         // monitoring should be on.
1137         final boolean enabled = Settings.Global.getInt(mResolver,
1138                 Settings.Global.ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS, 1) == 1;
1139 
1140         // Setting the threshold to 0 stops the checking.
1141         final long threshold = enabled ? mSystemServerAutomaticHeapDumpPssThresholdBytes : 0;
1142         mService.setDumpHeapDebugLimit(null, 0, threshold,
1143                 mSystemServerAutomaticHeapDumpPackageName);
1144     }
1145 
updateMaxCachedProcesses()1146     private void updateMaxCachedProcesses() {
1147         String maxCachedProcessesFlag = DeviceConfig.getProperty(
1148                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MAX_CACHED_PROCESSES);
1149         try {
1150             CUR_MAX_CACHED_PROCESSES = mOverrideMaxCachedProcesses < 0
1151                     ? (TextUtils.isEmpty(maxCachedProcessesFlag)
1152                     ? mCustomizedMaxCachedProcesses : Integer.parseInt(maxCachedProcessesFlag))
1153                     : mOverrideMaxCachedProcesses;
1154         } catch (NumberFormatException e) {
1155             // Bad flag value from Phenotype, revert to default.
1156             Slog.e(TAG,
1157                     "Unable to parse flag for max_cached_processes: " + maxCachedProcessesFlag, e);
1158             CUR_MAX_CACHED_PROCESSES = mCustomizedMaxCachedProcesses;
1159         }
1160         CUR_MAX_EMPTY_PROCESSES = computeEmptyProcessLimit(CUR_MAX_CACHED_PROCESSES);
1161 
1162         // Note the trim levels do NOT depend on the override process limit, we want
1163         // to consider the same level the point where we do trimming regardless of any
1164         // additional enforced limit.
1165         final int rawMaxEmptyProcesses = computeEmptyProcessLimit(MAX_CACHED_PROCESSES);
1166         CUR_TRIM_EMPTY_PROCESSES = rawMaxEmptyProcesses/2;
1167         CUR_TRIM_CACHED_PROCESSES = (MAX_CACHED_PROCESSES-rawMaxEmptyProcesses)/3;
1168     }
1169 
1170     private void updateMinAssocLogDuration() {
1171         MIN_ASSOC_LOG_DURATION = DeviceConfig.getLong(
1172                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MIN_ASSOC_LOG_DURATION,
1173                 /* defaultValue */ DEFAULT_MIN_ASSOC_LOG_DURATION);
1174     }
1175 
1176     private void updateBinderHeavyHitterWatcher() {
1177         BINDER_HEAVY_HITTER_WATCHER_ENABLED = DeviceConfig.getBoolean(
1178                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED,
1179                 mDefaultBinderHeavyHitterWatcherEnabled);
1180         BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE = DeviceConfig.getInt(
1181                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE,
1182                 mDefaultBinderHeavyHitterWatcherBatchSize);
1183         BINDER_HEAVY_HITTER_WATCHER_THRESHOLD = DeviceConfig.getFloat(
1184                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD,
1185                 mDefaultBinderHeavyHitterWatcherThreshold);
1186         BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED = DeviceConfig.getBoolean(
1187                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1188                 KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED,
1189                 mDefaultBinderHeavyHitterAutoSamplerEnabled);
1190         BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE = DeviceConfig.getInt(
1191                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1192                 KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE,
1193                 mDefaultBinderHeavyHitterAutoSamplerBatchSize);
1194         BINDER_HEAVY_HITTER_WATCHER_THRESHOLD = DeviceConfig.getFloat(
1195                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1196                 KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD,
1197                 mDefaultBinderHeavyHitterAutoSamplerThreshold);
1198         mService.scheduleUpdateBinderHeavyHitterWatcherConfig();
1199     }
1200 
1201     private void updateMaxPhantomProcesses() {
1202         final int oldVal = MAX_PHANTOM_PROCESSES;
1203         MAX_PHANTOM_PROCESSES = DeviceConfig.getInt(
1204                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MAX_PHANTOM_PROCESSES,
1205                 DEFAULT_MAX_PHANTOM_PROCESSES);
1206         if (oldVal > MAX_PHANTOM_PROCESSES) {
1207             mService.mHandler.post(mService.mPhantomProcessList::trimPhantomProcessesIfNecessary);
1208         }
1209     }
1210 
1211     void dump(PrintWriter pw) {
1212         pw.println("ACTIVITY MANAGER SETTINGS (dumpsys activity settings) "
1213                 + Settings.Global.ACTIVITY_MANAGER_CONSTANTS + ":");
1214 
1215         pw.print("  "); pw.print(KEY_MAX_CACHED_PROCESSES); pw.print("=");
1216         pw.println(MAX_CACHED_PROCESSES);
1217         pw.print("  "); pw.print(KEY_BACKGROUND_SETTLE_TIME); pw.print("=");
1218         pw.println(BACKGROUND_SETTLE_TIME);
1219         pw.print("  "); pw.print(KEY_FGSERVICE_MIN_SHOWN_TIME); pw.print("=");
1220         pw.println(FGSERVICE_MIN_SHOWN_TIME);
1221         pw.print("  "); pw.print(KEY_FGSERVICE_MIN_REPORT_TIME); pw.print("=");
1222         pw.println(FGSERVICE_MIN_REPORT_TIME);
1223         pw.print("  "); pw.print(KEY_FGSERVICE_SCREEN_ON_BEFORE_TIME); pw.print("=");
1224         pw.println(FGSERVICE_SCREEN_ON_BEFORE_TIME);
1225         pw.print("  "); pw.print(KEY_FGSERVICE_SCREEN_ON_AFTER_TIME); pw.print("=");
1226         pw.println(FGSERVICE_SCREEN_ON_AFTER_TIME);
1227         pw.print("  "); pw.print(KEY_CONTENT_PROVIDER_RETAIN_TIME); pw.print("=");
1228         pw.println(CONTENT_PROVIDER_RETAIN_TIME);
1229         pw.print("  "); pw.print(KEY_GC_TIMEOUT); pw.print("=");
1230         pw.println(GC_TIMEOUT);
1231         pw.print("  "); pw.print(KEY_GC_MIN_INTERVAL); pw.print("=");
1232         pw.println(GC_MIN_INTERVAL);
1233         pw.print("  "); pw.print(KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS); pw.print("=");
1234         pw.println(FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS);
1235         pw.print("  "); pw.print(KEY_FULL_PSS_MIN_INTERVAL); pw.print("=");
1236         pw.println(FULL_PSS_MIN_INTERVAL);
1237         pw.print("  "); pw.print(KEY_FULL_PSS_LOWERED_INTERVAL); pw.print("=");
1238         pw.println(FULL_PSS_LOWERED_INTERVAL);
1239         pw.print("  "); pw.print(KEY_POWER_CHECK_INTERVAL); pw.print("=");
1240         pw.println(POWER_CHECK_INTERVAL);
1241         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_1); pw.print("=");
1242         pw.println(POWER_CHECK_MAX_CPU_1);
1243         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_2); pw.print("=");
1244         pw.println(POWER_CHECK_MAX_CPU_2);
1245         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_3); pw.print("=");
1246         pw.println(POWER_CHECK_MAX_CPU_3);
1247         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_4); pw.print("=");
1248         pw.println(POWER_CHECK_MAX_CPU_4);
1249         pw.print("  "); pw.print(KEY_SERVICE_USAGE_INTERACTION_TIME_PRE_S); pw.print("=");
1250         pw.println(SERVICE_USAGE_INTERACTION_TIME_PRE_S);
1251         pw.print("  "); pw.print(KEY_SERVICE_USAGE_INTERACTION_TIME_POST_S); pw.print("=");
1252         pw.println(SERVICE_USAGE_INTERACTION_TIME_POST_S);
1253         pw.print("  "); pw.print(KEY_USAGE_STATS_INTERACTION_INTERVAL_PRE_S); pw.print("=");
1254         pw.println(USAGE_STATS_INTERACTION_INTERVAL_PRE_S);
1255         pw.print("  "); pw.print(KEY_USAGE_STATS_INTERACTION_INTERVAL_POST_S); pw.print("=");
1256         pw.println(USAGE_STATS_INTERACTION_INTERVAL_POST_S);
1257         pw.print("  "); pw.print(KEY_SERVICE_RESTART_DURATION); pw.print("=");
1258         pw.println(SERVICE_RESTART_DURATION);
1259         pw.print("  "); pw.print(KEY_SERVICE_RESET_RUN_DURATION); pw.print("=");
1260         pw.println(SERVICE_RESET_RUN_DURATION);
1261         pw.print("  "); pw.print(KEY_SERVICE_RESTART_DURATION_FACTOR); pw.print("=");
1262         pw.println(SERVICE_RESTART_DURATION_FACTOR);
1263         pw.print("  "); pw.print(KEY_SERVICE_MIN_RESTART_TIME_BETWEEN); pw.print("=");
1264         pw.println(SERVICE_MIN_RESTART_TIME_BETWEEN);
1265         pw.print("  "); pw.print(KEY_MAX_SERVICE_INACTIVITY); pw.print("=");
1266         pw.println(MAX_SERVICE_INACTIVITY);
1267         pw.print("  "); pw.print(KEY_BG_START_TIMEOUT); pw.print("=");
1268         pw.println(BG_START_TIMEOUT);
1269         pw.print("  "); pw.print(KEY_SERVICE_BG_ACTIVITY_START_TIMEOUT); pw.print("=");
1270         pw.println(SERVICE_BG_ACTIVITY_START_TIMEOUT);
1271         pw.print("  "); pw.print(KEY_BOUND_SERVICE_CRASH_RESTART_DURATION); pw.print("=");
1272         pw.println(BOUND_SERVICE_CRASH_RESTART_DURATION);
1273         pw.print("  "); pw.print(KEY_BOUND_SERVICE_CRASH_MAX_RETRY); pw.print("=");
1274         pw.println(BOUND_SERVICE_MAX_CRASH_RETRY);
1275         pw.print("  "); pw.print(KEY_PROCESS_START_ASYNC); pw.print("=");
1276         pw.println(FLAG_PROCESS_START_ASYNC);
1277         pw.print("  "); pw.print(KEY_MEMORY_INFO_THROTTLE_TIME); pw.print("=");
1278         pw.println(MEMORY_INFO_THROTTLE_TIME);
1279         pw.print("  "); pw.print(KEY_TOP_TO_FGS_GRACE_DURATION); pw.print("=");
1280         pw.println(TOP_TO_FGS_GRACE_DURATION);
1281         pw.print("  "); pw.print(KEY_MIN_CRASH_INTERVAL); pw.print("=");
1282         pw.println(MIN_CRASH_INTERVAL);
1283         pw.print("  "); pw.print(KEY_PROCESS_CRASH_COUNT_RESET_INTERVAL); pw.print("=");
1284         pw.println(PROCESS_CRASH_COUNT_RESET_INTERVAL);
1285         pw.print("  "); pw.print(KEY_PROCESS_CRASH_COUNT_LIMIT); pw.print("=");
1286         pw.println(PROCESS_CRASH_COUNT_LIMIT);
1287         pw.print("  "); pw.print(KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES); pw.print("=");
1288         pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.toArray()));
1289         pw.print("  "); pw.print(KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES); pw.print("=");
1290         pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.toArray()));
1291         pw.print("  "); pw.print(KEY_MIN_ASSOC_LOG_DURATION); pw.print("=");
1292         pw.println(MIN_ASSOC_LOG_DURATION);
1293         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED); pw.print("=");
1294         pw.println(BINDER_HEAVY_HITTER_WATCHER_ENABLED);
1295         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE); pw.print("=");
1296         pw.println(BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE);
1297         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD); pw.print("=");
1298         pw.println(BINDER_HEAVY_HITTER_WATCHER_THRESHOLD);
1299         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED); pw.print("=");
1300         pw.println(BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED);
1301         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE); pw.print("=");
1302         pw.println(BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE);
1303         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD); pw.print("=");
1304         pw.println(BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD);
1305         pw.print("  "); pw.print(KEY_MAX_PHANTOM_PROCESSES); pw.print("=");
1306         pw.println(MAX_PHANTOM_PROCESSES);
1307         pw.print("  "); pw.print(KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION); pw.print("=");
1308         pw.println(mBootTimeTempAllowlistDuration);
1309         pw.print("  "); pw.print(KEY_FG_TO_BG_FGS_GRACE_DURATION); pw.print("=");
1310         pw.println(mFgToBgFgsGraceDuration);
1311         pw.print("  "); pw.print(KEY_FGS_START_FOREGROUND_TIMEOUT); pw.print("=");
1312         pw.println(mFgsStartForegroundTimeoutMs);
1313         pw.print("  "); pw.print(KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED); pw.print("=");
1314         pw.println(mFlagBackgroundActivityStartsEnabled);
1315         pw.print("  "); pw.print(KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED);
1316         pw.print("="); pw.println(mFlagBackgroundFgsStartRestrictionEnabled);
1317         pw.print("  "); pw.print(KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED); pw.print("=");
1318         pw.println(mFlagFgsStartRestrictionEnabled);
1319         pw.print("  "); pw.print(KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED);
1320                 pw.print("=");
1321         pw.println(mFgsStartRestrictionNotificationEnabled);
1322         pw.print("  "); pw.print(KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK);
1323         pw.print("="); pw.println(mFgsStartRestrictionCheckCallerTargetSdk);
1324         pw.print("  "); pw.print(KEY_FGS_ATOM_SAMPLE_RATE);
1325         pw.print("="); pw.println(mFgsAtomSampleRate);
1326         pw.print("  "); pw.print(KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE);
1327         pw.print("="); pw.println(mFgsStartAllowedLogSampleRate);
1328         pw.print("  "); pw.print(KEY_FGS_START_DENIED_LOG_SAMPLE_RATE);
1329         pw.print("="); pw.println(mFgsStartDeniedLogSampleRate);
1330         pw.print("  "); pw.print(KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR);
1331         pw.print("="); pw.println(mPushMessagingOverQuotaBehavior);
1332         pw.print("  "); pw.print(KEY_FGS_ALLOW_OPT_OUT);
1333         pw.print("="); pw.println(mFgsAllowOptOut);
1334 
1335         pw.println();
1336         if (mOverrideMaxCachedProcesses >= 0) {
1337             pw.print("  mOverrideMaxCachedProcesses="); pw.println(mOverrideMaxCachedProcesses);
1338         }
1339         pw.print("  mCustomizedMaxCachedProcesses="); pw.println(mCustomizedMaxCachedProcesses);
1340         pw.print("  CUR_MAX_CACHED_PROCESSES="); pw.println(CUR_MAX_CACHED_PROCESSES);
1341         pw.print("  CUR_MAX_EMPTY_PROCESSES="); pw.println(CUR_MAX_EMPTY_PROCESSES);
1342         pw.print("  CUR_TRIM_EMPTY_PROCESSES="); pw.println(CUR_TRIM_EMPTY_PROCESSES);
1343         pw.print("  CUR_TRIM_CACHED_PROCESSES="); pw.println(CUR_TRIM_CACHED_PROCESSES);
1344         pw.print("  OOMADJ_UPDATE_QUICK="); pw.println(OOMADJ_UPDATE_QUICK);
1345     }
1346 }
1347