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.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE;
20 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_HEALTH;
21 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION;
22 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING;
23 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
24 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
25 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED;
26 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE;
27 
28 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER_QUICK;
29 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_BACKGROUND_RESTRICTED_ONLY;
30 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_TARGET_T_ONLY;
31 import static com.android.server.am.BroadcastConstants.getDeviceConfigBoolean;
32 
33 import android.annotation.NonNull;
34 import android.app.ActivityThread;
35 import android.app.ForegroundServiceTypePolicy;
36 import android.content.ComponentName;
37 import android.content.ContentResolver;
38 import android.content.Context;
39 import android.database.ContentObserver;
40 import android.net.Uri;
41 import android.os.Build;
42 import android.os.Handler;
43 import android.os.Message;
44 import android.os.PowerExemptionManager;
45 import android.os.SystemClock;
46 import android.provider.DeviceConfig;
47 import android.provider.DeviceConfig.OnPropertiesChangedListener;
48 import android.provider.DeviceConfig.Properties;
49 import android.provider.Settings;
50 import android.text.TextUtils;
51 import android.util.ArraySet;
52 import android.util.KeyValueListParser;
53 import android.util.Slog;
54 import android.util.SparseBooleanArray;
55 
56 import com.android.internal.R;
57 import com.android.internal.annotations.GuardedBy;
58 
59 import dalvik.annotation.optimization.NeverCompile;
60 
61 import java.io.PrintWriter;
62 import java.util.Arrays;
63 import java.util.List;
64 import java.util.stream.Collectors;
65 
66 /**
67  * Settings constants that can modify the activity manager's behavior.
68  */
69 final class ActivityManagerConstants extends ContentObserver {
70     private static final String TAG = "ActivityManagerConstants";
71 
72     // Key names stored in the settings value.
73     static final String KEY_BACKGROUND_SETTLE_TIME = "background_settle_time";
74 
75     private static final String KEY_FGSERVICE_MIN_SHOWN_TIME
76             = "fgservice_min_shown_time";
77     private static final String KEY_FGSERVICE_MIN_REPORT_TIME
78             = "fgservice_min_report_time";
79     private static final String KEY_FGSERVICE_SCREEN_ON_BEFORE_TIME
80             = "fgservice_screen_on_before_time";
81     private static final String KEY_FGSERVICE_SCREEN_ON_AFTER_TIME
82             = "fgservice_screen_on_after_time";
83 
84     private static final String KEY_FGS_BOOT_COMPLETED_ALLOWLIST = "fgs_boot_completed_allowlist";
85 
86     private static final String KEY_CONTENT_PROVIDER_RETAIN_TIME = "content_provider_retain_time";
87     private static final String KEY_GC_TIMEOUT = "gc_timeout";
88     private static final String KEY_GC_MIN_INTERVAL = "gc_min_interval";
89     private static final String KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS =
90             "force_bg_check_on_restricted";
91     private static final String KEY_FULL_PSS_MIN_INTERVAL = "full_pss_min_interval";
92     private static final String KEY_FULL_PSS_LOWERED_INTERVAL = "full_pss_lowered_interval";
93     private static final String KEY_POWER_CHECK_INTERVAL = "power_check_interval";
94     private static final String KEY_POWER_CHECK_MAX_CPU_1 = "power_check_max_cpu_1";
95     private static final String KEY_POWER_CHECK_MAX_CPU_2 = "power_check_max_cpu_2";
96     private static final String KEY_POWER_CHECK_MAX_CPU_3 = "power_check_max_cpu_3";
97     private static final String KEY_POWER_CHECK_MAX_CPU_4 = "power_check_max_cpu_4";
98     /** Used for all apps on R and earlier versions. */
99     private static final String KEY_SERVICE_USAGE_INTERACTION_TIME_PRE_S =
100             "service_usage_interaction_time";
101     private static final String KEY_SERVICE_USAGE_INTERACTION_TIME_POST_S =
102             "service_usage_interaction_time_post_s";
103     /** Used for all apps on R and earlier versions. */
104     private static final String KEY_USAGE_STATS_INTERACTION_INTERVAL_PRE_S =
105             "usage_stats_interaction_interval";
106     private static final String KEY_USAGE_STATS_INTERACTION_INTERVAL_POST_S =
107             "usage_stats_interaction_interval_post_s";
108     private static final String KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES =
109             "imperceptible_kill_exempt_packages";
110     private static final String KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES =
111             "imperceptible_kill_exempt_proc_states";
112     static final String KEY_SERVICE_RESTART_DURATION = "service_restart_duration";
113     static final String KEY_SERVICE_RESET_RUN_DURATION = "service_reset_run_duration";
114     static final String KEY_SERVICE_RESTART_DURATION_FACTOR = "service_restart_duration_factor";
115     static final String KEY_SERVICE_MIN_RESTART_TIME_BETWEEN = "service_min_restart_time_between";
116     static final String KEY_MAX_SERVICE_INACTIVITY = "service_max_inactivity";
117     static final String KEY_BG_START_TIMEOUT = "service_bg_start_timeout";
118     static final String KEY_SERVICE_BG_ACTIVITY_START_TIMEOUT = "service_bg_activity_start_timeout";
119     static final String KEY_BOUND_SERVICE_CRASH_RESTART_DURATION = "service_crash_restart_duration";
120     static final String KEY_BOUND_SERVICE_CRASH_MAX_RETRY = "service_crash_max_retry";
121     static final String KEY_PROCESS_START_ASYNC = "process_start_async";
122     static final String KEY_MEMORY_INFO_THROTTLE_TIME = "memory_info_throttle_time";
123     static final String KEY_TOP_TO_FGS_GRACE_DURATION = "top_to_fgs_grace_duration";
124     static final String KEY_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION =
125             "top_to_almost_perceptible_grace_duration";
126     static final String KEY_PENDINGINTENT_WARNING_THRESHOLD = "pendingintent_warning_threshold";
127     static final String KEY_MIN_CRASH_INTERVAL = "min_crash_interval";
128     static final String KEY_PROCESS_CRASH_COUNT_RESET_INTERVAL =
129             "process_crash_count_reset_interval";
130     static final String KEY_PROCESS_CRASH_COUNT_LIMIT = "process_crash_count_limit";
131     static final String KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION = "boot_time_temp_allowlist_duration";
132     static final String KEY_FG_TO_BG_FGS_GRACE_DURATION = "fg_to_bg_fgs_grace_duration";
133     static final String KEY_VISIBLE_TO_INVISIBLE_UIJ_SCHEDULE_GRACE_DURATION =
134             "vis_to_invis_uij_schedule_grace_duration";
135     static final String KEY_FGS_START_FOREGROUND_TIMEOUT = "fgs_start_foreground_timeout";
136     static final String KEY_FGS_ATOM_SAMPLE_RATE = "fgs_atom_sample_rate";
137     static final String KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE = "fgs_start_allowed_log_sample_rate";
138     static final String KEY_FGS_START_DENIED_LOG_SAMPLE_RATE = "fgs_start_denied_log_sample_rate";
139     static final String KEY_FGS_ALLOW_OPT_OUT = "fgs_allow_opt_out";
140     static final String KEY_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE =
141             "extra_delay_svc_restart_mem_pressure";
142     static final String KEY_ENABLE_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE =
143             "enable_extra_delay_svc_restart_mem_pressure";
144     static final String KEY_KILL_BG_RESTRICTED_CACHED_IDLE = "kill_bg_restricted_cached_idle";
145     static final String KEY_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME =
146             "kill_bg_restricted_cached_idle_settle_time";
147     static final String KEY_MAX_PREVIOUS_TIME = "max_previous_time";
148     /**
149      * Note this key is on {@link DeviceConfig#NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS}.
150      * @see #mEnableComponentAlias
151      */
152     static final String KEY_ENABLE_COMPONENT_ALIAS = "enable_experimental_component_alias";
153     /**
154      * Note this key is on {@link DeviceConfig#NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS}.
155      * @see #mComponentAliasOverrides
156      */
157     static final String KEY_COMPONENT_ALIAS_OVERRIDES = "component_alias_overrides";
158 
159     /**
160      * Indicates the maximum time that an app is blocked for the network rules to get updated.
161      */
162     static final String KEY_NETWORK_ACCESS_TIMEOUT_MS = "network_access_timeout_ms";
163 
164     static final String KEY_USE_TIERED_CACHED_ADJ = "use_tiered_cached_adj";
165     static final String KEY_TIERED_CACHED_ADJ_DECAY_TIME = "tiered_cached_adj_decay_time";
166 
167     /**
168      * Whether or not to enable the new oom adjuster implementation.
169      */
170     static final String KEY_ENABLE_NEW_OOMADJ = "enable_new_oom_adj";
171 
172     /**
173      * Whether or not to enable the batching of OOM adjuster calls to LMKD
174      */
175     static final String KEY_ENABLE_BATCHING_OOM_ADJ = "enable_batching_oom_adj";
176 
177     /**
178      * How long to wait before scheduling another follow-up oomAdjuster update for time based state.
179      */
180     static final String KEY_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION =
181             "follow_up_oomadj_update_wait_duration";
182 
183     private static final int DEFAULT_MAX_CACHED_PROCESSES = 1024;
184     private static final boolean DEFAULT_PRIORITIZE_ALARM_BROADCASTS = true;
185     private static final long DEFAULT_FGSERVICE_MIN_SHOWN_TIME = 2*1000;
186     private static final long DEFAULT_FGSERVICE_MIN_REPORT_TIME = 3*1000;
187     private static final long DEFAULT_FGSERVICE_SCREEN_ON_BEFORE_TIME = 1*1000;
188     private static final long DEFAULT_FGSERVICE_SCREEN_ON_AFTER_TIME = 5*1000;
189 
190     private static final int DEFAULT_FGS_BOOT_COMPLETED_ALLOWLIST =
191             FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
192                 | FOREGROUND_SERVICE_TYPE_HEALTH
193                 | FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
194                 | FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
195                 | FOREGROUND_SERVICE_TYPE_SPECIAL_USE
196                 | FOREGROUND_SERVICE_TYPE_LOCATION;
197 
198     private static final long DEFAULT_CONTENT_PROVIDER_RETAIN_TIME = 20*1000;
199     private static final long DEFAULT_GC_TIMEOUT = 5*1000;
200     private static final long DEFAULT_GC_MIN_INTERVAL = 60*1000;
201     private static final long DEFAULT_FULL_PSS_MIN_INTERVAL = 20*60*1000;
202     private static final boolean DEFAULT_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS = true;
203     private static final long DEFAULT_FULL_PSS_LOWERED_INTERVAL = 5*60*1000;
204     private static final long DEFAULT_POWER_CHECK_INTERVAL = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
205     private static final int DEFAULT_POWER_CHECK_MAX_CPU_1 = 25;
206     private static final int DEFAULT_POWER_CHECK_MAX_CPU_2 = 25;
207     private static final int DEFAULT_POWER_CHECK_MAX_CPU_3 = 10;
208     private static final int DEFAULT_POWER_CHECK_MAX_CPU_4 = 2;
209     private static final long DEFAULT_SERVICE_USAGE_INTERACTION_TIME_PRE_S = 30 * 60 * 1000;
210     private static final long DEFAULT_SERVICE_USAGE_INTERACTION_TIME_POST_S = 60 * 1000;
211     private static final long DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_PRE_S = 2 * 60 * 60 * 1000;
212     private static final long DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_POST_S = 10 * 60 * 1000;
213     private static final long DEFAULT_SERVICE_RESTART_DURATION = 1*1000;
214     private static final long DEFAULT_SERVICE_RESET_RUN_DURATION = 60*1000;
215     private static final int DEFAULT_SERVICE_RESTART_DURATION_FACTOR = 4;
216     private static final long DEFAULT_SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
217     private static final long DEFAULT_MAX_SERVICE_INACTIVITY = 30*60*1000;
218     private static final long DEFAULT_BG_START_TIMEOUT = 15*1000;
219     private static final long DEFAULT_SERVICE_BG_ACTIVITY_START_TIMEOUT = 10_000;
220     private static final long DEFAULT_BOUND_SERVICE_CRASH_RESTART_DURATION = 30*60_000;
221     private static final int DEFAULT_BOUND_SERVICE_CRASH_MAX_RETRY = 16;
222     private static final boolean DEFAULT_PROCESS_START_ASYNC = true;
223     private static final long DEFAULT_MEMORY_INFO_THROTTLE_TIME = 5*60*1000;
224     private static final long DEFAULT_TOP_TO_FGS_GRACE_DURATION = 15 * 1000;
225     private static final long DEFAULT_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION = 15 * 1000;
226     private static final int DEFAULT_PENDINGINTENT_WARNING_THRESHOLD = 2000;
227     private static final int DEFAULT_MIN_CRASH_INTERVAL = 2 * 60 * 1000;
228     private static final int DEFAULT_MAX_PHANTOM_PROCESSES = 32;
229     private static final int DEFAULT_PROCESS_CRASH_COUNT_RESET_INTERVAL = 12 * 60 * 60 * 1000;
230     private static final int DEFAULT_PROCESS_CRASH_COUNT_LIMIT = 12;
231     private static final int DEFAULT_BOOT_TIME_TEMP_ALLOWLIST_DURATION = 20 * 1000;
232     private static final long DEFAULT_FG_TO_BG_FGS_GRACE_DURATION = 5 * 1000;
233     private static final long DEFAULT_VISIBLE_TO_INVISIBLE_UIJ_SCHEDULE_GRACE_DURATION =
234             DEFAULT_FG_TO_BG_FGS_GRACE_DURATION;
235     private static final int DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS = 10 * 1000;
236     private static final float DEFAULT_FGS_ATOM_SAMPLE_RATE = 1; // 100 %
237     private static final float DEFAULT_FGS_START_ALLOWED_LOG_SAMPLE_RATE = 0.25f; // 25%
238     private static final float DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE = 1; // 100%
239     private static final long DEFAULT_PROCESS_KILL_TIMEOUT_MS = 10 * 1000;
240     private static final long DEFAULT_NETWORK_ACCESS_TIMEOUT_MS = 200; // 0.2 sec
241     private static final long DEFAULT_MAX_PREVIOUS_TIME = 60 * 1000; // 60s
242 
243     static final long DEFAULT_BACKGROUND_SETTLE_TIME = 60 * 1000;
244     static final long DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME_MS = 60 * 1000;
245     static final boolean DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE = false;
246 
247     static final int DEFAULT_MAX_SERVICE_CONNECTIONS_PER_PROCESS = 3000;
248 
249     private static final boolean DEFAULT_USE_TIERED_CACHED_ADJ = false;
250     private static final long DEFAULT_TIERED_CACHED_ADJ_DECAY_TIME = 60 * 1000;
251 
252     /**
253      * The default value to {@link #KEY_ENABLE_NEW_OOMADJ}.
254      */
255     private static final boolean DEFAULT_ENABLE_NEW_OOM_ADJ = Flags.oomadjusterCorrectnessRewrite();
256 
257     /**
258      * The default value to {@link #KEY_ENABLE_BATCHING_OOM_ADJ}.
259      */
260     private static final boolean DEFAULT_ENABLE_BATCHING_OOM_ADJ = Flags.batchingOomAdj();
261 
262     /**
263      * The default value to {@link #KEY_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION}.
264      */
265     private static final long DEFAULT_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION = 1000L;
266 
267     /**
268      * Same as {@link TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED}
269      */
270     private static final int
271             DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR = 1;
272     private static final boolean DEFAULT_FGS_ALLOW_OPT_OUT = false;
273 
274     private static final boolean DEFAULT_SYSTEM_EXEMPT_POWER_RESTRICTIONS_ENABLED = true;
275 
276     /**
277      * The extra delays we're putting to service restarts, based on current memory pressure.
278      */
279     private static final long DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_NORMAL_MEM = 0; // ms
280     private static final long DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_MODERATE_MEM = 10000; // ms
281     private static final long DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_LOW_MEM = 20000; // ms
282     private static final long DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_CRITICAL_MEM = 30000; // ms
283     private static final long[] DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE  = {
284         DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_NORMAL_MEM,
285         DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_MODERATE_MEM,
286         DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_LOW_MEM,
287         DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_CRITICAL_MEM,
288     };
289 
290     /**
291      * Whether or not to enable the extra delays to service restarts on memory pressure.
292      */
293     private static final boolean DEFAULT_ENABLE_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE = true;
294     private static final boolean DEFAULT_ENABLE_COMPONENT_ALIAS = false;
295     private static final String DEFAULT_COMPONENT_ALIAS_OVERRIDES = "";
296 
297     private static final int DEFAULT_DEFER_BOOT_COMPLETED_BROADCAST =
298              DEFER_BOOT_COMPLETED_BROADCAST_BACKGROUND_RESTRICTED_ONLY
299              | DEFER_BOOT_COMPLETED_BROADCAST_TARGET_T_ONLY;
300 
301     private static final int DEFAULT_SERVICE_START_FOREGROUND_TIMEOUT_MS = 30 * 1000;
302 
303     private static final int DEFAULT_SERVICE_START_FOREGROUND_ANR_DELAY_MS = 10 * 1000;
304 
305     private static final long DEFAULT_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS = 15 * 1000;
306 
307     /**
308      * Default value to {@link #SERVICE_TIMEOUT}.
309      */
310     private static final long DEFAULT_SERVICE_TIMEOUT = 20 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
311 
312     /**
313      * Default value to {@link #SERVICE_BACKGROUND_TIMEOUT}.
314      */
315     private static final long DEFAULT_SERVICE_BACKGROUND_TIMEOUT = DEFAULT_SERVICE_TIMEOUT * 10;
316 
317     /**
318      * Maximum number of cached processes.
319      */
320     private static final String KEY_MAX_CACHED_PROCESSES = "max_cached_processes";
321 
322     /**
323      * Maximum number of cached processes.
324      */
325     private static final String KEY_MAX_PHANTOM_PROCESSES = "max_phantom_processes";
326 
327     /**
328      * Enables proactive killing of cached apps
329      */
330     private static final String KEY_PROACTIVE_KILLS_ENABLED = "proactive_kills_enabled";
331 
332     /**
333       * Trim LRU cached app when swap falls below this minimum percentage.
334       *
335       * Depends on KEY_PROACTIVE_KILLS_ENABLED
336       */
337     private static final String KEY_LOW_SWAP_THRESHOLD_PERCENT = "low_swap_threshold_percent";
338 
339     /**
340      * Default value for mFlagBackgroundActivityStartsEnabled if not explicitly set in
341      * Settings.Global. This allows it to be set experimentally unless it has been
342      * enabled/disabled in developer options. Defaults to false.
343      */
344     private static final String KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED =
345             "default_background_activity_starts_enabled";
346 
347     /**
348      * Default value for mFlagBackgroundFgsStartRestrictionEnabled if not explicitly set in
349      * Settings.Global.
350      */
351     private static final String KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED =
352             "default_background_fgs_starts_restriction_enabled";
353 
354     /**
355      * Default value for mFlagFgsStartRestrictionEnabled if not explicitly set in
356      * Settings.Global.
357      */
358     private static final String KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED =
359             "default_fgs_starts_restriction_enabled";
360 
361     /**
362      * Default value for mFgsStartRestrictionNotificationEnabled if not explicitly set in
363      * Settings.Global.
364      */
365     private static final String KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED =
366             "default_fgs_starts_restriction_notification_enabled";
367 
368     /**
369      * Default value for mFgsStartRestrictionCheckCallerTargetSdk if not explicitly set in
370      * Settings.Global.
371      */
372     private static final String KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK =
373             "default_fgs_starts_restriction_check_caller_target_sdk";
374 
375     /**
376      * Whether FGS notification display is deferred following the transition into
377      * the foreground state.  Default behavior is {@code true} unless overridden.
378      */
379     private static final String KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED =
380             "deferred_fgs_notifications_enabled";
381 
382     /** Whether FGS notification deferral applies only to those apps targeting
383      * API version S or higher.  Default is {@code true} unless overidden.
384      */
385     private static final String KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED =
386             "deferred_fgs_notifications_api_gated";
387 
388     /**
389      * Time in milliseconds to defer display of FGS notifications following the
390      * transition into the foreground state.  Default is 10_000 (ten seconds)
391      * unless overridden.
392      */
393     private static final String KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL =
394             "deferred_fgs_notification_interval";
395 
396     /**
397      * Same as {@link #KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL} but for "short FGS".
398      */
399     private static final String KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL_FOR_SHORT =
400             "deferred_fgs_notification_interval_for_short";
401 
402     /**
403      * Time in milliseconds; once an FGS notification for a given uid has been
404      * deferred, no subsequent FGS notification from that uid will be deferred
405      * until this amount of time has passed.  Default is two minutes
406      * (2 * 60 * 1000) unless overridden.
407      */
408     private static final String KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME =
409             "deferred_fgs_notification_exclusion_time";
410 
411     /**
412      * Same as {@link #KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME} but for "short FGS".
413      */
414     private static final String KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME_FOR_SHORT =
415             "deferred_fgs_notification_exclusion_time_for_short";
416 
417     /**
418      * Default value for mFlagSystemExemptPowerRestrictionEnabled.
419      */
420     private static final String KEY_SYSTEM_EXEMPT_POWER_RESTRICTIONS_ENABLED =
421             "system_exempt_power_restrictions_enabled";
422 
423     /**
424      * Default value for mPushMessagingOverQuotaBehavior if not explicitly set in
425      * Settings.Global.
426      */
427     private static final String KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR =
428             "push_messaging_over_quota_behavior";
429 
430     /**
431      * Time in milliseconds; the allowed duration from a process is killed until it's really gone.
432      */
433     private static final String KEY_PROCESS_KILL_TIMEOUT = "process_kill_timeout";
434 
435     /**
436      * {@code true} to send in-flight alarm broadcasts ahead of non-alarms; {@code false}
437      * to queue alarm broadcasts identically to non-alarms [i.e. the pre-U behavior]; or
438      * {@code null} or empty string in order to fall back to whatever the build-time default
439      * was for the device.
440      */
441     private static final String KEY_PRIORITIZE_ALARM_BROADCASTS = "prioritize_alarm_broadcasts";
442 
443     private static final String KEY_DEFER_BOOT_COMPLETED_BROADCAST =
444             "defer_boot_completed_broadcast";
445 
446     private static final String KEY_SERVICE_START_FOREGROUND_TIMEOUT_MS =
447             "service_start_foreground_timeout_ms";
448 
449     private static final String KEY_SERVICE_START_FOREGROUND_ANR_DELAY_MS =
450             "service_start_foreground_anr_delay_ms";
451 
452     private static final String KEY_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS =
453             "service_bind_almost_perceptible_timeout_ms";
454 
455     private static final String KEY_MAX_SERVICE_CONNECTIONS_PER_PROCESS =
456             "max_service_connections_per_process";
457 
458     private static final String KEY_PROC_STATE_DEBUG_UIDS = "proc_state_debug_uids";
459 
460     /**
461      * UIDs we want to print detailed info in OomAdjuster.
462      * It's only used for debugging, and it's almost never updated, so we just create a new
463      * array when it's changed to avoid synchronization.
464      */
465     volatile SparseBooleanArray mProcStateDebugUids = new SparseBooleanArray(0);
466     volatile boolean mEnableProcStateStacktrace = false;
467     volatile int mProcStateDebugSetProcStateDelay = 0;
468     volatile int mProcStateDebugSetUidStateDelay = 0;
469 
470     // Maximum number of cached processes we will allow.
471     public int MAX_CACHED_PROCESSES = DEFAULT_MAX_CACHED_PROCESSES;
472 
473     // This is the amount of time we allow an app to settle after it goes into the background,
474     // before we start restricting what it can do.
475     public long BACKGROUND_SETTLE_TIME = DEFAULT_BACKGROUND_SETTLE_TIME;
476 
477     // The minimum time we allow a foreground service to run with a notification and the
478     // screen on without otherwise telling the user about it.  (If it runs for less than this,
479     // it will still be reported to the user as a running app for at least this amount of time.)
480     public long FGSERVICE_MIN_SHOWN_TIME = DEFAULT_FGSERVICE_MIN_SHOWN_TIME;
481 
482     // If a foreground service is shown for less than FGSERVICE_MIN_SHOWN_TIME, we will display
483     // the background app running notification about it for at least this amount of time (if it
484     // is larger than the remaining shown time).
485     public long FGSERVICE_MIN_REPORT_TIME = DEFAULT_FGSERVICE_MIN_REPORT_TIME;
486 
487     // The minimum amount of time the foreground service needs to have remain being shown
488     // before the screen goes on for us to consider it not worth showing to the user.  That is
489     // if an app has a foreground service that stops itself this amount of time or more before
490     // the user turns on the screen, we will just let it go without the user being told about it.
491     public long FGSERVICE_SCREEN_ON_BEFORE_TIME = DEFAULT_FGSERVICE_SCREEN_ON_BEFORE_TIME;
492 
493     // The minimum amount of time a foreground service should remain reported to the user if
494     // it is stopped when the screen turns on.  This is the time from when the screen turns
495     // on until we will stop reporting it.
496     public long FGSERVICE_SCREEN_ON_AFTER_TIME = DEFAULT_FGSERVICE_SCREEN_ON_AFTER_TIME;
497 
498     // Allow-list for FGS types that are allowed to start from BOOT_COMPLETED.
499     public int FGS_BOOT_COMPLETED_ALLOWLIST = DEFAULT_FGS_BOOT_COMPLETED_ALLOWLIST;
500 
501     // How long we will retain processes hosting content providers in the "last activity"
502     // state before allowing them to drop down to the regular cached LRU list.  This is
503     // to avoid thrashing of provider processes under low memory situations.
504     long CONTENT_PROVIDER_RETAIN_TIME = DEFAULT_CONTENT_PROVIDER_RETAIN_TIME;
505 
506     // How long to wait after going idle before forcing apps to GC.
507     long GC_TIMEOUT = DEFAULT_GC_TIMEOUT;
508 
509     // The minimum amount of time between successive GC requests for a process.
510     long GC_MIN_INTERVAL = DEFAULT_GC_MIN_INTERVAL;
511 
512     /**
513      * Whether or not Background Check should be forced on any apps in the
514      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RESTRICTED} bucket,
515      * regardless of target SDK version.
516      */
517     boolean FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS =
518             DEFAULT_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS;
519 
520     // The minimum amount of time between successive PSS requests for a process.
521     long FULL_PSS_MIN_INTERVAL = DEFAULT_FULL_PSS_MIN_INTERVAL;
522 
523     // The minimum amount of time between successive PSS requests for a process
524     // when the request is due to the memory state being lowered.
525     long FULL_PSS_LOWERED_INTERVAL = DEFAULT_FULL_PSS_LOWERED_INTERVAL;
526 
527     // The minimum sample duration we will allow before deciding we have
528     // enough data on CPU usage to start killing things.
529     long POWER_CHECK_INTERVAL = DEFAULT_POWER_CHECK_INTERVAL;
530 
531     // The maximum CPU (as a percentage) a process is allowed to use over the first
532     // power check interval that it is cached.
533     int POWER_CHECK_MAX_CPU_1 = DEFAULT_POWER_CHECK_MAX_CPU_1;
534 
535     // The maximum CPU (as a percentage) a process is allowed to use over the second
536     // power check interval that it is cached.  The home app will never check for less
537     // CPU than this (it will not test against the 3 or 4 levels).
538     int POWER_CHECK_MAX_CPU_2 = DEFAULT_POWER_CHECK_MAX_CPU_2;
539 
540     // The maximum CPU (as a percentage) a process is allowed to use over the third
541     // power check interval that it is cached.
542     int POWER_CHECK_MAX_CPU_3 = DEFAULT_POWER_CHECK_MAX_CPU_3;
543 
544     // The maximum CPU (as a percentage) a process is allowed to use over the fourth
545     // power check interval that it is cached.
546     int POWER_CHECK_MAX_CPU_4 = DEFAULT_POWER_CHECK_MAX_CPU_4;
547 
548     // This is the amount of time an app needs to be running a foreground service before
549     // we will consider it to be doing interaction for usage stats.
550     // Only used for apps targeting pre-S versions.
551     long SERVICE_USAGE_INTERACTION_TIME_PRE_S = DEFAULT_SERVICE_USAGE_INTERACTION_TIME_PRE_S;
552 
553     // This is the amount of time an app needs to be running a foreground service before
554     // we will consider it to be doing interaction for usage stats.
555     // Only used for apps targeting versions S and above.
556     long SERVICE_USAGE_INTERACTION_TIME_POST_S = DEFAULT_SERVICE_USAGE_INTERACTION_TIME_POST_S;
557 
558     // Maximum amount of time we will allow to elapse before re-reporting usage stats
559     // interaction with foreground processes.
560     // Only used for apps targeting pre-S versions.
561     long USAGE_STATS_INTERACTION_INTERVAL_PRE_S = DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_PRE_S;
562 
563     // Maximum amount of time we will allow to elapse before re-reporting usage stats
564     // interaction with foreground processes.
565     // Only used for apps targeting versions S and above.
566     long USAGE_STATS_INTERACTION_INTERVAL_POST_S = DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_POST_S;
567 
568     // How long a service needs to be running until restarting its process
569     // is no longer considered to be a relaunch of the service.
570     public long SERVICE_RESTART_DURATION = DEFAULT_SERVICE_RESTART_DURATION;
571 
572     // How long a service needs to be running until it will start back at
573     // SERVICE_RESTART_DURATION after being killed.
574     public long SERVICE_RESET_RUN_DURATION = DEFAULT_SERVICE_RESET_RUN_DURATION;
575 
576     // Multiplying factor to increase restart duration time by, for each time
577     // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
578     public int SERVICE_RESTART_DURATION_FACTOR = DEFAULT_SERVICE_RESTART_DURATION_FACTOR;
579 
580     // The minimum amount of time between restarting services that we allow.
581     // That is, when multiple services are restarting, we won't allow each
582     // to restart less than this amount of time from the last one.
583     public long SERVICE_MIN_RESTART_TIME_BETWEEN = DEFAULT_SERVICE_MIN_RESTART_TIME_BETWEEN;
584 
585     // How long we wait for a service to finish executing.
586     long SERVICE_TIMEOUT = DEFAULT_SERVICE_TIMEOUT;
587 
588     // How long we wait for a service to finish executing.
589     long SERVICE_BACKGROUND_TIMEOUT = DEFAULT_SERVICE_BACKGROUND_TIMEOUT;
590 
591     // Maximum amount of time for there to be no activity on a service before
592     // we consider it non-essential and allow its process to go on the
593     // LRU background list.
594     public long MAX_SERVICE_INACTIVITY = DEFAULT_MAX_SERVICE_INACTIVITY;
595 
596     // How long we wait for a background started service to stop itself before
597     // allowing the next pending start to run.
598     public long BG_START_TIMEOUT = DEFAULT_BG_START_TIMEOUT;
599 
600     // For a service that has been allowed to start background activities, how long after it started
601     // its process can start a background activity.
602     public long SERVICE_BG_ACTIVITY_START_TIMEOUT = DEFAULT_SERVICE_BG_ACTIVITY_START_TIMEOUT;
603 
604     // Initial backoff delay for retrying bound foreground services
605     public long BOUND_SERVICE_CRASH_RESTART_DURATION = DEFAULT_BOUND_SERVICE_CRASH_RESTART_DURATION;
606 
607     // Maximum number of retries for bound foreground services that crash soon after start
608     public long BOUND_SERVICE_MAX_CRASH_RETRY = DEFAULT_BOUND_SERVICE_CRASH_MAX_RETRY;
609 
610     // Indicates if the processes need to be started asynchronously.
611     public boolean FLAG_PROCESS_START_ASYNC = DEFAULT_PROCESS_START_ASYNC;
612 
613     // The minimum time we allow between requests for the MemoryInfo of a process to
614     // throttle requests from apps.
615     public long MEMORY_INFO_THROTTLE_TIME = DEFAULT_MEMORY_INFO_THROTTLE_TIME;
616 
617     // Allow app just moving from TOP to FOREGROUND_SERVICE to stay in a higher adj value for
618     // this long.
619     public volatile long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION;
620 
621     /**
622      * Allow app just leaving TOP with an already running ALMOST_PERCEPTIBLE service to stay in
623      * a higher adj value for this long.
624      */
625     public long TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION =
626             DEFAULT_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION;
627 
628     // How long a process can remain at previous oom_adj before dropping to cached
629     public static long MAX_PREVIOUS_TIME = DEFAULT_MAX_PREVIOUS_TIME;
630 
631     /**
632      * The minimum time we allow between crashes, for us to consider this
633      * application to be bad and stop its services and reject broadcasts.
634      * A reasonable interval here would be anything between 1-3 minutes.
635      */
636     public static int MIN_CRASH_INTERVAL = DEFAULT_MIN_CRASH_INTERVAL;
637 
638     /**
639      * We will allow for a maximum number of {@link PROCESS_CRASH_COUNT_LIMIT} crashes within this
640      * time period before we consider the application to be bad and stop services and reject
641      * broadcasts.
642      * A reasonable reset interval here would be anything between 10-20 hours along with a crash
643      * count limit of 10-20 crashes.
644      */
645     static long PROCESS_CRASH_COUNT_RESET_INTERVAL = DEFAULT_PROCESS_CRASH_COUNT_RESET_INTERVAL;
646 
647     /**
648      * The maximum number of crashes allowed within {@link PROCESS_CRASH_COUNT_RESET_INTERVAL_MS}
649      * before we consider the application to be bad and stop services and reject broadcasts.
650      * A reasonable crash count limit here would be anything between 10-20 crashes along with a
651      * reset interval of 10-20 hours.
652      */
653     static int PROCESS_CRASH_COUNT_LIMIT = DEFAULT_PROCESS_CRASH_COUNT_LIMIT;
654 
655     // Indicates whether the activity starts logging is enabled.
656     // Controlled by Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED
657     volatile boolean mFlagActivityStartsLoggingEnabled;
658 
659     // Indicates whether the background activity starts is enabled.
660     // Controlled by Settings.Global.BACKGROUND_ACTIVITY_STARTS_ENABLED.
661     // If not set explicitly the default is controlled by DeviceConfig.
662     volatile boolean mFlagBackgroundActivityStartsEnabled;
663 
664     // Indicates whether foreground service starts logging is enabled.
665     // Controlled by Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED
666     volatile boolean mFlagForegroundServiceStartsLoggingEnabled;
667 
668     // Indicates whether the foreground service background start restriction is enabled.
669     // When the restriction is enabled, foreground service started from background will not have
670     // while-in-use permissions like location, camera and microphone. (The foreground service can be
671     // started, the restriction is on while-in-use permissions.)
672     volatile boolean mFlagBackgroundFgsStartRestrictionEnabled = true;
673 
674     // Indicates whether the foreground service background start restriction is enabled for
675     // apps targeting S+.
676     // When the restriction is enabled, service is not allowed to startForeground from background
677     // at all.
678     volatile boolean mFlagFgsStartRestrictionEnabled = true;
679 
680     // Whether to display a notification when a service is restricted from startForeground due to
681     // foreground service background start restriction.
682     volatile boolean mFgsStartRestrictionNotificationEnabled = false;
683 
684     // Indicates whether PSS profiling in AppProfiler is force-enabled, even if RSS is used by
685     // default. Controlled by Settings.Global.FORCE_ENABLE_PSS_PROFILING
686     volatile boolean mForceEnablePssProfiling = false;
687 
688     /**
689      * Indicates whether the foreground service background start restriction is enabled for
690      * caller app that is targeting S+.
691      * This is in addition to check of {@link #mFlagFgsStartRestrictionEnabled} flag.
692      */
693     volatile boolean mFgsStartRestrictionCheckCallerTargetSdk = true;
694 
695     // Whether we defer FGS notifications a few seconds following their transition to
696     // the foreground state.  Applies only to S+ apps; enabled by default.
697     volatile boolean mFlagFgsNotificationDeferralEnabled = true;
698 
699     // Restrict FGS notification deferral policy to only those apps that target
700     // API version S or higher.  Disabled by default; set to "true" to force
701     // legacy app FGS notifications to display immediately in all cases.
702     volatile boolean mFlagFgsNotificationDeferralApiGated = false;
703 
704     // Time in milliseconds to defer FGS notifications after their transition to
705     // the foreground state.
706     volatile long mFgsNotificationDeferralInterval = 10_000;
707 
708     /**
709      * Same as {@link #mFgsNotificationDeferralInterval} but used for "short FGS".
710      */
711     volatile long mFgsNotificationDeferralIntervalForShort = mFgsNotificationDeferralInterval;
712 
713     // Rate limit: minimum time after an app's FGS notification is deferred
714     // before another FGS notification from that app can be deferred.
715     volatile long mFgsNotificationDeferralExclusionTime = 2 * 60 * 1000L;
716 
717     /**
718      * Same as {@link #mFgsNotificationDeferralExclusionTime} but used for "short FGS".
719      */
720     volatile long mFgsNotificationDeferralExclusionTimeForShort =
721             mFgsNotificationDeferralExclusionTime;
722 
723     // Indicates whether the system-applied exemption from all power restrictions is enabled.
724     // When the exemption is enabled, any app which has the OP_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS
725     // app op will be exempt from all power-related restrictions, including app standby
726     // and doze. In addition, the app will be able to start foreground services from the background,
727     // and the user will not be able to stop foreground services run by the app.
728     volatile boolean mFlagSystemExemptPowerRestrictionsEnabled = true;
729 
730     /**
731      * When server pushing message is over the quote, select one of the temp allow list type as
732      * defined in {@link PowerExemptionManager.TempAllowListType}
733      */
734     volatile @PowerExemptionManager.TempAllowListType int mPushMessagingOverQuotaBehavior =
735             DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR;
736 
737     /*
738      * At boot time, broadcast receiver ACTION_BOOT_COMPLETED, ACTION_LOCKED_BOOT_COMPLETED and
739      * ACTION_PRE_BOOT_COMPLETED are temp allowlisted to start FGS for a duration of time in
740      * milliseconds.
741      */
742     volatile long mBootTimeTempAllowlistDuration = DEFAULT_BOOT_TIME_TEMP_ALLOWLIST_DURATION;
743 
744     /**
745      * The grace period in milliseconds to allow a process to start FGS from background after
746      * switching from foreground to background; currently it's only applicable to its activities.
747      */
748     volatile long mFgToBgFgsGraceDuration = DEFAULT_FG_TO_BG_FGS_GRACE_DURATION;
749 
750     /**
751      * The grace period in milliseconds to allow a process to schedule a
752      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}
753      * after switching from visible to a non-visible state.
754      * Currently it's only applicable to its activities.
755      */
756     volatile long mVisibleToInvisibleUijScheduleGraceDurationMs =
757             DEFAULT_VISIBLE_TO_INVISIBLE_UIJ_SCHEDULE_GRACE_DURATION;
758 
759     /**
760      * When service started from background, before the timeout it can be promoted to FGS by calling
761      * Service.startForeground().
762      */
763     volatile long mFgsStartForegroundTimeoutMs = DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS;
764 
765     /**
766      * Sample rate for the FGS atom.
767      *
768      * If the value is 0.1, 10% of the installed packages would be sampled.
769      */
770     volatile float mFgsAtomSampleRate = DEFAULT_FGS_ATOM_SAMPLE_RATE;
771 
772     /**
773      * Sample rate for the allowed FGS start WTF logs.
774      *
775      * If the value is 0.1, 10% of the logs would be sampled.
776      */
777     volatile float mFgsStartAllowedLogSampleRate = DEFAULT_FGS_START_ALLOWED_LOG_SAMPLE_RATE;
778 
779     /**
780      * Sample rate for the denied FGS start WTF logs.
781      *
782      * If the value is 0.1, 10% of the logs would be sampled.
783      */
784     volatile float mFgsStartDeniedLogSampleRate = DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE;
785 
786     /**
787      * Whether or not to kill apps in background restricted mode and it's cached, its UID state is
788      * idle.
789      */
790     volatile boolean mKillBgRestrictedAndCachedIdle = DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE;
791 
792     /**
793      * The amount of time we allow an app in background restricted mode to settle after it goes
794      * into the cached & UID idle, before we decide to kill it.
795      */
796     volatile long mKillBgRestrictedAndCachedIdleSettleTimeMs =
797             DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME_MS;
798 
799     /**
800      * The allowed duration from a process is killed until it's really gone.
801      */
802     volatile long mProcessKillTimeoutMs = DEFAULT_PROCESS_KILL_TIMEOUT_MS;
803 
804     /**
805      * Whether to allow "opt-out" from the foreground service restrictions.
806      * (https://developer.android.com/about/versions/12/foreground-services)
807      */
808     volatile boolean mFgsAllowOptOut = DEFAULT_FGS_ALLOW_OPT_OUT;
809 
810     /*
811      * The extra delays we're putting to service restarts, based on current memory pressure.
812      */
813     @GuardedBy("mService")
814     long[] mExtraServiceRestartDelayOnMemPressure =
815             DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE;
816 
817     /**
818      * Whether or not to enable the extra delays to service restarts on memory pressure.
819      */
820     @GuardedBy("mService")
821     boolean mEnableExtraServiceRestartDelayOnMemPressure =
822             DEFAULT_ENABLE_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE;
823 
824     /**
825      * Whether to enable "component alias" experimental feature. This can only be enabled
826      * on userdebug or eng builds.
827      */
828     volatile boolean mEnableComponentAlias = DEFAULT_ENABLE_COMPONENT_ALIAS;
829 
830     /**
831      * Where or not to defer LOCKED_BOOT_COMPLETED and BOOT_COMPLETED broadcasts until the first
832      * time the process of the UID is started.
833      * Defined in {@link BroadcastConstants#DeferBootCompletedBroadcastType}
834      */
835     @GuardedBy("mService")
836     volatile @BroadcastConstants.DeferBootCompletedBroadcastType int mDeferBootCompletedBroadcast =
837             DEFAULT_DEFER_BOOT_COMPLETED_BROADCAST;
838 
839     /**
840      * Whether alarm broadcasts are delivered immediately, or queued along with the rest
841      * of the pending ordered broadcasts.
842      */
843     volatile boolean mPrioritizeAlarmBroadcasts = DEFAULT_PRIORITIZE_ALARM_BROADCASTS;
844 
845     /**
846      * How long the Context.startForegroundService() grace period is to get around to
847      * calling Service.startForeground() before we generate ANR.
848      */
849     volatile int mServiceStartForegroundTimeoutMs = DEFAULT_SERVICE_START_FOREGROUND_TIMEOUT_MS;
850 
851     /**
852      *  How long from Service.startForeground() timed-out to when we generate ANR of the user app.
853      *  This delay is after the timeout {@link #mServiceStartForegroundTimeoutMs}.
854      */
855     volatile int mServiceStartForegroundAnrDelayMs =
856             DEFAULT_SERVICE_START_FOREGROUND_ANR_DELAY_MS;
857 
858     /**
859      * How long the grace period is from starting an almost perceptible service to a successful
860      * binding before we stop considering it an almost perceptible service.
861      */
862     volatile long mServiceBindAlmostPerceptibleTimeoutMs =
863             DEFAULT_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS;
864 
865     /**
866      * Defines component aliases. Format
867      * ComponentName ":" ComponentName ( "," ComponentName ":" ComponentName )*
868      */
869     volatile String mComponentAliasOverrides = DEFAULT_COMPONENT_ALIAS_OVERRIDES;
870 
871     /**
872      *  The max number of outgoing ServiceConnection a process is allowed to bind to a service
873      *  (or multiple services).
874      */
875     volatile int mMaxServiceConnectionsPerProcess = DEFAULT_MAX_SERVICE_CONNECTIONS_PER_PROCESS;
876 
877     private final ActivityManagerService mService;
878     private ContentResolver mResolver;
879     private final KeyValueListParser mParser = new KeyValueListParser(',');
880 
881     private int mOverrideMaxCachedProcesses = -1;
882     private final int mCustomizedMaxCachedProcesses;
883 
884     // The maximum number of cached processes we will keep around before killing them.
885     // NOTE: this constant is *only* a control to not let us go too crazy with
886     // keeping around processes on devices with large amounts of RAM.  For devices that
887     // are tighter on RAM, the out of memory killer is responsible for killing background
888     // processes as RAM is needed, and we should *never* be relying on this limit to
889     // kill them.  Also note that this limit only applies to cached background processes;
890     // we have no limit on the number of service, visible, foreground, or other such
891     // processes and the number of those processes does not count against the cached
892     // process limit. This will be initialized in the constructor.
893     public int CUR_MAX_CACHED_PROCESSES;
894 
895     // The maximum number of empty app processes we will let sit around.  This will be
896     // initialized in the constructor.
897     public int CUR_MAX_EMPTY_PROCESSES;
898 
899     /** @see #mNoKillCachedProcessesUntilBootCompleted */
900     private static final String KEY_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED =
901             "no_kill_cached_processes_until_boot_completed";
902 
903     /** @see #mNoKillCachedProcessesPostBootCompletedDurationMillis */
904     private static final String KEY_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS =
905             "no_kill_cached_processes_post_boot_completed_duration_millis";
906 
907     /** @see #mNoKillCachedProcessesUntilBootCompleted */
908     private static final boolean DEFAULT_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED = true;
909 
910     /** @see #mNoKillCachedProcessesPostBootCompletedDurationMillis */
911     private static final long
912             DEFAULT_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS = 600_000;
913 
914     /**
915      * If true, do not kill excessive cached processes proactively, until user-0 is unlocked.
916      * @see #mNoKillCachedProcessesPostBootCompletedDurationMillis
917      */
918     volatile boolean mNoKillCachedProcessesUntilBootCompleted =
919             DEFAULT_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED;
920 
921     /**
922      * Do not kill excessive cached processes proactively, for this duration after each user is
923      * unlocked.
924      * Note we don't proactively kill extra cached processes after this. The next oomadjuster pass
925      * will naturally do it.
926      */
927     volatile long mNoKillCachedProcessesPostBootCompletedDurationMillis =
928             DEFAULT_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS;
929 
930     // The number of empty apps at which we don't consider it necessary to do
931     // memory trimming.
932     public int CUR_TRIM_EMPTY_PROCESSES = computeEmptyProcessLimit(MAX_CACHED_PROCESSES) / 2;
933 
934     // The number of cached at which we don't consider it necessary to do
935     // memory trimming.
936     public int CUR_TRIM_CACHED_PROCESSES =
937             (MAX_CACHED_PROCESSES - computeEmptyProcessLimit(MAX_CACHED_PROCESSES)) / 3;
938 
939     /** @see #mNoKillCachedProcessesUntilBootCompleted */
940     private static final String KEY_MAX_EMPTY_TIME_MILLIS =
941             "max_empty_time_millis";
942 
943     private static final long DEFAULT_MAX_EMPTY_TIME_MILLIS = 1000L * 60L * 60L * 1000L;
944 
945     volatile long mMaxEmptyTimeMillis = DEFAULT_MAX_EMPTY_TIME_MILLIS;
946 
947     /**
948      * Packages that can't be killed even if it's requested to be killed on imperceptible.
949      */
950     public ArraySet<String> IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES = new ArraySet<String>();
951 
952     /**
953      * Proc State that can't be killed even if it's requested to be killed on imperceptible.
954      */
955     public ArraySet<Integer> IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES = new ArraySet<Integer>();
956 
957     /**
958      * The threshold for the amount of PendingIntent for each UID, there will be
959      * warning logs if the number goes beyond this threshold.
960      */
961     public int PENDINGINTENT_WARNING_THRESHOLD =  DEFAULT_PENDINGINTENT_WARNING_THRESHOLD;
962 
963     /**
964      * Component names of the services which will keep critical code path of the host warm
965      */
966     public final ArraySet<ComponentName> KEEP_WARMING_SERVICES = new ArraySet<ComponentName>();
967 
968     /**
969      * Maximum number of phantom processes.
970      */
971     public int MAX_PHANTOM_PROCESSES = DEFAULT_MAX_PHANTOM_PROCESSES;
972 
973     private List<String> mDefaultImperceptibleKillExemptPackages;
974     private List<Integer> mDefaultImperceptibleKillExemptProcStates;
975 
976     /**
977      * Indicates the maximum time spent waiting for the network rules to get updated.
978      */
979     volatile long mNetworkAccessTimeoutMs = DEFAULT_NETWORK_ACCESS_TIMEOUT_MS;
980 
981     @SuppressWarnings("unused")
982     private static final int OOMADJ_UPDATE_POLICY_SLOW = 0;
983     private static final int OOMADJ_UPDATE_POLICY_QUICK = 1;
984     private static final int DEFAULT_OOMADJ_UPDATE_POLICY = OOMADJ_UPDATE_POLICY_QUICK;
985 
986     private static final String KEY_OOMADJ_UPDATE_POLICY = "oomadj_update_policy";
987 
988     // Indicate if the oom adjuster should take the quick path to update the oom adj scores,
989     // in which no futher actions will be performed if there are no significant adj/proc state
990     // changes for the specific process; otherwise, use the traditonal slow path which would
991     // keep updating all processes in the LRU list.
992     public boolean OOMADJ_UPDATE_QUICK = DEFAULT_OOMADJ_UPDATE_POLICY == OOMADJ_UPDATE_POLICY_QUICK;
993 
994     private static final long MIN_AUTOMATIC_HEAP_DUMP_PSS_THRESHOLD_BYTES = 100 * 1024; // 100 KB
995 
996     private final boolean mSystemServerAutomaticHeapDumpEnabled;
997 
998     /** Package to report to when the memory usage exceeds the limit. */
999     private final String mSystemServerAutomaticHeapDumpPackageName;
1000 
1001     /** Byte limit for dump heap monitoring. */
1002     private long mSystemServerAutomaticHeapDumpPssThresholdBytes;
1003 
1004     private static final Uri ACTIVITY_MANAGER_CONSTANTS_URI = Settings.Global.getUriFor(
1005                 Settings.Global.ACTIVITY_MANAGER_CONSTANTS);
1006 
1007     private static final Uri ACTIVITY_STARTS_LOGGING_ENABLED_URI = Settings.Global.getUriFor(
1008                 Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED);
1009 
1010     private static final Uri FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI =
1011                 Settings.Global.getUriFor(
1012                         Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED);
1013 
1014     private static final Uri ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI =
1015             Settings.Global.getUriFor(Settings.Global.ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS);
1016 
1017     private static final Uri FORCE_ENABLE_PSS_PROFILING_URI =
1018             Settings.Global.getUriFor(Settings.Global.FORCE_ENABLE_PSS_PROFILING);
1019 
1020     /**
1021      * The threshold to decide if a given association should be dumped into metrics.
1022      */
1023     private static final long DEFAULT_MIN_ASSOC_LOG_DURATION = 5 * 60 * 1000; // 5 mins
1024 
1025     private static final boolean DEFAULT_PROACTIVE_KILLS_ENABLED = false;
1026 
1027     private static final float DEFAULT_LOW_SWAP_THRESHOLD_PERCENT = 0.10f;
1028 
1029     private static final String KEY_MIN_ASSOC_LOG_DURATION = "min_assoc_log_duration";
1030 
1031     public static long MIN_ASSOC_LOG_DURATION = DEFAULT_MIN_ASSOC_LOG_DURATION;
1032 
1033     private static final String KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED =
1034             "binder_heavy_hitter_watcher_enabled";
1035     private static final String KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE =
1036             "binder_heavy_hitter_watcher_batchsize";
1037     private static final String KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD =
1038             "binder_heavy_hitter_watcher_threshold";
1039     private static final String KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED =
1040             "binder_heavy_hitter_auto_sampler_enabled";
1041     private static final String KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE =
1042             "binder_heavy_hitter_auto_sampler_batchsize";
1043     private static final String KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD =
1044             "binder_heavy_hitter_auto_sampler_threshold";
1045 
1046     private final boolean mDefaultBinderHeavyHitterWatcherEnabled;
1047     private final int mDefaultBinderHeavyHitterWatcherBatchSize;
1048     private final float mDefaultBinderHeavyHitterWatcherThreshold;
1049     private final boolean mDefaultBinderHeavyHitterAutoSamplerEnabled;
1050     private final int mDefaultBinderHeavyHitterAutoSamplerBatchSize;
1051     private final float mDefaultBinderHeavyHitterAutoSamplerThreshold;
1052 
1053     public static boolean BINDER_HEAVY_HITTER_WATCHER_ENABLED;
1054     public static int BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE;
1055     public static float BINDER_HEAVY_HITTER_WATCHER_THRESHOLD;
1056     public static boolean BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED;
1057     public static int BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
1058     public static float BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
1059     public static boolean PROACTIVE_KILLS_ENABLED = DEFAULT_PROACTIVE_KILLS_ENABLED;
1060     public static float LOW_SWAP_THRESHOLD_PERCENT = DEFAULT_LOW_SWAP_THRESHOLD_PERCENT;
1061 
1062     /** Timeout for a "short service" FGS, in milliseconds. */
1063     private static final String KEY_SHORT_FGS_TIMEOUT_DURATION =
1064             "short_fgs_timeout_duration";
1065 
1066     /** @see #KEY_SHORT_FGS_TIMEOUT_DURATION */
1067     static final long DEFAULT_SHORT_FGS_TIMEOUT_DURATION = 3 * 60_000;
1068 
1069     /** @see #KEY_SHORT_FGS_TIMEOUT_DURATION */
1070     public volatile long mShortFgsTimeoutDuration = DEFAULT_SHORT_FGS_TIMEOUT_DURATION;
1071 
1072     /**
1073      * If a "short service" doesn't finish within this after the timeout (
1074      * {@link #KEY_SHORT_FGS_TIMEOUT_DURATION}), then we'll lower the procstate.
1075      */
1076     private static final String KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION =
1077             "short_fgs_proc_state_extra_wait_duration";
1078 
1079     /** @see #KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION */
1080     static final long DEFAULT_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION = 5_000;
1081 
1082     /** @see #KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION */
1083     public volatile long mShortFgsProcStateExtraWaitDuration =
1084             DEFAULT_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION;
1085 
1086     /** Timeout for a mediaProcessing FGS, in milliseconds. */
1087     private static final String KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION =
1088             "media_processing_fgs_timeout_duration";
1089 
1090     /** @see #KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION */
1091     static final long DEFAULT_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION = 6 * 60 * 60_000; // 6 hours
1092 
1093     /** @see #KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION */
1094     public volatile long mMediaProcessingFgsTimeoutDuration =
1095             DEFAULT_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION;
1096 
1097     /** Timeout for a dataSync FGS, in milliseconds. */
1098     private static final String KEY_DATA_SYNC_FGS_TIMEOUT_DURATION =
1099             "data_sync_fgs_timeout_duration";
1100 
1101     /** @see #KEY_DATA_SYNC_FGS_TIMEOUT_DURATION */
1102     static final long DEFAULT_DATA_SYNC_FGS_TIMEOUT_DURATION = 6 * 60 * 60_000; // 6 hours
1103 
1104     /** @see #KEY_DATA_SYNC_FGS_TIMEOUT_DURATION */
1105     public volatile long mDataSyncFgsTimeoutDuration = DEFAULT_DATA_SYNC_FGS_TIMEOUT_DURATION;
1106 
1107     /**
1108      * If enabled, when starting an application, the system will wait for a
1109      * {@link ActivityManagerService#finishAttachApplication} from the app before scheduling
1110      * Broadcasts or Services to it.
1111      */
1112     private static final String KEY_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION =
1113             "enable_wait_for_finish_attach_application";
1114 
1115     private static final boolean DEFAULT_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION = true;
1116 
1117     /** @see #KEY_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION */
1118     public volatile boolean mEnableWaitForFinishAttachApplication =
1119             DEFAULT_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION;
1120 
1121     /**
1122      * If a "short service" doesn't finish within this after the timeout (
1123      * {@link #KEY_SHORT_FGS_TIMEOUT_DURATION}), then we'll declare an ANR.
1124      * i.e. if the timeout is 60 seconds, and this ANR extra duration is 5 seconds, then
1125      * the app will be ANR'ed in 65 seconds after a short service starts and it's not stopped.
1126      */
1127     private static final String KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION =
1128             "short_fgs_anr_extra_wait_duration";
1129 
1130     /** @see #KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION */
1131     static final long DEFAULT_SHORT_FGS_ANR_EXTRA_WAIT_DURATION = 10_000;
1132 
1133     /** @see #KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION */
1134     public volatile long mShortFgsAnrExtraWaitDuration =
1135             DEFAULT_SHORT_FGS_ANR_EXTRA_WAIT_DURATION;
1136 
1137     /**
1138      * If a service of a timeout-enforced type doesn't finish within this duration after its
1139      * timeout, then we'll crash the app.
1140      * i.e. if the time limit for a type is 1 hour, and this extra duration is 10 seconds, then
1141      * the app will crash 1 hour and 10 seconds after it started.
1142      */
1143     private static final String KEY_FGS_CRASH_EXTRA_WAIT_DURATION = "fgs_crash_extra_wait_duration";
1144 
1145     /** @see #KEY_FGS_CRASH_EXTRA_WAIT_DURATION */
1146     static final long DEFAULT_FGS_CRASH_EXTRA_WAIT_DURATION = 10_000;
1147 
1148     /** @see #KEY_FGS_CRASH_EXTRA_WAIT_DURATION */
1149     public volatile long mFgsCrashExtraWaitDuration = DEFAULT_FGS_CRASH_EXTRA_WAIT_DURATION;
1150 
1151     /** @see #KEY_USE_TIERED_CACHED_ADJ */
1152     public boolean USE_TIERED_CACHED_ADJ = DEFAULT_USE_TIERED_CACHED_ADJ;
1153 
1154     /** @see #KEY_TIERED_CACHED_ADJ_DECAY_TIME */
1155     public long TIERED_CACHED_ADJ_DECAY_TIME = DEFAULT_TIERED_CACHED_ADJ_DECAY_TIME;
1156 
1157     /** @see #KEY_ENABLE_NEW_OOMADJ */
1158     public boolean ENABLE_NEW_OOMADJ = DEFAULT_ENABLE_NEW_OOM_ADJ;
1159 
1160     /** @see #KEY_ENABLE_BATCHING_OOM_ADJ */
1161     public boolean ENABLE_BATCHING_OOM_ADJ = DEFAULT_ENABLE_BATCHING_OOM_ADJ;
1162 
1163     /** @see #KEY_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION */
1164     public long FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION =
1165             DEFAULT_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION;
1166 
1167     /**
1168      * Indicates whether PSS profiling in AppProfiler is disabled or not.
1169      */
1170     static final String KEY_DISABLE_APP_PROFILER_PSS_PROFILING =
1171             "disable_app_profiler_pss_profiling";
1172 
1173     private final boolean mDefaultDisableAppProfilerPssProfiling;
1174 
1175     public boolean APP_PROFILER_PSS_PROFILING_DISABLED;
1176 
1177     /**
1178      * The modifier used to adjust PSS thresholds in OomAdjuster when RSS is collected instead.
1179      */
1180     static final String KEY_PSS_TO_RSS_THRESHOLD_MODIFIER =
1181             "pss_to_rss_threshold_modifier";
1182 
1183     private final float mDefaultPssToRssThresholdModifier;
1184 
1185     public float PSS_TO_RSS_THRESHOLD_MODIFIER;
1186 
1187     private final OnPropertiesChangedListener mOnDeviceConfigChangedListener =
1188             new OnPropertiesChangedListener() {
1189                 @Override
1190                 public void onPropertiesChanged(Properties properties) {
1191                     for (String name : properties.getKeyset()) {
1192                         if (name == null) {
1193                             return;
1194                         }
1195                         switch (name) {
1196                             case KEY_MAX_CACHED_PROCESSES:
1197                                 updateMaxCachedProcesses();
1198                                 break;
1199                             case KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED:
1200                                 updateBackgroundActivityStarts();
1201                                 break;
1202                             case KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED:
1203                                 updateBackgroundFgsStartsRestriction();
1204                                 break;
1205                             case KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED:
1206                                 updateFgsStartsRestriction();
1207                                 break;
1208                             case KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED:
1209                                 updateFgsStartsRestrictionNotification();
1210                                 break;
1211                             case KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK:
1212                                 updateFgsStartsRestrictionCheckCallerTargetSdk();
1213                                 break;
1214                             case KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED:
1215                                 updateFgsNotificationDeferralEnable();
1216                                 break;
1217                             case KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED:
1218                                 updateFgsNotificationDeferralApiGated();
1219                                 break;
1220                             case KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL:
1221                                 updateFgsNotificationDeferralInterval();
1222                                 break;
1223                             case KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME:
1224                                 updateFgsNotificationDeferralExclusionTime();
1225                                 break;
1226                             case KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL_FOR_SHORT:
1227                                 updateFgsNotificationDeferralIntervalForShort();
1228                                 break;
1229                             case KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME_FOR_SHORT:
1230                                 updateFgsNotificationDeferralExclusionTimeForShort();
1231                                 break;
1232                             case KEY_SYSTEM_EXEMPT_POWER_RESTRICTIONS_ENABLED:
1233                                 updateSystemExemptPowerRestrictionsEnabled();
1234                                 break;
1235                             case KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR:
1236                                 updatePushMessagingOverQuotaBehavior();
1237                                 break;
1238                             case KEY_OOMADJ_UPDATE_POLICY:
1239                                 updateOomAdjUpdatePolicy();
1240                                 break;
1241                             case KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES:
1242                             case KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES:
1243                                 updateImperceptibleKillExemptions();
1244                                 break;
1245                             case KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS:
1246                                 updateForceRestrictedBackgroundCheck();
1247                                 break;
1248                             case KEY_MIN_ASSOC_LOG_DURATION:
1249                                 updateMinAssocLogDuration();
1250                                 break;
1251                             case KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED:
1252                             case KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE:
1253                             case KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD:
1254                             case KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED:
1255                             case KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE:
1256                             case KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD:
1257                                 updateBinderHeavyHitterWatcher();
1258                                 break;
1259                             case KEY_MAX_PHANTOM_PROCESSES:
1260                                 updateMaxPhantomProcesses();
1261                                 break;
1262                             case KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION:
1263                                 updateBootTimeTempAllowListDuration();
1264                                 break;
1265                             case KEY_FG_TO_BG_FGS_GRACE_DURATION:
1266                                 updateFgToBgFgsGraceDuration();
1267                                 break;
1268                             case KEY_VISIBLE_TO_INVISIBLE_UIJ_SCHEDULE_GRACE_DURATION:
1269                                 updateFgToBgFgsGraceDuration();
1270                                 break;
1271                             case KEY_FGS_START_FOREGROUND_TIMEOUT:
1272                                 updateFgsStartForegroundTimeout();
1273                                 break;
1274                             case KEY_FGS_ATOM_SAMPLE_RATE:
1275                                 updateFgsAtomSamplePercent();
1276                                 break;
1277                             case KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE:
1278                                 updateFgsStartAllowedLogSamplePercent();
1279                                 break;
1280                             case KEY_FGS_START_DENIED_LOG_SAMPLE_RATE:
1281                                 updateFgsStartDeniedLogSamplePercent();
1282                                 break;
1283                             case KEY_KILL_BG_RESTRICTED_CACHED_IDLE:
1284                                 updateKillBgRestrictedCachedIdle();
1285                                 break;
1286                             case KEY_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME:
1287                                 updateKillBgRestrictedCachedIdleSettleTime();
1288                                 break;
1289                             case KEY_FGS_ALLOW_OPT_OUT:
1290                                 updateFgsAllowOptOut();
1291                                 break;
1292                             case KEY_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE:
1293                                 updateExtraServiceRestartDelayOnMemPressure();
1294                                 break;
1295                             case KEY_ENABLE_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE:
1296                                 updateEnableExtraServiceRestartDelayOnMemPressure();
1297                                 break;
1298                             case KEY_PROCESS_KILL_TIMEOUT:
1299                                 updateProcessKillTimeout();
1300                                 break;
1301                             case KEY_PRIORITIZE_ALARM_BROADCASTS:
1302                                 updatePrioritizeAlarmBroadcasts();
1303                                 break;
1304                             case KEY_DEFER_BOOT_COMPLETED_BROADCAST:
1305                                 updateDeferBootCompletedBroadcast();
1306                                 break;
1307                             case KEY_SERVICE_START_FOREGROUND_TIMEOUT_MS:
1308                                 updateServiceStartForegroundTimeoutMs();
1309                                 break;
1310                             case KEY_SERVICE_START_FOREGROUND_ANR_DELAY_MS:
1311                                 updateServiceStartForegroundAnrDealyMs();
1312                                 break;
1313                             case KEY_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS:
1314                                 updateServiceBindAlmostPerceptibleTimeoutMs();
1315                                 break;
1316                             case KEY_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED:
1317                                 updateNoKillCachedProcessesUntilBootCompleted();
1318                                 break;
1319                             case KEY_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS:
1320                                 updateNoKillCachedProcessesPostBootCompletedDurationMillis();
1321                                 break;
1322                             case KEY_MAX_EMPTY_TIME_MILLIS:
1323                                 updateMaxEmptyTimeMillis();
1324                                 break;
1325                             case KEY_NETWORK_ACCESS_TIMEOUT_MS:
1326                                 updateNetworkAccessTimeoutMs();
1327                                 break;
1328                             case KEY_MAX_SERVICE_CONNECTIONS_PER_PROCESS:
1329                                 updateMaxServiceConnectionsPerProcess();
1330                                 break;
1331                             case KEY_SHORT_FGS_TIMEOUT_DURATION:
1332                                 updateShortFgsTimeoutDuration();
1333                                 break;
1334                             case KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION:
1335                                 updateShortFgsProcStateExtraWaitDuration();
1336                                 break;
1337                             case KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION:
1338                                 updateMediaProcessingFgsTimeoutDuration();
1339                                 break;
1340                             case KEY_DATA_SYNC_FGS_TIMEOUT_DURATION:
1341                                 updateDataSyncFgsTimeoutDuration();
1342                                 break;
1343                             case KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION:
1344                                 updateShortFgsAnrExtraWaitDuration();
1345                                 break;
1346                             case KEY_FGS_CRASH_EXTRA_WAIT_DURATION:
1347                                 updateFgsCrashExtraWaitDuration();
1348                                 break;
1349                             case KEY_PROACTIVE_KILLS_ENABLED:
1350                                 updateProactiveKillsEnabled();
1351                                 break;
1352                             case KEY_LOW_SWAP_THRESHOLD_PERCENT:
1353                                 updateLowSwapThresholdPercent();
1354                                 break;
1355                             case KEY_TOP_TO_FGS_GRACE_DURATION:
1356                                 updateTopToFgsGraceDuration();
1357                                 break;
1358                             case KEY_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION:
1359                                 updateEnableWaitForFinishAttachApplication();
1360                                 break;
1361                             case KEY_MAX_PREVIOUS_TIME:
1362                                 updateMaxPreviousTime();
1363                                 break;
1364                             case KEY_USE_TIERED_CACHED_ADJ:
1365                             case KEY_TIERED_CACHED_ADJ_DECAY_TIME:
1366                                 updateUseTieredCachedAdj();
1367                                 break;
1368                             case KEY_DISABLE_APP_PROFILER_PSS_PROFILING:
1369                                 updateDisableAppProfilerPssProfiling();
1370                                 break;
1371                             case KEY_PSS_TO_RSS_THRESHOLD_MODIFIER:
1372                                 updatePssToRssThresholdModifier();
1373                                 break;
1374                             case KEY_PROC_STATE_DEBUG_UIDS:
1375                                 updateProcStateDebugUids();
1376                                 break;
1377                             case KEY_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION:
1378                                 updateFollowUpOomAdjUpdateWaitDuration();
1379                                 break;
1380                             default:
1381                                 updateFGSPermissionEnforcementFlagsIfNecessary(name);
1382                                 break;
1383                         }
1384                     }
1385                 }
1386             };
1387 
1388     private final OnPropertiesChangedListener mOnDeviceConfigChangedForComponentAliasListener =
1389             new OnPropertiesChangedListener() {
1390                 @Override
1391                 public void onPropertiesChanged(Properties properties) {
1392                     for (String name : properties.getKeyset()) {
1393                         if (name == null) {
1394                             return;
1395                         }
1396                         switch (name) {
1397                             case KEY_ENABLE_COMPONENT_ALIAS:
1398                             case KEY_COMPONENT_ALIAS_OVERRIDES:
1399                                 updateComponentAliases();
1400                                 break;
1401                             default:
1402                                 break;
1403                         }
1404                     }
1405                 }
1406             };
1407 
ActivityManagerConstants(Context context, ActivityManagerService service, Handler handler)1408     ActivityManagerConstants(Context context, ActivityManagerService service, Handler handler) {
1409         super(handler);
1410         mService = service;
1411         mSystemServerAutomaticHeapDumpEnabled = Build.IS_DEBUGGABLE
1412                 && context.getResources().getBoolean(
1413                 com.android.internal.R.bool.config_debugEnableAutomaticSystemServerHeapDumps);
1414         mSystemServerAutomaticHeapDumpPackageName = context.getPackageName();
1415         mSystemServerAutomaticHeapDumpPssThresholdBytes = Math.max(
1416                 MIN_AUTOMATIC_HEAP_DUMP_PSS_THRESHOLD_BYTES,
1417                 context.getResources().getInteger(
1418                         com.android.internal.R.integer.config_debugSystemServerPssThresholdBytes));
1419         mDefaultImperceptibleKillExemptPackages = Arrays.asList(
1420                 context.getResources().getStringArray(
1421                 com.android.internal.R.array.config_defaultImperceptibleKillingExemptionPkgs));
1422         mDefaultImperceptibleKillExemptProcStates = Arrays.stream(
1423                 context.getResources().getIntArray(
1424                 com.android.internal.R.array.config_defaultImperceptibleKillingExemptionProcStates))
1425                 .boxed().collect(Collectors.toList());
1426         IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.addAll(mDefaultImperceptibleKillExemptPackages);
1427         IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.addAll(mDefaultImperceptibleKillExemptProcStates);
1428         mDefaultBinderHeavyHitterWatcherEnabled = context.getResources().getBoolean(
1429                 com.android.internal.R.bool.config_defaultBinderHeavyHitterWatcherEnabled);
1430         mDefaultBinderHeavyHitterWatcherBatchSize = context.getResources().getInteger(
1431                 com.android.internal.R.integer.config_defaultBinderHeavyHitterWatcherBatchSize);
1432         mDefaultBinderHeavyHitterWatcherThreshold = context.getResources().getFloat(
1433                 com.android.internal.R.dimen.config_defaultBinderHeavyHitterWatcherThreshold);
1434         mDefaultBinderHeavyHitterAutoSamplerEnabled = context.getResources().getBoolean(
1435                 com.android.internal.R.bool.config_defaultBinderHeavyHitterAutoSamplerEnabled);
1436         mDefaultBinderHeavyHitterAutoSamplerBatchSize = context.getResources().getInteger(
1437                 com.android.internal.R.integer.config_defaultBinderHeavyHitterAutoSamplerBatchSize);
1438         mDefaultBinderHeavyHitterAutoSamplerThreshold = context.getResources().getFloat(
1439                 com.android.internal.R.dimen.config_defaultBinderHeavyHitterAutoSamplerThreshold);
1440         BINDER_HEAVY_HITTER_WATCHER_ENABLED = mDefaultBinderHeavyHitterWatcherEnabled;
1441         BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE = mDefaultBinderHeavyHitterWatcherBatchSize;
1442         BINDER_HEAVY_HITTER_WATCHER_THRESHOLD = mDefaultBinderHeavyHitterWatcherThreshold;
1443         BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED = mDefaultBinderHeavyHitterAutoSamplerEnabled;
1444         BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE = mDefaultBinderHeavyHitterAutoSamplerBatchSize;
1445         BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD = mDefaultBinderHeavyHitterAutoSamplerThreshold;
1446         service.scheduleUpdateBinderHeavyHitterWatcherConfig();
1447         KEEP_WARMING_SERVICES.addAll(Arrays.stream(
1448                 context.getResources().getStringArray(
1449                         com.android.internal.R.array.config_keep_warming_services))
1450                 .map(ComponentName::unflattenFromString).collect(Collectors.toSet()));
1451         mCustomizedMaxCachedProcesses = context.getResources().getInteger(
1452                 com.android.internal.R.integer.config_customizedMaxCachedProcesses);
1453         CUR_MAX_CACHED_PROCESSES = mCustomizedMaxCachedProcesses;
1454         CUR_MAX_EMPTY_PROCESSES = computeEmptyProcessLimit(CUR_MAX_CACHED_PROCESSES);
1455 
1456         final int rawMaxEmptyProcesses = computeEmptyProcessLimit(
1457                 Integer.min(CUR_MAX_CACHED_PROCESSES, MAX_CACHED_PROCESSES));
1458         CUR_TRIM_EMPTY_PROCESSES = rawMaxEmptyProcesses / 2;
1459         CUR_TRIM_CACHED_PROCESSES = (Integer.min(CUR_MAX_CACHED_PROCESSES, MAX_CACHED_PROCESSES)
1460                     - rawMaxEmptyProcesses) / 3;
1461         loadNativeBootDeviceConfigConstants();
1462         mDefaultDisableAppProfilerPssProfiling = context.getResources().getBoolean(
1463                 R.bool.config_am_disablePssProfiling);
1464         APP_PROFILER_PSS_PROFILING_DISABLED = mDefaultDisableAppProfilerPssProfiling;
1465 
1466         mDefaultPssToRssThresholdModifier = context.getResources().getFloat(
1467                 com.android.internal.R.dimen.config_am_pssToRssThresholdModifier);
1468         PSS_TO_RSS_THRESHOLD_MODIFIER = mDefaultPssToRssThresholdModifier;
1469     }
1470 
start(ContentResolver resolver)1471     public void start(ContentResolver resolver) {
1472         mResolver = resolver;
1473         mResolver.registerContentObserver(ACTIVITY_MANAGER_CONSTANTS_URI, false, this);
1474         mResolver.registerContentObserver(ACTIVITY_STARTS_LOGGING_ENABLED_URI, false, this);
1475         mResolver.registerContentObserver(FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI,
1476                 false, this);
1477         if (mSystemServerAutomaticHeapDumpEnabled) {
1478             mResolver.registerContentObserver(ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI,
1479                     false, this);
1480         }
1481         mResolver.registerContentObserver(FORCE_ENABLE_PSS_PROFILING_URI, false, this);
1482         updateConstants();
1483         if (mSystemServerAutomaticHeapDumpEnabled) {
1484             updateEnableAutomaticSystemServerHeapDumps();
1485         }
1486         DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1487                 ActivityThread.currentApplication().getMainExecutor(),
1488                 mOnDeviceConfigChangedListener);
1489         DeviceConfig.addOnPropertiesChangedListener(
1490                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS,
1491                 ActivityThread.currentApplication().getMainExecutor(),
1492                 mOnDeviceConfigChangedForComponentAliasListener);
1493         loadDeviceConfigConstants();
1494         // The following read from Settings.
1495         updateActivityStartsLoggingEnabled();
1496         updateForegroundServiceStartsLoggingEnabled();
1497         updateForceEnablePssProfiling();
1498         // Read DropboxRateLimiter params from flags.
1499         mService.initDropboxRateLimiter();
1500     }
1501 
loadDeviceConfigConstants()1502     void loadDeviceConfigConstants() {
1503         mOnDeviceConfigChangedListener.onPropertiesChanged(
1504                 DeviceConfig.getProperties(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER));
1505         mOnDeviceConfigChangedForComponentAliasListener.onPropertiesChanged(
1506                 DeviceConfig.getProperties(
1507                         DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS));
1508     }
1509 
loadNativeBootDeviceConfigConstants()1510     private void loadNativeBootDeviceConfigConstants() {
1511         ENABLE_NEW_OOMADJ = getDeviceConfigBoolean(KEY_ENABLE_NEW_OOMADJ,
1512                 DEFAULT_ENABLE_NEW_OOM_ADJ);
1513         ENABLE_BATCHING_OOM_ADJ = getDeviceConfigBoolean(KEY_ENABLE_BATCHING_OOM_ADJ,
1514                 DEFAULT_ENABLE_BATCHING_OOM_ADJ);
1515     }
1516 
setOverrideMaxCachedProcesses(int value)1517     public void setOverrideMaxCachedProcesses(int value) {
1518         mOverrideMaxCachedProcesses = value;
1519         updateMaxCachedProcesses();
1520     }
1521 
getOverrideMaxCachedProcesses()1522     public int getOverrideMaxCachedProcesses() {
1523         return mOverrideMaxCachedProcesses;
1524     }
1525 
computeEmptyProcessLimit(int totalProcessLimit)1526     public static int computeEmptyProcessLimit(int totalProcessLimit) {
1527         return totalProcessLimit/2;
1528     }
1529 
1530     @Override
onChange(boolean selfChange, Uri uri)1531     public void onChange(boolean selfChange, Uri uri) {
1532         if (uri == null) return;
1533         if (ACTIVITY_MANAGER_CONSTANTS_URI.equals(uri)) {
1534             updateConstants();
1535         } else if (ACTIVITY_STARTS_LOGGING_ENABLED_URI.equals(uri)) {
1536             updateActivityStartsLoggingEnabled();
1537         } else if (FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI.equals(uri)) {
1538             updateForegroundServiceStartsLoggingEnabled();
1539         } else if (ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI.equals(uri)) {
1540             updateEnableAutomaticSystemServerHeapDumps();
1541         } else if (FORCE_ENABLE_PSS_PROFILING_URI.equals(uri)) {
1542             updateForceEnablePssProfiling();
1543         }
1544     }
1545 
updateConstants()1546     private void updateConstants() {
1547         final String setting = Settings.Global.getString(mResolver,
1548                 Settings.Global.ACTIVITY_MANAGER_CONSTANTS);
1549         synchronized (mService) {
1550             try {
1551                 mParser.setString(setting);
1552             } catch (IllegalArgumentException e) {
1553                 // Failed to parse the settings string, log this and move on
1554                 // with defaults.
1555                 Slog.e("ActivityManagerConstants", "Bad activity manager config settings", e);
1556             }
1557             final long currentPowerCheckInterval = POWER_CHECK_INTERVAL;
1558 
1559             BACKGROUND_SETTLE_TIME = mParser.getLong(KEY_BACKGROUND_SETTLE_TIME,
1560                     DEFAULT_BACKGROUND_SETTLE_TIME);
1561             FGSERVICE_MIN_SHOWN_TIME = mParser.getLong(KEY_FGSERVICE_MIN_SHOWN_TIME,
1562                     DEFAULT_FGSERVICE_MIN_SHOWN_TIME);
1563             FGSERVICE_MIN_REPORT_TIME = mParser.getLong(KEY_FGSERVICE_MIN_REPORT_TIME,
1564                     DEFAULT_FGSERVICE_MIN_REPORT_TIME);
1565             FGSERVICE_SCREEN_ON_BEFORE_TIME = mParser.getLong(KEY_FGSERVICE_SCREEN_ON_BEFORE_TIME,
1566                     DEFAULT_FGSERVICE_SCREEN_ON_BEFORE_TIME);
1567             FGSERVICE_SCREEN_ON_AFTER_TIME = mParser.getLong(KEY_FGSERVICE_SCREEN_ON_AFTER_TIME,
1568                     DEFAULT_FGSERVICE_SCREEN_ON_AFTER_TIME);
1569             FGS_BOOT_COMPLETED_ALLOWLIST = mParser.getInt(KEY_FGS_BOOT_COMPLETED_ALLOWLIST,
1570                     DEFAULT_FGS_BOOT_COMPLETED_ALLOWLIST);
1571             CONTENT_PROVIDER_RETAIN_TIME = mParser.getLong(KEY_CONTENT_PROVIDER_RETAIN_TIME,
1572                     DEFAULT_CONTENT_PROVIDER_RETAIN_TIME);
1573             GC_TIMEOUT = mParser.getLong(KEY_GC_TIMEOUT,
1574                     DEFAULT_GC_TIMEOUT);
1575             GC_MIN_INTERVAL = mParser.getLong(KEY_GC_MIN_INTERVAL,
1576                     DEFAULT_GC_MIN_INTERVAL);
1577             FULL_PSS_MIN_INTERVAL = mParser.getLong(KEY_FULL_PSS_MIN_INTERVAL,
1578                     DEFAULT_FULL_PSS_MIN_INTERVAL);
1579             FULL_PSS_LOWERED_INTERVAL = mParser.getLong(KEY_FULL_PSS_LOWERED_INTERVAL,
1580                     DEFAULT_FULL_PSS_LOWERED_INTERVAL);
1581             POWER_CHECK_INTERVAL = mParser.getLong(KEY_POWER_CHECK_INTERVAL,
1582                     DEFAULT_POWER_CHECK_INTERVAL);
1583             POWER_CHECK_MAX_CPU_1 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_1,
1584                     DEFAULT_POWER_CHECK_MAX_CPU_1);
1585             POWER_CHECK_MAX_CPU_2 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_2,
1586                     DEFAULT_POWER_CHECK_MAX_CPU_2);
1587             POWER_CHECK_MAX_CPU_3 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_3,
1588                     DEFAULT_POWER_CHECK_MAX_CPU_3);
1589             POWER_CHECK_MAX_CPU_4 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_4,
1590                     DEFAULT_POWER_CHECK_MAX_CPU_4);
1591             SERVICE_USAGE_INTERACTION_TIME_PRE_S = mParser.getLong(
1592                     KEY_SERVICE_USAGE_INTERACTION_TIME_PRE_S,
1593                     DEFAULT_SERVICE_USAGE_INTERACTION_TIME_PRE_S);
1594             SERVICE_USAGE_INTERACTION_TIME_POST_S = mParser.getLong(
1595                     KEY_SERVICE_USAGE_INTERACTION_TIME_POST_S,
1596                     DEFAULT_SERVICE_USAGE_INTERACTION_TIME_POST_S);
1597             USAGE_STATS_INTERACTION_INTERVAL_PRE_S = mParser.getLong(
1598                     KEY_USAGE_STATS_INTERACTION_INTERVAL_PRE_S,
1599                     DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_PRE_S);
1600             USAGE_STATS_INTERACTION_INTERVAL_POST_S = mParser.getLong(
1601                     KEY_USAGE_STATS_INTERACTION_INTERVAL_POST_S,
1602                     DEFAULT_USAGE_STATS_INTERACTION_INTERVAL_POST_S);
1603             SERVICE_RESTART_DURATION = mParser.getLong(KEY_SERVICE_RESTART_DURATION,
1604                     DEFAULT_SERVICE_RESTART_DURATION);
1605             SERVICE_RESET_RUN_DURATION = mParser.getLong(KEY_SERVICE_RESET_RUN_DURATION,
1606                     DEFAULT_SERVICE_RESET_RUN_DURATION);
1607             SERVICE_RESTART_DURATION_FACTOR = mParser.getInt(KEY_SERVICE_RESTART_DURATION_FACTOR,
1608                     DEFAULT_SERVICE_RESTART_DURATION_FACTOR);
1609             SERVICE_MIN_RESTART_TIME_BETWEEN = mParser.getLong(KEY_SERVICE_MIN_RESTART_TIME_BETWEEN,
1610                     DEFAULT_SERVICE_MIN_RESTART_TIME_BETWEEN);
1611             MAX_SERVICE_INACTIVITY = mParser.getLong(KEY_MAX_SERVICE_INACTIVITY,
1612                     DEFAULT_MAX_SERVICE_INACTIVITY);
1613             BG_START_TIMEOUT = mParser.getLong(KEY_BG_START_TIMEOUT,
1614                     DEFAULT_BG_START_TIMEOUT);
1615             SERVICE_BG_ACTIVITY_START_TIMEOUT = mParser.getLong(
1616                     KEY_SERVICE_BG_ACTIVITY_START_TIMEOUT,
1617                     DEFAULT_SERVICE_BG_ACTIVITY_START_TIMEOUT);
1618             BOUND_SERVICE_CRASH_RESTART_DURATION = mParser.getLong(
1619                 KEY_BOUND_SERVICE_CRASH_RESTART_DURATION,
1620                 DEFAULT_BOUND_SERVICE_CRASH_RESTART_DURATION);
1621             BOUND_SERVICE_MAX_CRASH_RETRY = mParser.getInt(KEY_BOUND_SERVICE_CRASH_MAX_RETRY,
1622                 DEFAULT_BOUND_SERVICE_CRASH_MAX_RETRY);
1623             FLAG_PROCESS_START_ASYNC = mParser.getBoolean(KEY_PROCESS_START_ASYNC,
1624                     DEFAULT_PROCESS_START_ASYNC);
1625             MEMORY_INFO_THROTTLE_TIME = mParser.getLong(KEY_MEMORY_INFO_THROTTLE_TIME,
1626                     DEFAULT_MEMORY_INFO_THROTTLE_TIME);
1627             TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION = mParser.getDurationMillis(
1628                     KEY_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION,
1629                     DEFAULT_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION);
1630             MIN_CRASH_INTERVAL = mParser.getInt(KEY_MIN_CRASH_INTERVAL,
1631                     DEFAULT_MIN_CRASH_INTERVAL);
1632             PENDINGINTENT_WARNING_THRESHOLD = mParser.getInt(KEY_PENDINGINTENT_WARNING_THRESHOLD,
1633                     DEFAULT_PENDINGINTENT_WARNING_THRESHOLD);
1634             PROCESS_CRASH_COUNT_RESET_INTERVAL = mParser.getInt(
1635                     KEY_PROCESS_CRASH_COUNT_RESET_INTERVAL,
1636                     DEFAULT_PROCESS_CRASH_COUNT_RESET_INTERVAL);
1637             PROCESS_CRASH_COUNT_LIMIT = mParser.getInt(KEY_PROCESS_CRASH_COUNT_LIMIT,
1638                     DEFAULT_PROCESS_CRASH_COUNT_LIMIT);
1639 
1640             if (POWER_CHECK_INTERVAL != currentPowerCheckInterval) {
1641                 mService.mHandler.removeMessages(
1642                         ActivityManagerService.CHECK_EXCESSIVE_POWER_USE_MSG);
1643                 final Message msg = mService.mHandler.obtainMessage(
1644                         ActivityManagerService.CHECK_EXCESSIVE_POWER_USE_MSG);
1645                 mService.mHandler.sendMessageDelayed(msg, POWER_CHECK_INTERVAL);
1646             }
1647             // For new flags that are intended for server-side experiments, please use the new
1648             // DeviceConfig package.
1649         }
1650     }
1651 
updateActivityStartsLoggingEnabled()1652     private void updateActivityStartsLoggingEnabled() {
1653         mFlagActivityStartsLoggingEnabled = Settings.Global.getInt(mResolver,
1654                 Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED, 1) == 1;
1655     }
1656 
updateForceEnablePssProfiling()1657     private void updateForceEnablePssProfiling() {
1658         mForceEnablePssProfiling = Settings.Global.getInt(mResolver,
1659                 Settings.Global.FORCE_ENABLE_PSS_PROFILING, 0) == 1;
1660     }
1661 
updateBackgroundActivityStarts()1662     private void updateBackgroundActivityStarts() {
1663         mFlagBackgroundActivityStartsEnabled = DeviceConfig.getBoolean(
1664                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1665                 KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED,
1666                 /*defaultValue*/ false);
1667     }
1668 
updateForegroundServiceStartsLoggingEnabled()1669     private void updateForegroundServiceStartsLoggingEnabled() {
1670         mFlagForegroundServiceStartsLoggingEnabled = Settings.Global.getInt(mResolver,
1671                 Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED, 1) == 1;
1672     }
1673 
updateBackgroundFgsStartsRestriction()1674     private void updateBackgroundFgsStartsRestriction() {
1675         mFlagBackgroundFgsStartRestrictionEnabled = DeviceConfig.getBoolean(
1676                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1677                 KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED,
1678                 /*defaultValue*/ true);
1679     }
1680 
updateFgsStartsRestriction()1681     private void updateFgsStartsRestriction() {
1682         mFlagFgsStartRestrictionEnabled = DeviceConfig.getBoolean(
1683                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1684                 KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED,
1685                 /*defaultValue*/ true);
1686     }
1687 
updateFgsStartsRestrictionNotification()1688     private void updateFgsStartsRestrictionNotification() {
1689         mFgsStartRestrictionNotificationEnabled = DeviceConfig.getBoolean(
1690                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1691                 KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED,
1692                 /*defaultValue*/ false);
1693     }
1694 
updateFgsStartsRestrictionCheckCallerTargetSdk()1695     private void updateFgsStartsRestrictionCheckCallerTargetSdk() {
1696         mFgsStartRestrictionCheckCallerTargetSdk = DeviceConfig.getBoolean(
1697                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1698                 KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK,
1699                 /*defaultValue*/ true);
1700     }
1701 
updateFgsNotificationDeferralEnable()1702     private void updateFgsNotificationDeferralEnable() {
1703         mFlagFgsNotificationDeferralEnabled = DeviceConfig.getBoolean(
1704                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1705                 KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED,
1706                 /*default value*/ true);
1707     }
1708 
updateFgsNotificationDeferralApiGated()1709     private void updateFgsNotificationDeferralApiGated() {
1710         mFlagFgsNotificationDeferralApiGated = DeviceConfig.getBoolean(
1711                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1712                 KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED,
1713                 /*default value*/ false);
1714     }
1715 
updateFgsNotificationDeferralInterval()1716     private void updateFgsNotificationDeferralInterval() {
1717         mFgsNotificationDeferralInterval = DeviceConfig.getLong(
1718                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1719                 KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL,
1720                 /*default value*/ 10_000L);
1721     }
1722 
updateFgsNotificationDeferralIntervalForShort()1723     private void updateFgsNotificationDeferralIntervalForShort() {
1724         mFgsNotificationDeferralIntervalForShort = DeviceConfig.getLong(
1725                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1726                 KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL_FOR_SHORT,
1727                 /*default value*/ 10_000L);
1728     }
1729 
updateFgsNotificationDeferralExclusionTime()1730     private void updateFgsNotificationDeferralExclusionTime() {
1731         mFgsNotificationDeferralExclusionTime = DeviceConfig.getLong(
1732                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1733                 KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME,
1734                 /*default value*/ 2 * 60 * 1000L);
1735     }
1736 
updateFgsNotificationDeferralExclusionTimeForShort()1737     private void updateFgsNotificationDeferralExclusionTimeForShort() {
1738         mFgsNotificationDeferralExclusionTimeForShort = DeviceConfig.getLong(
1739                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1740                 KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME_FOR_SHORT,
1741                 /*default value*/ 2 * 60 * 1000L);
1742     }
1743 
updateSystemExemptPowerRestrictionsEnabled()1744     private void updateSystemExemptPowerRestrictionsEnabled() {
1745         mFlagSystemExemptPowerRestrictionsEnabled = DeviceConfig.getBoolean(
1746                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1747                 KEY_SYSTEM_EXEMPT_POWER_RESTRICTIONS_ENABLED,
1748                 DEFAULT_SYSTEM_EXEMPT_POWER_RESTRICTIONS_ENABLED);
1749     }
1750 
updatePushMessagingOverQuotaBehavior()1751     private void updatePushMessagingOverQuotaBehavior() {
1752         mPushMessagingOverQuotaBehavior = DeviceConfig.getInt(
1753                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1754                 KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR,
1755                 DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR);
1756         if (mPushMessagingOverQuotaBehavior < TEMPORARY_ALLOW_LIST_TYPE_NONE
1757                 || mPushMessagingOverQuotaBehavior
1758                 > TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_NOT_ALLOWED) {
1759             mPushMessagingOverQuotaBehavior =
1760                     DEFAULT_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR;
1761         }
1762     }
1763 
updateOomAdjUpdatePolicy()1764     private void updateOomAdjUpdatePolicy() {
1765         OOMADJ_UPDATE_QUICK = DeviceConfig.getInt(
1766                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1767                 KEY_OOMADJ_UPDATE_POLICY,
1768                 /* defaultValue */ DEFAULT_OOMADJ_UPDATE_POLICY)
1769                 == OOMADJ_UPDATE_POLICY_QUICK;
1770     }
1771 
updateForceRestrictedBackgroundCheck()1772     private void updateForceRestrictedBackgroundCheck() {
1773         FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS = DeviceConfig.getBoolean(
1774                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1775                 KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS,
1776                 DEFAULT_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS);
1777     }
1778 
updateBootTimeTempAllowListDuration()1779     private void updateBootTimeTempAllowListDuration() {
1780         mBootTimeTempAllowlistDuration = DeviceConfig.getLong(
1781                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1782                 KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION,
1783                 DEFAULT_BOOT_TIME_TEMP_ALLOWLIST_DURATION);
1784     }
1785 
updateFgToBgFgsGraceDuration()1786     private void updateFgToBgFgsGraceDuration() {
1787         mFgToBgFgsGraceDuration = DeviceConfig.getLong(
1788                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1789                 KEY_FG_TO_BG_FGS_GRACE_DURATION,
1790                 DEFAULT_FG_TO_BG_FGS_GRACE_DURATION);
1791     }
1792 
updateVisibleToInvisibleUijScheduleGraceDuration()1793     private void updateVisibleToInvisibleUijScheduleGraceDuration() {
1794         mVisibleToInvisibleUijScheduleGraceDurationMs = DeviceConfig.getLong(
1795                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1796                 KEY_VISIBLE_TO_INVISIBLE_UIJ_SCHEDULE_GRACE_DURATION,
1797                 DEFAULT_VISIBLE_TO_INVISIBLE_UIJ_SCHEDULE_GRACE_DURATION);
1798     }
1799 
updateFgsStartForegroundTimeout()1800     private void updateFgsStartForegroundTimeout() {
1801         mFgsStartForegroundTimeoutMs = DeviceConfig.getLong(
1802                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1803                 KEY_FGS_START_FOREGROUND_TIMEOUT,
1804                 DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS);
1805     }
1806 
updateFgsAtomSamplePercent()1807     private void updateFgsAtomSamplePercent() {
1808         mFgsAtomSampleRate = DeviceConfig.getFloat(
1809                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1810                 KEY_FGS_ATOM_SAMPLE_RATE,
1811                 DEFAULT_FGS_ATOM_SAMPLE_RATE);
1812     }
1813 
updateFgsStartAllowedLogSamplePercent()1814     private void updateFgsStartAllowedLogSamplePercent() {
1815         mFgsStartAllowedLogSampleRate = DeviceConfig.getFloat(
1816                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1817                 KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE,
1818                 DEFAULT_FGS_START_ALLOWED_LOG_SAMPLE_RATE);
1819     }
1820 
updateFgsStartDeniedLogSamplePercent()1821     private void updateFgsStartDeniedLogSamplePercent() {
1822         mFgsStartDeniedLogSampleRate = DeviceConfig.getFloat(
1823                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1824                 KEY_FGS_START_DENIED_LOG_SAMPLE_RATE,
1825                 DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE);
1826     }
1827 
updateKillBgRestrictedCachedIdle()1828     private void updateKillBgRestrictedCachedIdle() {
1829         mKillBgRestrictedAndCachedIdle = DeviceConfig.getBoolean(
1830                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1831                 KEY_KILL_BG_RESTRICTED_CACHED_IDLE,
1832                 DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE);
1833     }
1834 
updateKillBgRestrictedCachedIdleSettleTime()1835     private void updateKillBgRestrictedCachedIdleSettleTime() {
1836         final long currentSettleTime = mKillBgRestrictedAndCachedIdleSettleTimeMs;
1837         mKillBgRestrictedAndCachedIdleSettleTimeMs = DeviceConfig.getLong(
1838                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1839                 KEY_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME,
1840                 DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME_MS);
1841         if (mKillBgRestrictedAndCachedIdleSettleTimeMs < currentSettleTime) {
1842             // Don't remove existing messages in case other IDLE_UIDS_MSG initiators use lower
1843             // delays, but send a new message if the settle time has decreased.
1844             mService.mHandler.sendEmptyMessageDelayed(
1845                     ActivityManagerService.IDLE_UIDS_MSG,
1846                     mKillBgRestrictedAndCachedIdleSettleTimeMs);
1847         }
1848     }
1849 
updateFgsAllowOptOut()1850     private void updateFgsAllowOptOut() {
1851         mFgsAllowOptOut = DeviceConfig.getBoolean(
1852                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1853                 KEY_FGS_ALLOW_OPT_OUT,
1854                 DEFAULT_FGS_ALLOW_OPT_OUT);
1855     }
1856 
updateExtraServiceRestartDelayOnMemPressure()1857     private void updateExtraServiceRestartDelayOnMemPressure() {
1858         synchronized (mService) {
1859             final int memFactor = mService.mAppProfiler.getLastMemoryLevelLocked();
1860             final long[] prevDelays = mExtraServiceRestartDelayOnMemPressure;
1861             mExtraServiceRestartDelayOnMemPressure = parseLongArray(
1862                     KEY_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE,
1863                     DEFAULT_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE);
1864             mService.mServices.performRescheduleServiceRestartOnMemoryPressureLocked(
1865                     mExtraServiceRestartDelayOnMemPressure[memFactor],
1866                     prevDelays[memFactor], "config", SystemClock.uptimeMillis());
1867         }
1868     }
1869 
updateEnableExtraServiceRestartDelayOnMemPressure()1870     private void updateEnableExtraServiceRestartDelayOnMemPressure() {
1871         synchronized (mService) {
1872             final boolean prevEnabled = mEnableExtraServiceRestartDelayOnMemPressure;
1873             mEnableExtraServiceRestartDelayOnMemPressure = DeviceConfig.getBoolean(
1874                     DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1875                     KEY_ENABLE_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE,
1876                     DEFAULT_ENABLE_EXTRA_SERVICE_RESTART_DELAY_ON_MEM_PRESSURE);
1877             mService.mServices.rescheduleServiceRestartOnMemoryPressureIfNeededLocked(
1878                     prevEnabled, mEnableExtraServiceRestartDelayOnMemPressure,
1879                     SystemClock.uptimeMillis());
1880         }
1881     }
1882 
updatePrioritizeAlarmBroadcasts()1883     private void updatePrioritizeAlarmBroadcasts() {
1884         // Flag value can be something that evaluates to `true` or `false`,
1885         // or empty/null.  If it's empty/null, the platform default is used.
1886         final String flag = DeviceConfig.getString(
1887                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1888                 KEY_PRIORITIZE_ALARM_BROADCASTS,
1889                 "");
1890         mPrioritizeAlarmBroadcasts = TextUtils.isEmpty(flag)
1891                 ? DEFAULT_PRIORITIZE_ALARM_BROADCASTS
1892                 : Boolean.parseBoolean(flag);
1893     }
updateDeferBootCompletedBroadcast()1894     private void updateDeferBootCompletedBroadcast() {
1895         mDeferBootCompletedBroadcast = DeviceConfig.getInt(
1896                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1897                 KEY_DEFER_BOOT_COMPLETED_BROADCAST,
1898                 DEFAULT_DEFER_BOOT_COMPLETED_BROADCAST);
1899     }
1900 
updateNoKillCachedProcessesUntilBootCompleted()1901     private void updateNoKillCachedProcessesUntilBootCompleted() {
1902         mNoKillCachedProcessesUntilBootCompleted = DeviceConfig.getBoolean(
1903                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1904                 KEY_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED,
1905                 DEFAULT_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED);
1906     }
1907 
updateNoKillCachedProcessesPostBootCompletedDurationMillis()1908     private void updateNoKillCachedProcessesPostBootCompletedDurationMillis() {
1909         mNoKillCachedProcessesPostBootCompletedDurationMillis = DeviceConfig.getLong(
1910                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1911                 KEY_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS,
1912                 DEFAULT_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS);
1913     }
1914 
updateMaxEmptyTimeMillis()1915     private void updateMaxEmptyTimeMillis() {
1916         mMaxEmptyTimeMillis = DeviceConfig.getLong(
1917                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1918                 KEY_MAX_EMPTY_TIME_MILLIS,
1919                 DEFAULT_MAX_EMPTY_TIME_MILLIS);
1920     }
1921 
updateNetworkAccessTimeoutMs()1922     private void updateNetworkAccessTimeoutMs() {
1923         mNetworkAccessTimeoutMs = DeviceConfig.getLong(
1924                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1925                 KEY_NETWORK_ACCESS_TIMEOUT_MS,
1926                 DEFAULT_NETWORK_ACCESS_TIMEOUT_MS);
1927     }
1928 
updateServiceStartForegroundTimeoutMs()1929     private void updateServiceStartForegroundTimeoutMs() {
1930         mServiceStartForegroundTimeoutMs = DeviceConfig.getInt(
1931                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1932                 KEY_SERVICE_START_FOREGROUND_TIMEOUT_MS,
1933                 DEFAULT_SERVICE_START_FOREGROUND_TIMEOUT_MS);
1934     }
1935 
updateServiceStartForegroundAnrDealyMs()1936     private void updateServiceStartForegroundAnrDealyMs() {
1937         mServiceStartForegroundAnrDelayMs = DeviceConfig.getInt(
1938                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1939                 KEY_SERVICE_START_FOREGROUND_ANR_DELAY_MS,
1940                 DEFAULT_SERVICE_START_FOREGROUND_ANR_DELAY_MS);
1941     }
1942 
updateServiceBindAlmostPerceptibleTimeoutMs()1943     private void updateServiceBindAlmostPerceptibleTimeoutMs() {
1944         mServiceBindAlmostPerceptibleTimeoutMs = DeviceConfig.getLong(
1945                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1946                 KEY_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS,
1947                 DEFAULT_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS);
1948     }
1949 
1950 
parseLongArray(@onNull String key, @NonNull long[] def)1951     private long[] parseLongArray(@NonNull String key, @NonNull long[] def) {
1952         final String val = DeviceConfig.getString(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1953                 key, null);
1954         if (!TextUtils.isEmpty(val)) {
1955             final String[] ss = val.split(",");
1956             if (ss.length == def.length) {
1957                 final long[] tmp = new long[ss.length];
1958                 try {
1959                     for (int i = 0; i < ss.length; i++) {
1960                         tmp[i] = Long.parseLong(ss[i]);
1961                     }
1962                     return tmp;
1963                 } catch (NumberFormatException e) {
1964                 }
1965             }
1966         }
1967         return def;
1968     }
1969 
updateComponentAliases()1970     private void updateComponentAliases() {
1971         mEnableComponentAlias = DeviceConfig.getBoolean(
1972                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS,
1973                 KEY_ENABLE_COMPONENT_ALIAS,
1974                 DEFAULT_ENABLE_COMPONENT_ALIAS);
1975         mComponentAliasOverrides = DeviceConfig.getString(
1976                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS,
1977                 KEY_COMPONENT_ALIAS_OVERRIDES,
1978                 DEFAULT_COMPONENT_ALIAS_OVERRIDES);
1979         mService.mComponentAliasResolver.update(mEnableComponentAlias, mComponentAliasOverrides);
1980     }
1981 
updateProcessKillTimeout()1982     private void updateProcessKillTimeout() {
1983         mProcessKillTimeoutMs = DeviceConfig.getLong(
1984                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1985                 KEY_PROCESS_KILL_TIMEOUT,
1986                 DEFAULT_PROCESS_KILL_TIMEOUT_MS);
1987     }
1988 
updateImperceptibleKillExemptions()1989     private void updateImperceptibleKillExemptions() {
1990         IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.clear();
1991         IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.addAll(mDefaultImperceptibleKillExemptPackages);
1992         String val = DeviceConfig.getString(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
1993                 KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES, null);
1994         if (!TextUtils.isEmpty(val)) {
1995             IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.addAll(Arrays.asList(val.split(",")));
1996         }
1997 
1998         IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.clear();
1999         IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.addAll(mDefaultImperceptibleKillExemptProcStates);
2000         val = DeviceConfig.getString(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2001                 KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES, null);
2002         if (!TextUtils.isEmpty(val)) {
2003             Arrays.asList(val.split(",")).stream().forEach((v) -> {
2004                 try {
2005                     IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.add(Integer.parseInt(v));
2006                 } catch (NumberFormatException e) {
2007                 }
2008             });
2009         }
2010     }
2011 
updateEnableAutomaticSystemServerHeapDumps()2012     private void updateEnableAutomaticSystemServerHeapDumps() {
2013         if (!mSystemServerAutomaticHeapDumpEnabled) {
2014             Slog.wtf(TAG,
2015                     "updateEnableAutomaticSystemServerHeapDumps called when leak detection "
2016                             + "disabled");
2017             return;
2018         }
2019         // Monitoring is on by default, so if the setting hasn't been set by the user,
2020         // monitoring should be on.
2021         final boolean enabled = Settings.Global.getInt(mResolver,
2022                 Settings.Global.ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS, 1) == 1;
2023 
2024         // Setting the threshold to 0 stops the checking.
2025         final long threshold = enabled ? mSystemServerAutomaticHeapDumpPssThresholdBytes : 0;
2026         mService.setDumpHeapDebugLimit(null, 0, threshold,
2027                 mSystemServerAutomaticHeapDumpPackageName);
2028     }
2029 
updateMaxCachedProcesses()2030     private void updateMaxCachedProcesses() {
2031         String maxCachedProcessesFlag = DeviceConfig.getProperty(
2032                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MAX_CACHED_PROCESSES);
2033         try {
2034             CUR_MAX_CACHED_PROCESSES = mOverrideMaxCachedProcesses < 0
2035                     ? (TextUtils.isEmpty(maxCachedProcessesFlag)
2036                     ? mCustomizedMaxCachedProcesses : Integer.parseInt(maxCachedProcessesFlag))
2037                     : mOverrideMaxCachedProcesses;
2038         } catch (NumberFormatException e) {
2039             // Bad flag value from Phenotype, revert to default.
2040             Slog.e(TAG,
2041                     "Unable to parse flag for max_cached_processes: " + maxCachedProcessesFlag, e);
2042             CUR_MAX_CACHED_PROCESSES = mCustomizedMaxCachedProcesses;
2043         }
2044         CUR_MAX_EMPTY_PROCESSES = computeEmptyProcessLimit(CUR_MAX_CACHED_PROCESSES);
2045 
2046         final int rawMaxEmptyProcesses = computeEmptyProcessLimit(
2047                 Integer.min(CUR_MAX_CACHED_PROCESSES, MAX_CACHED_PROCESSES));
2048         CUR_TRIM_EMPTY_PROCESSES = rawMaxEmptyProcesses / 2;
2049         CUR_TRIM_CACHED_PROCESSES = (Integer.min(CUR_MAX_CACHED_PROCESSES, MAX_CACHED_PROCESSES)
2050                     - rawMaxEmptyProcesses) / 3;
2051     }
2052 
2053     private void updateProactiveKillsEnabled() {
2054         PROACTIVE_KILLS_ENABLED = DeviceConfig.getBoolean(
2055                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2056                 KEY_PROACTIVE_KILLS_ENABLED,
2057                 DEFAULT_PROACTIVE_KILLS_ENABLED);
2058     }
2059 
2060     private void updateLowSwapThresholdPercent() {
2061         LOW_SWAP_THRESHOLD_PERCENT = DeviceConfig.getFloat(
2062                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2063                 KEY_LOW_SWAP_THRESHOLD_PERCENT,
2064                 DEFAULT_LOW_SWAP_THRESHOLD_PERCENT);
2065     }
2066 
2067 
2068     private void updateTopToFgsGraceDuration() {
2069         TOP_TO_FGS_GRACE_DURATION = DeviceConfig.getLong(
2070                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2071                 KEY_TOP_TO_FGS_GRACE_DURATION,
2072                 DEFAULT_TOP_TO_FGS_GRACE_DURATION);
2073     }
2074 
2075     private void updateMaxPreviousTime() {
2076         MAX_PREVIOUS_TIME = DeviceConfig.getLong(
2077                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2078                 KEY_MAX_PREVIOUS_TIME,
2079                 DEFAULT_MAX_PREVIOUS_TIME);
2080     }
2081 
2082     private void updateProcStateDebugUids() {
2083         final String val = DeviceConfig.getString(
2084                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2085                 KEY_PROC_STATE_DEBUG_UIDS,
2086                 "").trim();
2087 
2088         // Parse KEY_PROC_STATE_DEBUG_UIDS as comma-separated values. Each values can be:
2089         // Number:  Enable debugging on the given UID.
2090         // "stack": Enable stack trace when updating proc/uid-states.s
2091         // "u" + delay-ms: Enable sleep when updating uid-state
2092         // "p" + delay-ms: Enable sleep when updating procstate
2093         //
2094         // Example:
2095         //   device_config put activity_manager proc_state_debug_uids '10177,10202,stack,p500,u100'
2096         // means:
2097         // - Monitor UID 10177 and 10202
2098         // - Also enable stack trace
2099         // - Sleep 500 ms when updating the procstate.
2100         // - Sleep 100 ms when updating the UID state.
2101 
2102         mEnableProcStateStacktrace = false;
2103         mProcStateDebugSetProcStateDelay = 0;
2104         mProcStateDebugSetUidStateDelay = 0;
2105         if (val.length() == 0) {
2106             mProcStateDebugUids = new SparseBooleanArray(0);
2107             return;
2108         }
2109         final String[] uids = val.split(",");
2110 
2111         final SparseBooleanArray newArray = new SparseBooleanArray(0);
2112 
2113         for (String token : uids) {
2114             if (token.length() == 0) {
2115                 continue;
2116             }
2117             // "stack" -> enable stacktrace.
2118             if ("stack".equals(token)) {
2119                 mEnableProcStateStacktrace = true;
2120                 continue;
2121             }
2122             boolean isUid = true;
2123             char prefix = token.charAt(0);
2124             if ('a' <= prefix && prefix <= 'z') {
2125                 // If the token starts with an alphabet, it's not a UID.
2126                 isUid = false;
2127                 token = token.substring(1);
2128             }
2129 
2130             int value = -1;
2131             try {
2132                 value = Integer.parseInt(token.trim());
2133             } catch (NumberFormatException e) {
2134                 Slog.w(TAG, "Invalid number " + token + " in " + val);
2135                 continue;
2136             }
2137             if (isUid) {
2138                 newArray.put(value, true);
2139             } else if (prefix == 'p') {
2140                 // Enable delay in set-proc-state
2141                 mProcStateDebugSetProcStateDelay = value;
2142             } else if (prefix == 'u') {
2143                 // Enable delay in set-uid-state
2144                 mProcStateDebugSetUidStateDelay = value;
2145             } else {
2146                 Slog.w(TAG, "Invalid prefix " + prefix + " in " + val);
2147             }
2148         }
2149         mProcStateDebugUids = newArray;
2150     }
2151 
2152     private void updateMinAssocLogDuration() {
2153         MIN_ASSOC_LOG_DURATION = DeviceConfig.getLong(
2154                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MIN_ASSOC_LOG_DURATION,
2155                 /* defaultValue */ DEFAULT_MIN_ASSOC_LOG_DURATION);
2156     }
2157 
2158     private void updateBinderHeavyHitterWatcher() {
2159         BINDER_HEAVY_HITTER_WATCHER_ENABLED = DeviceConfig.getBoolean(
2160                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED,
2161                 mDefaultBinderHeavyHitterWatcherEnabled);
2162         BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE = DeviceConfig.getInt(
2163                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE,
2164                 mDefaultBinderHeavyHitterWatcherBatchSize);
2165         BINDER_HEAVY_HITTER_WATCHER_THRESHOLD = DeviceConfig.getFloat(
2166                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD,
2167                 mDefaultBinderHeavyHitterWatcherThreshold);
2168         BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED = DeviceConfig.getBoolean(
2169                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2170                 KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED,
2171                 mDefaultBinderHeavyHitterAutoSamplerEnabled);
2172         BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE = DeviceConfig.getInt(
2173                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2174                 KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE,
2175                 mDefaultBinderHeavyHitterAutoSamplerBatchSize);
2176         BINDER_HEAVY_HITTER_WATCHER_THRESHOLD = DeviceConfig.getFloat(
2177                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2178                 KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD,
2179                 mDefaultBinderHeavyHitterAutoSamplerThreshold);
2180         mService.scheduleUpdateBinderHeavyHitterWatcherConfig();
2181     }
2182 
2183     private void updateMaxPhantomProcesses() {
2184         final int oldVal = MAX_PHANTOM_PROCESSES;
2185         MAX_PHANTOM_PROCESSES = DeviceConfig.getInt(
2186                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MAX_PHANTOM_PROCESSES,
2187                 DEFAULT_MAX_PHANTOM_PROCESSES);
2188         if (oldVal > MAX_PHANTOM_PROCESSES) {
2189             mService.mHandler.post(mService.mPhantomProcessList::trimPhantomProcessesIfNecessary);
2190         }
2191     }
2192 
2193     private void updateMaxServiceConnectionsPerProcess() {
2194         mMaxServiceConnectionsPerProcess = DeviceConfig.getInt(
2195                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2196                 KEY_MAX_SERVICE_CONNECTIONS_PER_PROCESS,
2197                 DEFAULT_MAX_SERVICE_CONNECTIONS_PER_PROCESS);
2198     }
2199 
2200     private void updateShortFgsTimeoutDuration() {
2201         mShortFgsTimeoutDuration = DeviceConfig.getLong(
2202                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2203                 KEY_SHORT_FGS_TIMEOUT_DURATION,
2204                 DEFAULT_SHORT_FGS_TIMEOUT_DURATION);
2205     }
2206 
2207     private void updateShortFgsProcStateExtraWaitDuration() {
2208         mShortFgsProcStateExtraWaitDuration = DeviceConfig.getLong(
2209                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2210                 KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION,
2211                 DEFAULT_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION);
2212     }
2213 
2214     private void updateShortFgsAnrExtraWaitDuration() {
2215         mShortFgsAnrExtraWaitDuration = DeviceConfig.getLong(
2216                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2217                 KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION,
2218                 DEFAULT_SHORT_FGS_ANR_EXTRA_WAIT_DURATION);
2219     }
2220 
2221     private void updateMediaProcessingFgsTimeoutDuration() {
2222         mMediaProcessingFgsTimeoutDuration = DeviceConfig.getLong(
2223                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2224                 KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION,
2225                 DEFAULT_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION);
2226     }
2227 
2228     private void updateDataSyncFgsTimeoutDuration() {
2229         mDataSyncFgsTimeoutDuration = DeviceConfig.getLong(
2230                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2231                 KEY_DATA_SYNC_FGS_TIMEOUT_DURATION,
2232                 DEFAULT_DATA_SYNC_FGS_TIMEOUT_DURATION);
2233     }
2234 
2235     private void updateFgsCrashExtraWaitDuration() {
2236         mFgsCrashExtraWaitDuration = DeviceConfig.getLong(
2237                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2238                 KEY_FGS_CRASH_EXTRA_WAIT_DURATION,
2239                 DEFAULT_FGS_CRASH_EXTRA_WAIT_DURATION);
2240     }
2241 
2242     private void updateEnableWaitForFinishAttachApplication() {
2243         mEnableWaitForFinishAttachApplication = DeviceConfig.getBoolean(
2244                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2245                 KEY_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION,
2246                 DEFAULT_ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION);
2247     }
2248 
2249     private void updateUseTieredCachedAdj() {
2250         USE_TIERED_CACHED_ADJ = DeviceConfig.getBoolean(
2251             DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2252             KEY_USE_TIERED_CACHED_ADJ,
2253             DEFAULT_USE_TIERED_CACHED_ADJ);
2254         TIERED_CACHED_ADJ_DECAY_TIME = DeviceConfig.getLong(
2255             DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2256             KEY_TIERED_CACHED_ADJ_DECAY_TIME,
2257             DEFAULT_TIERED_CACHED_ADJ_DECAY_TIME);
2258     }
2259 
2260     private void updateEnableNewOomAdj() {
2261         ENABLE_NEW_OOMADJ = DeviceConfig.getBoolean(
2262             DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_NATIVE_BOOT,
2263             KEY_ENABLE_NEW_OOMADJ,
2264             DEFAULT_ENABLE_NEW_OOM_ADJ);
2265     }
2266 
2267     private void updateFollowUpOomAdjUpdateWaitDuration() {
2268         FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION = DeviceConfig.getLong(
2269                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
2270                 KEY_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION,
2271                 DEFAULT_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION);
2272     }
2273 
2274     private void updateFGSPermissionEnforcementFlagsIfNecessary(@NonNull String name) {
2275         ForegroundServiceTypePolicy.getDefaultPolicy()
2276             .updatePermissionEnforcementFlagIfNecessary(name);
2277     }
2278 
2279     private void updateDisableAppProfilerPssProfiling() {
2280         APP_PROFILER_PSS_PROFILING_DISABLED = DeviceConfig.getBoolean(
2281                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_DISABLE_APP_PROFILER_PSS_PROFILING,
2282                 mDefaultDisableAppProfilerPssProfiling);
2283     }
2284 
2285     private void updatePssToRssThresholdModifier() {
2286         PSS_TO_RSS_THRESHOLD_MODIFIER = DeviceConfig.getFloat(
2287                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_PSS_TO_RSS_THRESHOLD_MODIFIER,
2288                 mDefaultPssToRssThresholdModifier);
2289     }
2290 
2291     private void updateEnableBatchingOomAdj() {
2292         ENABLE_BATCHING_OOM_ADJ = DeviceConfig.getBoolean(
2293                 DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_NATIVE_BOOT,
2294                 KEY_ENABLE_BATCHING_OOM_ADJ,
2295                 DEFAULT_ENABLE_BATCHING_OOM_ADJ);
2296     }
2297 
2298     boolean shouldDebugUidForProcState(int uid) {
2299         SparseBooleanArray ar = mProcStateDebugUids;
2300         final var size = ar.size();
2301         if (size == 0) { // Most common case.
2302             return false;
2303         }
2304         // If the array is small (also common), avoid the binary search.
2305         if (size <= 8) {
2306             for (int i = 0; i < size; i++) {
2307                 if (ar.keyAt(i) == uid) {
2308                     return ar.valueAt(i);
2309                 }
2310             }
2311             return false;
2312         }
2313         return ar.get(uid, false);
2314     }
2315 
2316     boolean shouldEnableProcStateDebug() {
2317         return mProcStateDebugUids.size() > 0;
2318     }
2319 
2320     @NeverCompile // Avoid size overhead of debugging code.
2321     void dump(PrintWriter pw) {
2322         pw.println("ACTIVITY MANAGER SETTINGS (dumpsys activity settings) "
2323                 + Settings.Global.ACTIVITY_MANAGER_CONSTANTS + ":");
2324 
2325         pw.print("  "); pw.print(KEY_MAX_CACHED_PROCESSES); pw.print("=");
2326         pw.println(MAX_CACHED_PROCESSES);
2327         pw.print("  "); pw.print(KEY_BACKGROUND_SETTLE_TIME); pw.print("=");
2328         pw.println(BACKGROUND_SETTLE_TIME);
2329         pw.print("  "); pw.print(KEY_FGSERVICE_MIN_SHOWN_TIME); pw.print("=");
2330         pw.println(FGSERVICE_MIN_SHOWN_TIME);
2331         pw.print("  "); pw.print(KEY_FGSERVICE_MIN_REPORT_TIME); pw.print("=");
2332         pw.println(FGSERVICE_MIN_REPORT_TIME);
2333         pw.print("  "); pw.print(KEY_FGSERVICE_SCREEN_ON_BEFORE_TIME); pw.print("=");
2334         pw.println(FGSERVICE_SCREEN_ON_BEFORE_TIME);
2335         pw.print("  "); pw.print(KEY_FGSERVICE_SCREEN_ON_AFTER_TIME); pw.print("=");
2336         pw.println(FGSERVICE_SCREEN_ON_AFTER_TIME);
2337         pw.print("  "); pw.print(KEY_FGS_BOOT_COMPLETED_ALLOWLIST); pw.print("=");
2338         pw.println(FGS_BOOT_COMPLETED_ALLOWLIST);
2339         pw.print("  "); pw.print(KEY_CONTENT_PROVIDER_RETAIN_TIME); pw.print("=");
2340         pw.println(CONTENT_PROVIDER_RETAIN_TIME);
2341         pw.print("  "); pw.print(KEY_GC_TIMEOUT); pw.print("=");
2342         pw.println(GC_TIMEOUT);
2343         pw.print("  "); pw.print(KEY_GC_MIN_INTERVAL); pw.print("=");
2344         pw.println(GC_MIN_INTERVAL);
2345         pw.print("  "); pw.print(KEY_FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS); pw.print("=");
2346         pw.println(FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS);
2347         pw.print("  "); pw.print(KEY_FULL_PSS_MIN_INTERVAL); pw.print("=");
2348         pw.println(FULL_PSS_MIN_INTERVAL);
2349         pw.print("  "); pw.print(KEY_FULL_PSS_LOWERED_INTERVAL); pw.print("=");
2350         pw.println(FULL_PSS_LOWERED_INTERVAL);
2351         pw.print("  "); pw.print(KEY_POWER_CHECK_INTERVAL); pw.print("=");
2352         pw.println(POWER_CHECK_INTERVAL);
2353         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_1); pw.print("=");
2354         pw.println(POWER_CHECK_MAX_CPU_1);
2355         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_2); pw.print("=");
2356         pw.println(POWER_CHECK_MAX_CPU_2);
2357         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_3); pw.print("=");
2358         pw.println(POWER_CHECK_MAX_CPU_3);
2359         pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_4); pw.print("=");
2360         pw.println(POWER_CHECK_MAX_CPU_4);
2361         pw.print("  "); pw.print(KEY_SERVICE_USAGE_INTERACTION_TIME_PRE_S); pw.print("=");
2362         pw.println(SERVICE_USAGE_INTERACTION_TIME_PRE_S);
2363         pw.print("  "); pw.print(KEY_SERVICE_USAGE_INTERACTION_TIME_POST_S); pw.print("=");
2364         pw.println(SERVICE_USAGE_INTERACTION_TIME_POST_S);
2365         pw.print("  "); pw.print(KEY_USAGE_STATS_INTERACTION_INTERVAL_PRE_S); pw.print("=");
2366         pw.println(USAGE_STATS_INTERACTION_INTERVAL_PRE_S);
2367         pw.print("  "); pw.print(KEY_USAGE_STATS_INTERACTION_INTERVAL_POST_S); pw.print("=");
2368         pw.println(USAGE_STATS_INTERACTION_INTERVAL_POST_S);
2369         pw.print("  "); pw.print(KEY_SERVICE_RESTART_DURATION); pw.print("=");
2370         pw.println(SERVICE_RESTART_DURATION);
2371         pw.print("  "); pw.print(KEY_SERVICE_RESET_RUN_DURATION); pw.print("=");
2372         pw.println(SERVICE_RESET_RUN_DURATION);
2373         pw.print("  "); pw.print(KEY_SERVICE_RESTART_DURATION_FACTOR); pw.print("=");
2374         pw.println(SERVICE_RESTART_DURATION_FACTOR);
2375         pw.print("  "); pw.print(KEY_SERVICE_MIN_RESTART_TIME_BETWEEN); pw.print("=");
2376         pw.println(SERVICE_MIN_RESTART_TIME_BETWEEN);
2377         pw.print("  "); pw.print(KEY_MAX_SERVICE_INACTIVITY); pw.print("=");
2378         pw.println(MAX_SERVICE_INACTIVITY);
2379         pw.print("  "); pw.print(KEY_BG_START_TIMEOUT); pw.print("=");
2380         pw.println(BG_START_TIMEOUT);
2381         pw.print("  "); pw.print(KEY_SERVICE_BG_ACTIVITY_START_TIMEOUT); pw.print("=");
2382         pw.println(SERVICE_BG_ACTIVITY_START_TIMEOUT);
2383         pw.print("  "); pw.print(KEY_BOUND_SERVICE_CRASH_RESTART_DURATION); pw.print("=");
2384         pw.println(BOUND_SERVICE_CRASH_RESTART_DURATION);
2385         pw.print("  "); pw.print(KEY_BOUND_SERVICE_CRASH_MAX_RETRY); pw.print("=");
2386         pw.println(BOUND_SERVICE_MAX_CRASH_RETRY);
2387         pw.print("  "); pw.print(KEY_PROCESS_START_ASYNC); pw.print("=");
2388         pw.println(FLAG_PROCESS_START_ASYNC);
2389         pw.print("  "); pw.print(KEY_MEMORY_INFO_THROTTLE_TIME); pw.print("=");
2390         pw.println(MEMORY_INFO_THROTTLE_TIME);
2391         pw.print("  "); pw.print(KEY_TOP_TO_FGS_GRACE_DURATION); pw.print("=");
2392         pw.println(TOP_TO_FGS_GRACE_DURATION);
2393         pw.print("  "); pw.print(KEY_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION); pw.print("=");
2394         pw.println(TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION);
2395         pw.print("  "); pw.print(KEY_MIN_CRASH_INTERVAL); pw.print("=");
2396         pw.println(MIN_CRASH_INTERVAL);
2397         pw.print("  "); pw.print(KEY_PROCESS_CRASH_COUNT_RESET_INTERVAL); pw.print("=");
2398         pw.println(PROCESS_CRASH_COUNT_RESET_INTERVAL);
2399         pw.print("  "); pw.print(KEY_PROCESS_CRASH_COUNT_LIMIT); pw.print("=");
2400         pw.println(PROCESS_CRASH_COUNT_LIMIT);
2401         pw.print("  "); pw.print(KEY_IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES); pw.print("=");
2402         pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PROC_STATES.toArray()));
2403         pw.print("  "); pw.print(KEY_IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES); pw.print("=");
2404         pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.toArray()));
2405         pw.print("  "); pw.print(KEY_MIN_ASSOC_LOG_DURATION); pw.print("=");
2406         pw.println(MIN_ASSOC_LOG_DURATION);
2407         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_WATCHER_ENABLED); pw.print("=");
2408         pw.println(BINDER_HEAVY_HITTER_WATCHER_ENABLED);
2409         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE); pw.print("=");
2410         pw.println(BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE);
2411         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_WATCHER_THRESHOLD); pw.print("=");
2412         pw.println(BINDER_HEAVY_HITTER_WATCHER_THRESHOLD);
2413         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED); pw.print("=");
2414         pw.println(BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED);
2415         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE); pw.print("=");
2416         pw.println(BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE);
2417         pw.print("  "); pw.print(KEY_BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD); pw.print("=");
2418         pw.println(BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD);
2419         pw.print("  "); pw.print(KEY_MAX_PHANTOM_PROCESSES); pw.print("=");
2420         pw.println(MAX_PHANTOM_PROCESSES);
2421         pw.print("  "); pw.print(KEY_BOOT_TIME_TEMP_ALLOWLIST_DURATION); pw.print("=");
2422         pw.println(mBootTimeTempAllowlistDuration);
2423         pw.print("  "); pw.print(KEY_FG_TO_BG_FGS_GRACE_DURATION); pw.print("=");
2424         pw.println(mFgToBgFgsGraceDuration);
2425         pw.print("  "); pw.print(KEY_FGS_START_FOREGROUND_TIMEOUT); pw.print("=");
2426         pw.println(mFgsStartForegroundTimeoutMs);
2427         pw.print("  "); pw.print(KEY_DEFAULT_BACKGROUND_ACTIVITY_STARTS_ENABLED); pw.print("=");
2428         pw.println(mFlagBackgroundActivityStartsEnabled);
2429         pw.print("  "); pw.print(KEY_DEFAULT_BACKGROUND_FGS_STARTS_RESTRICTION_ENABLED);
2430         pw.print("="); pw.println(mFlagBackgroundFgsStartRestrictionEnabled);
2431         pw.print("  "); pw.print(KEY_DEFAULT_FGS_STARTS_RESTRICTION_ENABLED); pw.print("=");
2432         pw.println(mFlagFgsStartRestrictionEnabled);
2433         pw.print("  "); pw.print(KEY_DEFAULT_FGS_STARTS_RESTRICTION_NOTIFICATION_ENABLED);
2434                 pw.print("=");
2435         pw.println(mFgsStartRestrictionNotificationEnabled);
2436         pw.print("  "); pw.print(KEY_DEFAULT_FGS_STARTS_RESTRICTION_CHECK_CALLER_TARGET_SDK);
2437         pw.print("="); pw.println(mFgsStartRestrictionCheckCallerTargetSdk);
2438         pw.print("  "); pw.print(KEY_FGS_ATOM_SAMPLE_RATE);
2439         pw.print("="); pw.println(mFgsAtomSampleRate);
2440         pw.print("  "); pw.print(KEY_FGS_START_ALLOWED_LOG_SAMPLE_RATE);
2441         pw.print("="); pw.println(mFgsStartAllowedLogSampleRate);
2442         pw.print("  "); pw.print(KEY_FGS_START_DENIED_LOG_SAMPLE_RATE);
2443         pw.print("="); pw.println(mFgsStartDeniedLogSampleRate);
2444         pw.print("  "); pw.print(KEY_PUSH_MESSAGING_OVER_QUOTA_BEHAVIOR);
2445         pw.print("="); pw.println(mPushMessagingOverQuotaBehavior);
2446         pw.print("  "); pw.print(KEY_FGS_ALLOW_OPT_OUT);
2447         pw.print("="); pw.println(mFgsAllowOptOut);
2448         pw.print("  "); pw.print(KEY_ENABLE_COMPONENT_ALIAS);
2449         pw.print("="); pw.println(mEnableComponentAlias);
2450         pw.print("  "); pw.print(KEY_COMPONENT_ALIAS_OVERRIDES);
2451         pw.print("="); pw.println(mComponentAliasOverrides);
2452         pw.print("  "); pw.print(KEY_DEFER_BOOT_COMPLETED_BROADCAST);
2453         pw.print("="); pw.println(mDeferBootCompletedBroadcast);
2454         pw.print("  "); pw.print(KEY_PRIORITIZE_ALARM_BROADCASTS);
2455         pw.print("="); pw.println(mPrioritizeAlarmBroadcasts);
2456         pw.print("  "); pw.print(KEY_NO_KILL_CACHED_PROCESSES_UNTIL_BOOT_COMPLETED);
2457         pw.print("="); pw.println(mNoKillCachedProcessesUntilBootCompleted);
2458         pw.print("  "); pw.print(KEY_NO_KILL_CACHED_PROCESSES_POST_BOOT_COMPLETED_DURATION_MILLIS);
2459         pw.print("="); pw.println(mNoKillCachedProcessesPostBootCompletedDurationMillis);
2460         pw.print("  "); pw.print(KEY_MAX_EMPTY_TIME_MILLIS);
2461         pw.print("="); pw.println(mMaxEmptyTimeMillis);
2462         pw.print("  "); pw.print(KEY_SERVICE_START_FOREGROUND_TIMEOUT_MS);
2463         pw.print("="); pw.println(mServiceStartForegroundTimeoutMs);
2464         pw.print("  "); pw.print(KEY_SERVICE_START_FOREGROUND_ANR_DELAY_MS);
2465         pw.print("="); pw.println(mServiceStartForegroundAnrDelayMs);
2466         pw.print("  "); pw.print(KEY_SERVICE_BIND_ALMOST_PERCEPTIBLE_TIMEOUT_MS);
2467         pw.print("="); pw.println(mServiceBindAlmostPerceptibleTimeoutMs);
2468         pw.print("  "); pw.print(KEY_NETWORK_ACCESS_TIMEOUT_MS);
2469         pw.print("="); pw.println(mNetworkAccessTimeoutMs);
2470         pw.print("  "); pw.print(KEY_MAX_SERVICE_CONNECTIONS_PER_PROCESS);
2471         pw.print("="); pw.println(mMaxServiceConnectionsPerProcess);
2472         pw.print("  "); pw.print(KEY_PROACTIVE_KILLS_ENABLED);
2473         pw.print("="); pw.println(PROACTIVE_KILLS_ENABLED);
2474         pw.print("  "); pw.print(KEY_LOW_SWAP_THRESHOLD_PERCENT);
2475         pw.print("="); pw.println(LOW_SWAP_THRESHOLD_PERCENT);
2476 
2477         pw.print("  "); pw.print(KEY_DEFERRED_FGS_NOTIFICATIONS_ENABLED);
2478         pw.print("="); pw.println(mFlagFgsNotificationDeferralEnabled);
2479         pw.print("  "); pw.print(KEY_DEFERRED_FGS_NOTIFICATIONS_API_GATED);
2480         pw.print("="); pw.println(mFlagFgsNotificationDeferralApiGated);
2481 
2482         pw.print("  "); pw.print(KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL);
2483         pw.print("="); pw.println(mFgsNotificationDeferralInterval);
2484         pw.print("  "); pw.print(KEY_DEFERRED_FGS_NOTIFICATION_INTERVAL_FOR_SHORT);
2485         pw.print("="); pw.println(mFgsNotificationDeferralIntervalForShort);
2486 
2487         pw.print("  "); pw.print(KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME);
2488         pw.print("="); pw.println(mFgsNotificationDeferralExclusionTime);
2489         pw.print("  "); pw.print(KEY_DEFERRED_FGS_NOTIFICATION_EXCLUSION_TIME_FOR_SHORT);
2490         pw.print("="); pw.println(mFgsNotificationDeferralExclusionTimeForShort);
2491 
2492         pw.print("  "); pw.print(KEY_SYSTEM_EXEMPT_POWER_RESTRICTIONS_ENABLED);
2493         pw.print("="); pw.println(mFlagSystemExemptPowerRestrictionsEnabled);
2494 
2495         pw.print("  "); pw.print(KEY_SHORT_FGS_TIMEOUT_DURATION);
2496         pw.print("="); pw.println(mShortFgsTimeoutDuration);
2497         pw.print("  "); pw.print(KEY_SHORT_FGS_PROC_STATE_EXTRA_WAIT_DURATION);
2498         pw.print("="); pw.println(mShortFgsProcStateExtraWaitDuration);
2499         pw.print("  "); pw.print(KEY_SHORT_FGS_ANR_EXTRA_WAIT_DURATION);
2500         pw.print("="); pw.println(mShortFgsAnrExtraWaitDuration);
2501 
2502         pw.print("  "); pw.print(KEY_MEDIA_PROCESSING_FGS_TIMEOUT_DURATION);
2503         pw.print("="); pw.println(mMediaProcessingFgsTimeoutDuration);
2504         pw.print("  "); pw.print(KEY_DATA_SYNC_FGS_TIMEOUT_DURATION);
2505         pw.print("="); pw.println(mDataSyncFgsTimeoutDuration);
2506         pw.print("  "); pw.print(KEY_FGS_CRASH_EXTRA_WAIT_DURATION);
2507         pw.print("="); pw.println(mFgsCrashExtraWaitDuration);
2508 
2509         pw.print("  "); pw.print(KEY_USE_TIERED_CACHED_ADJ);
2510         pw.print("="); pw.println(USE_TIERED_CACHED_ADJ);
2511         pw.print("  "); pw.print(KEY_TIERED_CACHED_ADJ_DECAY_TIME);
2512         pw.print("="); pw.println(TIERED_CACHED_ADJ_DECAY_TIME);
2513 
2514         pw.print("  "); pw.print(KEY_ENABLE_NEW_OOMADJ);
2515         pw.print("="); pw.println(ENABLE_NEW_OOMADJ);
2516 
2517         pw.print("  "); pw.print(KEY_DISABLE_APP_PROFILER_PSS_PROFILING);
2518         pw.print("="); pw.println(APP_PROFILER_PSS_PROFILING_DISABLED);
2519 
2520         pw.print("  "); pw.print(KEY_PSS_TO_RSS_THRESHOLD_MODIFIER);
2521         pw.print("="); pw.println(PSS_TO_RSS_THRESHOLD_MODIFIER);
2522 
2523         pw.print("  "); pw.print(KEY_MAX_PREVIOUS_TIME);
2524         pw.print("="); pw.println(MAX_PREVIOUS_TIME);
2525 
2526         pw.print("  "); pw.print(KEY_ENABLE_BATCHING_OOM_ADJ);
2527         pw.print("="); pw.println(ENABLE_BATCHING_OOM_ADJ);
2528 
2529         pw.println();
2530         if (mOverrideMaxCachedProcesses >= 0) {
2531             pw.print("  mOverrideMaxCachedProcesses="); pw.println(mOverrideMaxCachedProcesses);
2532         }
2533         pw.print("  mCustomizedMaxCachedProcesses="); pw.println(mCustomizedMaxCachedProcesses);
2534         pw.print("  CUR_MAX_CACHED_PROCESSES="); pw.println(CUR_MAX_CACHED_PROCESSES);
2535         pw.print("  CUR_MAX_EMPTY_PROCESSES="); pw.println(CUR_MAX_EMPTY_PROCESSES);
2536         pw.print("  CUR_TRIM_EMPTY_PROCESSES="); pw.println(CUR_TRIM_EMPTY_PROCESSES);
2537         pw.print("  CUR_TRIM_CACHED_PROCESSES="); pw.println(CUR_TRIM_CACHED_PROCESSES);
2538         pw.print("  OOMADJ_UPDATE_QUICK="); pw.println(OOMADJ_UPDATE_QUICK);
2539         pw.print("  ENABLE_WAIT_FOR_FINISH_ATTACH_APPLICATION=");
2540         pw.println(mEnableWaitForFinishAttachApplication);
2541 
2542         pw.print("  "); pw.print(KEY_FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION);
2543         pw.print("="); pw.println(FOLLOW_UP_OOMADJ_UPDATE_WAIT_DURATION);
2544 
2545         synchronized (mProcStateDebugUids) {
2546             pw.print("  "); pw.print(KEY_PROC_STATE_DEBUG_UIDS);
2547             pw.print("="); pw.println(mProcStateDebugUids);
2548             pw.print("    uid-state-delay="); pw.println(mProcStateDebugSetUidStateDelay);
2549             pw.print("    proc-state-delay="); pw.println(mProcStateDebugSetProcStateDelay);
2550         }
2551     }
2552 }
2553