• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 android.app;
18 
19 import static android.app.WindowConfiguration.activityTypeToString;
20 import static android.app.WindowConfiguration.windowingModeToString;
21 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
22 import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
23 
24 import android.Manifest;
25 import android.annotation.ColorInt;
26 import android.annotation.DrawableRes;
27 import android.annotation.IntDef;
28 import android.annotation.IntRange;
29 import android.annotation.NonNull;
30 import android.annotation.Nullable;
31 import android.annotation.RequiresPermission;
32 import android.annotation.SystemApi;
33 import android.annotation.SystemService;
34 import android.annotation.TestApi;
35 import android.annotation.UserIdInt;
36 import android.compat.annotation.ChangeId;
37 import android.compat.annotation.EnabledSince;
38 import android.compat.annotation.UnsupportedAppUsage;
39 import android.content.ComponentName;
40 import android.content.Context;
41 import android.content.Intent;
42 import android.content.pm.ActivityInfo;
43 import android.content.pm.ApplicationInfo;
44 import android.content.pm.ConfigurationInfo;
45 import android.content.pm.IPackageDataObserver;
46 import android.content.pm.PackageManager;
47 import android.content.pm.ParceledListSlice;
48 import android.content.pm.UserInfo;
49 import android.content.res.Resources;
50 import android.graphics.Bitmap;
51 import android.graphics.Canvas;
52 import android.graphics.Color;
53 import android.graphics.Matrix;
54 import android.graphics.Point;
55 import android.graphics.Rect;
56 import android.graphics.drawable.Icon;
57 import android.hardware.HardwareBuffer;
58 import android.os.BatteryStats;
59 import android.os.Binder;
60 import android.os.Build;
61 import android.os.Build.VERSION_CODES;
62 import android.os.Bundle;
63 import android.os.Debug;
64 import android.os.Handler;
65 import android.os.IBinder;
66 import android.os.LocaleList;
67 import android.os.Parcel;
68 import android.os.Parcelable;
69 import android.os.PowerExemptionManager;
70 import android.os.PowerExemptionManager.ReasonCode;
71 import android.os.Process;
72 import android.os.RemoteException;
73 import android.os.ServiceManager;
74 import android.os.SystemProperties;
75 import android.os.UserHandle;
76 import android.os.UserManager;
77 import android.os.WorkSource;
78 import android.text.TextUtils;
79 import android.util.ArrayMap;
80 import android.util.DisplayMetrics;
81 import android.util.Singleton;
82 import android.util.Size;
83 import android.util.TypedXmlPullParser;
84 import android.util.TypedXmlSerializer;
85 import android.window.TaskSnapshot;
86 
87 import com.android.internal.app.LocalePicker;
88 import com.android.internal.app.procstats.ProcessStats;
89 import com.android.internal.os.RoSystemProperties;
90 import com.android.internal.os.TransferPipe;
91 import com.android.internal.util.FastPrintWriter;
92 import com.android.internal.util.MemInfoReader;
93 import com.android.internal.util.Preconditions;
94 import com.android.server.LocalServices;
95 
96 import java.io.FileDescriptor;
97 import java.io.FileOutputStream;
98 import java.io.IOException;
99 import java.io.PrintWriter;
100 import java.lang.annotation.Retention;
101 import java.lang.annotation.RetentionPolicy;
102 import java.util.ArrayList;
103 import java.util.Collection;
104 import java.util.Collections;
105 import java.util.List;
106 import java.util.Locale;
107 import java.util.concurrent.Executor;
108 
109 /**
110  * <p>
111  * This class gives information about, and interacts
112  * with, activities, services, and the containing
113  * process.
114  * </p>
115  *
116  * <p>
117  * A number of the methods in this class are for
118  * debugging or informational purposes and they should
119  * not be used to affect any runtime behavior of
120  * your app. These methods are called out as such in
121  * the method level documentation.
122  * </p>
123  *
124  *<p>
125  * Most application developers should not have the need to
126  * use this class, most of whose methods are for specialized
127  * use cases. However, a few methods are more broadly applicable.
128  * For instance, {@link android.app.ActivityManager#isLowRamDevice() isLowRamDevice()}
129  * enables your app to detect whether it is running on a low-memory device,
130  * and behave accordingly.
131  * {@link android.app.ActivityManager#clearApplicationUserData() clearApplicationUserData()}
132  * is for apps with reset-data functionality.
133  * </p>
134  *
135  * <p>
136  * In some special use cases, where an app interacts with
137  * its Task stack, the app may use the
138  * {@link android.app.ActivityManager.AppTask} and
139  * {@link android.app.ActivityManager.RecentTaskInfo} inner
140  * classes. However, in general, the methods in this class should
141  * be used for testing and debugging purposes only.
142  * </p>
143  */
144 @SystemService(Context.ACTIVITY_SERVICE)
145 public class ActivityManager {
146     private static String TAG = "ActivityManager";
147 
148     @UnsupportedAppUsage
149     private final Context mContext;
150 
151     private static volatile boolean sSystemReady = false;
152 
153 
154     private static final int FIRST_START_FATAL_ERROR_CODE = -100;
155     private static final int LAST_START_FATAL_ERROR_CODE = -1;
156     private static final int FIRST_START_SUCCESS_CODE = 0;
157     private static final int LAST_START_SUCCESS_CODE = 99;
158     private static final int FIRST_START_NON_FATAL_ERROR_CODE = 100;
159     private static final int LAST_START_NON_FATAL_ERROR_CODE = 199;
160 
161     /**
162      * Disable hidden API checks for the newly started instrumentation.
163      * @hide
164      */
165     public static final int INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS = 1 << 0;
166     /**
167      * Grant full access to the external storage for the newly started instrumentation.
168      * @hide
169      */
170     public static final int INSTR_FLAG_DISABLE_ISOLATED_STORAGE = 1 << 1;
171 
172     /**
173      * Disable test API access for the newly started instrumentation.
174      * @hide
175      */
176     public static final int INSTR_FLAG_DISABLE_TEST_API_CHECKS = 1 << 2;
177 
178     /**
179      * Do not restart the target process when starting or finishing instrumentation.
180      * @hide
181      */
182     public static final int INSTR_FLAG_NO_RESTART = 1 << 3;
183     /**
184      * Force the check that instrumentation and the target package are signed with the same
185      * certificate even if {@link Build#IS_DEBUGGABLE} is {@code true}.
186      * @hide
187      */
188     public static final int INSTR_FLAG_ALWAYS_CHECK_SIGNATURE = 1 << 4;
189     /**
190      * Instrument Sdk Sandbox process that corresponds to the target package.
191      * @hide
192      */
193     public static final int INSTR_FLAG_INSTRUMENT_SDK_SANDBOX = 1 << 5;
194 
195     static final class UidObserver extends IUidObserver.Stub {
196         final OnUidImportanceListener mListener;
197         final Context mContext;
198 
UidObserver(OnUidImportanceListener listener, Context clientContext)199         UidObserver(OnUidImportanceListener listener, Context clientContext) {
200             mListener = listener;
201             mContext = clientContext;
202         }
203 
204         @Override
onUidStateChanged(int uid, int procState, long procStateSeq, int capability)205         public void onUidStateChanged(int uid, int procState, long procStateSeq, int capability) {
206             mListener.onUidImportance(uid, RunningAppProcessInfo.procStateToImportanceForClient(
207                     procState, mContext));
208         }
209 
210         @Override
onUidGone(int uid, boolean disabled)211         public void onUidGone(int uid, boolean disabled) {
212             mListener.onUidImportance(uid, RunningAppProcessInfo.IMPORTANCE_GONE);
213         }
214 
215         @Override
onUidActive(int uid)216         public void onUidActive(int uid) {
217         }
218 
219         @Override
onUidIdle(int uid, boolean disabled)220         public void onUidIdle(int uid, boolean disabled) {
221         }
222 
onUidCachedChanged(int uid, boolean cached)223         @Override public void onUidCachedChanged(int uid, boolean cached) {
224         }
225 
onUidProcAdjChanged(int uid)226         @Override public void onUidProcAdjChanged(int uid) {
227         }
228     }
229 
230     final ArrayMap<OnUidImportanceListener, UidObserver> mImportanceListeners = new ArrayMap<>();
231 
232     /**
233      * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
234      * <meta-data>}</a> name for a 'home' Activity that declares a package that is to be
235      * uninstalled in lieu of the declaring one.  The package named here must be
236      * signed with the same certificate as the one declaring the {@code <meta-data>}.
237      */
238     public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
239 
240     // NOTE: Before adding a new start result, please reference the defined ranges to ensure the
241     // result is properly categorized.
242 
243     /**
244      * Result for IActivityManager.startVoiceActivity: active session is currently hidden.
245      * @hide
246      */
247     public static final int START_VOICE_HIDDEN_SESSION = FIRST_START_FATAL_ERROR_CODE;
248 
249     /**
250      * Result for IActivityManager.startVoiceActivity: active session does not match
251      * the requesting token.
252      * @hide
253      */
254     public static final int START_VOICE_NOT_ACTIVE_SESSION = FIRST_START_FATAL_ERROR_CODE + 1;
255 
256     /**
257      * Result for IActivityManager.startActivity: trying to start a background user
258      * activity that shouldn't be displayed for all users.
259      * @hide
260      */
261     public static final int START_NOT_CURRENT_USER_ACTIVITY = FIRST_START_FATAL_ERROR_CODE + 2;
262 
263     /**
264      * Result for IActivityManager.startActivity: trying to start an activity under voice
265      * control when that activity does not support the VOICE category.
266      * @hide
267      */
268     public static final int START_NOT_VOICE_COMPATIBLE = FIRST_START_FATAL_ERROR_CODE + 3;
269 
270     /**
271      * Result for IActivityManager.startActivity: an error where the
272      * start had to be canceled.
273      * @hide
274      */
275     public static final int START_CANCELED = FIRST_START_FATAL_ERROR_CODE + 4;
276 
277     /**
278      * Result for IActivityManager.startActivity: an error where the
279      * thing being started is not an activity.
280      * @hide
281      */
282     public static final int START_NOT_ACTIVITY = FIRST_START_FATAL_ERROR_CODE + 5;
283 
284     /**
285      * Result for IActivityManager.startActivity: an error where the
286      * caller does not have permission to start the activity.
287      * @hide
288      */
289     public static final int START_PERMISSION_DENIED = FIRST_START_FATAL_ERROR_CODE + 6;
290 
291     /**
292      * Result for IActivityManager.startActivity: an error where the
293      * caller has requested both to forward a result and to receive
294      * a result.
295      * @hide
296      */
297     public static final int START_FORWARD_AND_REQUEST_CONFLICT = FIRST_START_FATAL_ERROR_CODE + 7;
298 
299     /**
300      * Result for IActivityManager.startActivity: an error where the
301      * requested class is not found.
302      * @hide
303      */
304     public static final int START_CLASS_NOT_FOUND = FIRST_START_FATAL_ERROR_CODE + 8;
305 
306     /**
307      * Result for IActivityManager.startActivity: an error where the
308      * given Intent could not be resolved to an activity.
309      * @hide
310      */
311     public static final int START_INTENT_NOT_RESOLVED = FIRST_START_FATAL_ERROR_CODE + 9;
312 
313     /**
314      * Result for IActivityManager.startAssistantActivity: active session is currently hidden.
315      * @hide
316      */
317     public static final int START_ASSISTANT_HIDDEN_SESSION = FIRST_START_FATAL_ERROR_CODE + 10;
318 
319     /**
320      * Result for IActivityManager.startAssistantActivity: active session does not match
321      * the requesting token.
322      * @hide
323      */
324     public static final int START_ASSISTANT_NOT_ACTIVE_SESSION = FIRST_START_FATAL_ERROR_CODE + 11;
325 
326     /**
327      * Result for IActivityManaqer.startActivity: the activity was started
328      * successfully as normal.
329      * @hide
330      */
331     public static final int START_SUCCESS = FIRST_START_SUCCESS_CODE;
332 
333     /**
334      * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
335      * be executed if it is the recipient, and that is indeed the case.
336      * @hide
337      */
338     public static final int START_RETURN_INTENT_TO_CALLER = FIRST_START_SUCCESS_CODE + 1;
339 
340     /**
341      * Result for IActivityManaqer.startActivity: activity was started or brought forward in an
342      * existing task which was brought to the foreground.
343      * @hide
344      */
345     public static final int START_TASK_TO_FRONT = FIRST_START_SUCCESS_CODE + 2;
346 
347     /**
348      * Result for IActivityManaqer.startActivity: activity wasn't really started, but
349      * the given Intent was given to the existing top activity.
350      * @hide
351      */
352     public static final int START_DELIVERED_TO_TOP = FIRST_START_SUCCESS_CODE + 3;
353 
354     /**
355      * Result for IActivityManaqer.startActivity: request was canceled because
356      * app switches are temporarily canceled to ensure the user's last request
357      * (such as pressing home) is performed.
358      * @hide
359      */
360     public static final int START_SWITCHES_CANCELED = FIRST_START_NON_FATAL_ERROR_CODE;
361 
362     /**
363      * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
364      * while in Lock Task Mode.
365      * @hide
366      */
367     public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION =
368             FIRST_START_NON_FATAL_ERROR_CODE + 1;
369 
370     /**
371      * Result for IActivityManaqer.startActivity: a new activity start was aborted. Never returned
372      * externally.
373      * @hide
374      */
375     public static final int START_ABORTED = FIRST_START_NON_FATAL_ERROR_CODE + 2;
376 
377     /**
378      * Flag for IActivityManaqer.startActivity: do special start mode where
379      * a new activity is launched only if it is needed.
380      * @hide
381      */
382     public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
383 
384     /**
385      * Flag for IActivityManaqer.startActivity: launch the app for
386      * debugging.
387      * @hide
388      */
389     public static final int START_FLAG_DEBUG = 1<<1;
390 
391     /**
392      * Flag for IActivityManaqer.startActivity: launch the app for
393      * allocation tracking.
394      * @hide
395      */
396     public static final int START_FLAG_TRACK_ALLOCATION = 1<<2;
397 
398     /**
399      * Flag for IActivityManaqer.startActivity: launch the app with
400      * native debugging support.
401      * @hide
402      */
403     public static final int START_FLAG_NATIVE_DEBUGGING = 1<<3;
404 
405     /**
406      * Result for IActivityManaqer.broadcastIntent: success!
407      * @hide
408      */
409     public static final int BROADCAST_SUCCESS = 0;
410 
411     /**
412      * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
413      * a sticky intent without appropriate permission.
414      * @hide
415      */
416     public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
417 
418     /**
419      * Result for IActivityManager.broadcastIntent: trying to send a broadcast
420      * to a stopped user. Fail.
421      * @hide
422      */
423     public static final int BROADCAST_FAILED_USER_STOPPED = -2;
424 
425     /**
426      * Type for IActivityManaqer.getIntentSender: this PendingIntent type is unknown.
427      * @hide
428      */
429     public static final int INTENT_SENDER_UNKNOWN = 0;
430 
431     /**
432      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
433      * for a sendBroadcast operation.
434      * @hide
435      */
436     public static final int INTENT_SENDER_BROADCAST = 1;
437 
438     /**
439      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
440      * for a startActivity operation.
441      * @hide
442      */
443     @UnsupportedAppUsage
444     public static final int INTENT_SENDER_ACTIVITY = 2;
445 
446     /**
447      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
448      * for an activity result operation.
449      * @hide
450      */
451     public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
452 
453     /**
454      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
455      * for a startService operation.
456      * @hide
457      */
458     public static final int INTENT_SENDER_SERVICE = 4;
459 
460     /**
461      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
462      * for a startForegroundService operation.
463      * @hide
464      */
465     public static final int INTENT_SENDER_FOREGROUND_SERVICE = 5;
466 
467     /** @hide User operation call: success! */
468     public static final int USER_OP_SUCCESS = 0;
469 
470     /** @hide User operation call: given user id is not known. */
471     public static final int USER_OP_UNKNOWN_USER = -1;
472 
473     /** @hide User operation call: given user id is the current user, can't be stopped. */
474     public static final int USER_OP_IS_CURRENT = -2;
475 
476     /** @hide User operation call: system user can't be stopped. */
477     public static final int USER_OP_ERROR_IS_SYSTEM = -3;
478 
479     /** @hide User operation call: one of related users cannot be stopped. */
480     public static final int USER_OP_ERROR_RELATED_USERS_CANNOT_STOP = -4;
481 
482     /**
483      * Process states, describing the kind of state a particular process is in.
484      * When updating these, make sure to also check all related references to the
485      * constant in code, and update these arrays:
486      *
487      * @see com.android.internal.app.procstats.ProcessState#PROCESS_STATE_TO_STATE
488      * @see com.android.server.am.ProcessList#sProcStateToProcMem
489      * @see com.android.server.am.ProcessList#sFirstAwakePssTimes
490      * @see com.android.server.am.ProcessList#sSameAwakePssTimes
491      * @see com.android.server.am.ProcessList#sTestFirstPssTimes
492      * @see com.android.server.am.ProcessList#sTestSamePssTimes
493      * @hide
494      */
495     @IntDef(flag = false, prefix = { "PROCESS_STATE_" }, value = {
496         PROCESS_STATE_UNKNOWN, // -1
497         PROCESS_STATE_PERSISTENT, // 0
498         PROCESS_STATE_PERSISTENT_UI,
499         PROCESS_STATE_TOP,
500         PROCESS_STATE_BOUND_TOP,
501         PROCESS_STATE_FOREGROUND_SERVICE,
502         PROCESS_STATE_BOUND_FOREGROUND_SERVICE,
503         PROCESS_STATE_IMPORTANT_FOREGROUND,
504         PROCESS_STATE_IMPORTANT_BACKGROUND,
505         PROCESS_STATE_TRANSIENT_BACKGROUND,
506         PROCESS_STATE_BACKUP,
507         PROCESS_STATE_SERVICE,
508         PROCESS_STATE_RECEIVER,
509         PROCESS_STATE_TOP_SLEEPING,
510         PROCESS_STATE_HEAVY_WEIGHT,
511         PROCESS_STATE_HOME,
512         PROCESS_STATE_LAST_ACTIVITY,
513         PROCESS_STATE_CACHED_ACTIVITY,
514         PROCESS_STATE_CACHED_ACTIVITY_CLIENT,
515         PROCESS_STATE_CACHED_RECENT,
516         PROCESS_STATE_CACHED_EMPTY,
517     })
518     @Retention(RetentionPolicy.SOURCE)
519     public @interface ProcessState {}
520 
521     /*
522      * PROCESS_STATE_* must come from frameworks/base/core/java/android/app/ProcessStateEnum.aidl.
523      * This is to make sure that Java side uses the same values as native.
524      */
525 
526     /** @hide Not a real process state. */
527     public static final int PROCESS_STATE_UNKNOWN = ProcessStateEnum.UNKNOWN;
528 
529     /** @hide Process is a persistent system process. */
530     public static final int PROCESS_STATE_PERSISTENT = ProcessStateEnum.PERSISTENT;
531 
532     /** @hide Process is a persistent system process and is doing UI. */
533     public static final int PROCESS_STATE_PERSISTENT_UI = ProcessStateEnum.PERSISTENT_UI;
534 
535     /** @hide Process is hosting the current top activities.  Note that this covers
536      * all activities that are visible to the user. */
537     @UnsupportedAppUsage
538     @TestApi
539     public static final int PROCESS_STATE_TOP = ProcessStateEnum.TOP;
540 
541     /** @hide Process is bound to a TOP app. */
542     public static final int PROCESS_STATE_BOUND_TOP = ProcessStateEnum.BOUND_TOP;
543 
544     /** @hide Process is hosting a foreground service. */
545     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
546     @TestApi
547     public static final int PROCESS_STATE_FOREGROUND_SERVICE = ProcessStateEnum.FOREGROUND_SERVICE;
548 
549     /** @hide Process is hosting a foreground service due to a system binding. */
550     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
551     public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE =
552             ProcessStateEnum.BOUND_FOREGROUND_SERVICE;
553 
554     /** @hide Process is important to the user, and something they are aware of. */
555     public static final int PROCESS_STATE_IMPORTANT_FOREGROUND =
556             ProcessStateEnum.IMPORTANT_FOREGROUND;
557 
558     /** @hide Process is important to the user, but not something they are aware of. */
559     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
560     public static final int PROCESS_STATE_IMPORTANT_BACKGROUND =
561             ProcessStateEnum.IMPORTANT_BACKGROUND;
562 
563     /** @hide Process is in the background transient so we will try to keep running. */
564     public static final int PROCESS_STATE_TRANSIENT_BACKGROUND =
565             ProcessStateEnum.TRANSIENT_BACKGROUND;
566 
567     /** @hide Process is in the background running a backup/restore operation. */
568     public static final int PROCESS_STATE_BACKUP = ProcessStateEnum.BACKUP;
569 
570     /** @hide Process is in the background running a service.  Unlike oom_adj, this level
571      * is used for both the normal running in background state and the executing
572      * operations state. */
573     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
574     public static final int PROCESS_STATE_SERVICE = ProcessStateEnum.SERVICE;
575 
576     /** @hide Process is in the background running a receiver.   Note that from the
577      * perspective of oom_adj, receivers run at a higher foreground level, but for our
578      * prioritization here that is not necessary and putting them below services means
579      * many fewer changes in some process states as they receive broadcasts. */
580     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
581     public static final int PROCESS_STATE_RECEIVER = ProcessStateEnum.RECEIVER;
582 
583     /** @hide Same as {@link #PROCESS_STATE_TOP} but while device is sleeping. */
584     public static final int PROCESS_STATE_TOP_SLEEPING = ProcessStateEnum.TOP_SLEEPING;
585 
586     /** @hide Process is in the background, but it can't restore its state so we want
587      * to try to avoid killing it. */
588     public static final int PROCESS_STATE_HEAVY_WEIGHT = ProcessStateEnum.HEAVY_WEIGHT;
589 
590     /** @hide Process is in the background but hosts the home activity. */
591     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
592     public static final int PROCESS_STATE_HOME = ProcessStateEnum.HOME;
593 
594     /** @hide Process is in the background but hosts the last shown activity. */
595     public static final int PROCESS_STATE_LAST_ACTIVITY = ProcessStateEnum.LAST_ACTIVITY;
596 
597     /** @hide Process is being cached for later use and contains activities. */
598     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
599     public static final int PROCESS_STATE_CACHED_ACTIVITY = ProcessStateEnum.CACHED_ACTIVITY;
600 
601     /** @hide Process is being cached for later use and is a client of another cached
602      * process that contains activities. */
603     public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT =
604             ProcessStateEnum.CACHED_ACTIVITY_CLIENT;
605 
606     /** @hide Process is being cached for later use and has an activity that corresponds
607      * to an existing recent task. */
608     public static final int PROCESS_STATE_CACHED_RECENT = ProcessStateEnum.CACHED_RECENT;
609 
610     /** @hide Process is being cached for later use and is empty. */
611     public static final int PROCESS_STATE_CACHED_EMPTY = ProcessStateEnum.CACHED_EMPTY;
612 
613     /** @hide Process does not exist. */
614     public static final int PROCESS_STATE_NONEXISTENT = ProcessStateEnum.NONEXISTENT;
615 
616     /**
617      * The set of flags for process capability.
618      * @hide
619      */
620     @IntDef(flag = true, prefix = { "PROCESS_CAPABILITY_" }, value = {
621             PROCESS_CAPABILITY_NONE,
622             PROCESS_CAPABILITY_FOREGROUND_LOCATION,
623             PROCESS_CAPABILITY_FOREGROUND_CAMERA,
624             PROCESS_CAPABILITY_FOREGROUND_MICROPHONE,
625     })
626     @Retention(RetentionPolicy.SOURCE)
627     public @interface ProcessCapability {}
628 
629     /** @hide Process does not have any capability */
630     @TestApi
631     public static final int PROCESS_CAPABILITY_NONE = 0;
632 
633     /** @hide Process can access location while in foreground */
634     @TestApi
635     public static final int PROCESS_CAPABILITY_FOREGROUND_LOCATION = 1 << 0;
636 
637     /** @hide Process can access camera while in foreground */
638     @TestApi
639     public static final int PROCESS_CAPABILITY_FOREGROUND_CAMERA = 1 << 1;
640 
641     /** @hide Process can access microphone while in foreground */
642     @TestApi
643     public static final int PROCESS_CAPABILITY_FOREGROUND_MICROPHONE = 1 << 2;
644 
645     /** @hide Process can access network despite any power saving resrictions */
646     @TestApi
647     public static final int PROCESS_CAPABILITY_NETWORK = 1 << 3;
648 
649     /** @hide all capabilities, the ORing of all flags in {@link ProcessCapability}*/
650     @TestApi
651     public static final int PROCESS_CAPABILITY_ALL = PROCESS_CAPABILITY_FOREGROUND_LOCATION
652             | PROCESS_CAPABILITY_FOREGROUND_CAMERA
653             | PROCESS_CAPABILITY_FOREGROUND_MICROPHONE
654             | PROCESS_CAPABILITY_NETWORK;
655     /**
656      * All explicit capabilities. These are capabilities that need to be specified from manifest
657      * file.
658      * @hide
659      */
660     @TestApi
661     public static final int PROCESS_CAPABILITY_ALL_EXPLICIT =
662             PROCESS_CAPABILITY_FOREGROUND_LOCATION;
663 
664     /**
665      * All implicit capabilities. There are capabilities that process automatically have.
666      * @hide
667      */
668     @TestApi
669     public static final int PROCESS_CAPABILITY_ALL_IMPLICIT = PROCESS_CAPABILITY_FOREGROUND_CAMERA
670             | PROCESS_CAPABILITY_FOREGROUND_MICROPHONE;
671 
672     /**
673      * Print capability bits in human-readable form.
674      * @hide
675      */
printCapabilitiesSummary(PrintWriter pw, @ProcessCapability int caps)676     public static void printCapabilitiesSummary(PrintWriter pw, @ProcessCapability int caps) {
677         pw.print((caps & PROCESS_CAPABILITY_FOREGROUND_LOCATION) != 0 ? 'L' : '-');
678         pw.print((caps & PROCESS_CAPABILITY_FOREGROUND_CAMERA) != 0 ? 'C' : '-');
679         pw.print((caps & PROCESS_CAPABILITY_FOREGROUND_MICROPHONE) != 0 ? 'M' : '-');
680         pw.print((caps & PROCESS_CAPABILITY_NETWORK) != 0 ? 'N' : '-');
681     }
682 
683     /** @hide */
printCapabilitiesSummary(StringBuilder sb, @ProcessCapability int caps)684     public static void printCapabilitiesSummary(StringBuilder sb, @ProcessCapability int caps) {
685         sb.append((caps & PROCESS_CAPABILITY_FOREGROUND_LOCATION) != 0 ? 'L' : '-');
686         sb.append((caps & PROCESS_CAPABILITY_FOREGROUND_CAMERA) != 0 ? 'C' : '-');
687         sb.append((caps & PROCESS_CAPABILITY_FOREGROUND_MICROPHONE) != 0 ? 'M' : '-');
688         sb.append((caps & PROCESS_CAPABILITY_NETWORK) != 0 ? 'N' : '-');
689     }
690 
691     /**
692      * Print capability bits in human-readable form.
693      * @hide
694      */
printCapabilitiesFull(PrintWriter pw, @ProcessCapability int caps)695     public static void printCapabilitiesFull(PrintWriter pw, @ProcessCapability int caps) {
696         printCapabilitiesSummary(pw, caps);
697         final int remain = caps & ~(PROCESS_CAPABILITY_FOREGROUND_LOCATION
698                 | PROCESS_CAPABILITY_FOREGROUND_CAMERA
699                 | PROCESS_CAPABILITY_FOREGROUND_MICROPHONE
700                 | PROCESS_CAPABILITY_NETWORK);
701         if (remain != 0) {
702             pw.print('+');
703             pw.print(remain);
704         }
705     }
706 
707     /** @hide */
getCapabilitiesSummary(@rocessCapability int caps)708     public static String getCapabilitiesSummary(@ProcessCapability int caps) {
709         final StringBuilder sb = new StringBuilder();
710         printCapabilitiesSummary(sb, caps);
711         return sb.toString();
712     }
713 
714     // NOTE: If PROCESS_STATEs are added, then new fields must be added
715     // to frameworks/base/core/proto/android/app/enums.proto and the following method must
716     // be updated to correctly map between them.
717     // However, if the current ActivityManager values are merely modified, no update should be made
718     // to enums.proto, to which values can only be added but never modified. Note that the proto
719     // versions do NOT have the ordering restrictions of the ActivityManager process state.
720     /**
721      * Maps ActivityManager.PROCESS_STATE_ values to enums.proto ProcessStateEnum value.
722      *
723      * @param amInt a process state of the form ActivityManager.PROCESS_STATE_
724      * @return the value of the corresponding enums.proto ProcessStateEnum value.
725      * @hide
726      */
processStateAmToProto(int amInt)727     public static final int processStateAmToProto(int amInt) {
728         switch (amInt) {
729             case PROCESS_STATE_UNKNOWN:
730                 return AppProtoEnums.PROCESS_STATE_UNKNOWN;
731             case PROCESS_STATE_PERSISTENT:
732                 return AppProtoEnums.PROCESS_STATE_PERSISTENT;
733             case PROCESS_STATE_PERSISTENT_UI:
734                 return AppProtoEnums.PROCESS_STATE_PERSISTENT_UI;
735             case PROCESS_STATE_TOP:
736                 return AppProtoEnums.PROCESS_STATE_TOP;
737             case PROCESS_STATE_BOUND_TOP:
738                 return AppProtoEnums.PROCESS_STATE_BOUND_TOP;
739             case PROCESS_STATE_FOREGROUND_SERVICE:
740                 return AppProtoEnums.PROCESS_STATE_FOREGROUND_SERVICE;
741             case PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
742                 return AppProtoEnums.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
743             case PROCESS_STATE_IMPORTANT_FOREGROUND:
744                 return AppProtoEnums.PROCESS_STATE_IMPORTANT_FOREGROUND;
745             case PROCESS_STATE_IMPORTANT_BACKGROUND:
746                 return AppProtoEnums.PROCESS_STATE_IMPORTANT_BACKGROUND;
747             case PROCESS_STATE_TRANSIENT_BACKGROUND:
748                 return AppProtoEnums.PROCESS_STATE_TRANSIENT_BACKGROUND;
749             case PROCESS_STATE_BACKUP:
750                 return AppProtoEnums.PROCESS_STATE_BACKUP;
751             case PROCESS_STATE_SERVICE:
752                 return AppProtoEnums.PROCESS_STATE_SERVICE;
753             case PROCESS_STATE_RECEIVER:
754                 return AppProtoEnums.PROCESS_STATE_RECEIVER;
755             case PROCESS_STATE_TOP_SLEEPING:
756                 return AppProtoEnums.PROCESS_STATE_TOP_SLEEPING;
757             case PROCESS_STATE_HEAVY_WEIGHT:
758                 return AppProtoEnums.PROCESS_STATE_HEAVY_WEIGHT;
759             case PROCESS_STATE_HOME:
760                 return AppProtoEnums.PROCESS_STATE_HOME;
761             case PROCESS_STATE_LAST_ACTIVITY:
762                 return AppProtoEnums.PROCESS_STATE_LAST_ACTIVITY;
763             case PROCESS_STATE_CACHED_ACTIVITY:
764                 return AppProtoEnums.PROCESS_STATE_CACHED_ACTIVITY;
765             case PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
766                 return AppProtoEnums.PROCESS_STATE_CACHED_ACTIVITY_CLIENT;
767             case PROCESS_STATE_CACHED_RECENT:
768                 return AppProtoEnums.PROCESS_STATE_CACHED_RECENT;
769             case PROCESS_STATE_CACHED_EMPTY:
770                 return AppProtoEnums.PROCESS_STATE_CACHED_EMPTY;
771             case PROCESS_STATE_NONEXISTENT:
772                 return AppProtoEnums.PROCESS_STATE_NONEXISTENT;
773             default:
774                 // ActivityManager process state (amInt)
775                 // could not be mapped to an AppProtoEnums ProcessState state.
776                 return AppProtoEnums.PROCESS_STATE_UNKNOWN_TO_PROTO;
777         }
778     }
779 
780     /** @hide The lowest process state number */
781     public static final int MIN_PROCESS_STATE = PROCESS_STATE_PERSISTENT;
782 
783     /** @hide The highest process state number */
784     public static final int MAX_PROCESS_STATE = PROCESS_STATE_NONEXISTENT;
785 
786     /** @hide Should this process state be considered a background state? */
isProcStateBackground(int procState)787     public static final boolean isProcStateBackground(int procState) {
788         return procState >= PROCESS_STATE_TRANSIENT_BACKGROUND;
789     }
790 
791     /** @hide Should this process state be considered in the cache? */
isProcStateCached(int procState)792     public static final boolean isProcStateCached(int procState) {
793         return procState >= PROCESS_STATE_CACHED_ACTIVITY;
794     }
795 
796     /** @hide Is this a foreground service type? */
isForegroundService(int procState)797     public static boolean isForegroundService(int procState) {
798         return procState == PROCESS_STATE_FOREGROUND_SERVICE;
799     }
800 
801     /** @hide requestType for assist context: only basic information. */
802     public static final int ASSIST_CONTEXT_BASIC = 0;
803 
804     /** @hide requestType for assist context: generate full AssistStructure. */
805     public static final int ASSIST_CONTEXT_FULL = 1;
806 
807     /** @hide requestType for assist context: generate full AssistStructure for autofill. */
808     public static final int ASSIST_CONTEXT_AUTOFILL = 2;
809 
810     /** @hide requestType for assist context: generate AssistContent but not AssistStructure. */
811     public static final int ASSIST_CONTEXT_CONTENT = 3;
812 
813     /** @hide Flag for registerUidObserver: report changes in process state. */
814     public static final int UID_OBSERVER_PROCSTATE = 1<<0;
815 
816     /** @hide Flag for registerUidObserver: report uid gone. */
817     public static final int UID_OBSERVER_GONE = 1<<1;
818 
819     /** @hide Flag for registerUidObserver: report uid has become idle. */
820     public static final int UID_OBSERVER_IDLE = 1<<2;
821 
822     /** @hide Flag for registerUidObserver: report uid has become active. */
823     public static final int UID_OBSERVER_ACTIVE = 1<<3;
824 
825     /** @hide Flag for registerUidObserver: report uid cached state has changed. */
826     public static final int UID_OBSERVER_CACHED = 1<<4;
827 
828     /** @hide Flag for registerUidObserver: report uid capability has changed. */
829     public static final int UID_OBSERVER_CAPABILITY = 1<<5;
830 
831     /** @hide Flag for registerUidObserver: report pid oom adj has changed. */
832     public static final int UID_OBSERVER_PROC_OOM_ADJ = 1 << 6;
833 
834     /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: normal free-to-run operation. */
835     public static final int APP_START_MODE_NORMAL = 0;
836 
837     /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: delay running until later. */
838     public static final int APP_START_MODE_DELAYED = 1;
839 
840     /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: delay running until later, with
841      * rigid errors (throwing exception). */
842     public static final int APP_START_MODE_DELAYED_RIGID = 2;
843 
844     /** @hide Mode for {@link IActivityManager#isAppStartModeDisabled}: disable/cancel pending
845      * launches; this is the mode for ephemeral apps. */
846     public static final int APP_START_MODE_DISABLED = 3;
847 
848     /**
849      * Lock task mode is not active.
850      */
851     public static final int LOCK_TASK_MODE_NONE = 0;
852 
853     /**
854      * Full lock task mode is active.
855      */
856     public static final int LOCK_TASK_MODE_LOCKED = 1;
857 
858     /**
859      * App pinning mode is active.
860      */
861     public static final int LOCK_TASK_MODE_PINNED = 2;
862 
863     Point mAppTaskThumbnailSize;
864 
865     @UnsupportedAppUsage
ActivityManager(Context context, Handler handler)866     /*package*/ ActivityManager(Context context, Handler handler) {
867         mContext = context;
868     }
869 
870     /**
871      * Returns whether the launch was successful.
872      * @hide
873      */
isStartResultSuccessful(int result)874     public static final boolean isStartResultSuccessful(int result) {
875         return FIRST_START_SUCCESS_CODE <= result && result <= LAST_START_SUCCESS_CODE;
876     }
877 
878     /**
879      * Returns whether the launch result was a fatal error.
880      * @hide
881      */
isStartResultFatalError(int result)882     public static final boolean isStartResultFatalError(int result) {
883         return FIRST_START_FATAL_ERROR_CODE <= result && result <= LAST_START_FATAL_ERROR_CODE;
884     }
885 
886     /**
887      * Screen compatibility mode: the application most always run in
888      * compatibility mode.
889      * @hide
890      */
891     public static final int COMPAT_MODE_ALWAYS = -1;
892 
893     /**
894      * Screen compatibility mode: the application can never run in
895      * compatibility mode.
896      * @hide
897      */
898     public static final int COMPAT_MODE_NEVER = -2;
899 
900     /**
901      * Screen compatibility mode: unknown.
902      * @hide
903      */
904     public static final int COMPAT_MODE_UNKNOWN = -3;
905 
906     /**
907      * Screen compatibility mode: the application currently has compatibility
908      * mode disabled.
909      * @hide
910      */
911     public static final int COMPAT_MODE_DISABLED = 0;
912 
913     /**
914      * Screen compatibility mode: the application currently has compatibility
915      * mode enabled.
916      * @hide
917      */
918     public static final int COMPAT_MODE_ENABLED = 1;
919 
920     /**
921      * Screen compatibility mode: request to toggle the application's
922      * compatibility mode.
923      * @hide
924      */
925     public static final int COMPAT_MODE_TOGGLE = 2;
926 
927     private static final boolean DEVELOPMENT_FORCE_LOW_RAM =
928             SystemProperties.getBoolean("debug.force_low_ram", false);
929 
930     /**
931      * Intent {@link Intent#ACTION_CLOSE_SYSTEM_DIALOGS} is too powerful to be unrestricted. We
932      * restrict its usage for a few legitimate use-cases only, regardless of targetSdk. For the
933      * other use-cases we drop the intent with a log message.
934      *
935      * Note that this is the lighter version of {@link ActivityManager
936      * #LOCK_DOWN_CLOSE_SYSTEM_DIALOGS} which is not gated on targetSdk in order to eliminate the
937      * abuse vector.
938      *
939      * @hide
940      */
941     @ChangeId
942     public static final long DROP_CLOSE_SYSTEM_DIALOGS = 174664120L;
943 
944     /**
945      * Intent {@link Intent#ACTION_CLOSE_SYSTEM_DIALOGS} is too powerful to be unrestricted. So,
946      * apps targeting {@link Build.VERSION_CODES#S} or higher will crash if they try to send such
947      * intent and don't have permission {@code android.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS}.
948      *
949      * Note that this is the more restrict version of {@link ActivityManager
950      * #DROP_CLOSE_SYSTEM_DIALOGS} that expects the app to stop sending aforementioned intent once
951      * it bumps its targetSdk to {@link Build.VERSION_CODES#S} or higher.
952      *
953      * @hide
954      */
955     @TestApi
956     @ChangeId
957     @EnabledSince(targetSdkVersion = VERSION_CODES.S)
958     public static final long LOCK_DOWN_CLOSE_SYSTEM_DIALOGS = 174664365L;
959 
960     // The background process restriction levels. The definitions here are meant for internal
961     // bookkeeping only.
962 
963     /**
964      * Not a valid restriction level.
965      *
966      * @hide
967      */
968     public static final int RESTRICTION_LEVEL_UNKNOWN = 0;
969 
970     /**
971      * No background restrictions at all, this should NEVER be used
972      * for any process other than selected system processes, currently it's reserved.
973      *
974      * <p>In the future, apps in {@link #RESTRICTION_LEVEL_EXEMPTED} would receive permissive
975      * background restrictions to protect the system from buggy behaviors; in other words,
976      * the {@link #RESTRICTION_LEVEL_EXEMPTED} would not be the truly "unrestricted" state, while
977      * the {@link #RESTRICTION_LEVEL_UNRESTRICTED} here would be the last resort if there is
978      * a strong reason to grant such a capability to a system app. </p>
979      *
980      * @hide
981      */
982     public static final int RESTRICTION_LEVEL_UNRESTRICTED = 10;
983 
984     /**
985      * The default background restriction level for the "unrestricted" apps set by the user,
986      * where it'll have the {@link android.app.AppOpsManager#OP_RUN_ANY_IN_BACKGROUND} set to
987      * ALLOWED, being added into the device idle allow list; however there will be still certain
988      * restrictions to apps in this level.
989      *
990      * @hide
991      */
992     public static final int RESTRICTION_LEVEL_EXEMPTED = 20;
993 
994     /**
995      * The default background restriction level for all other apps, they'll be moved between
996      * various standby buckets, including
997      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_ACTIVE},
998      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_WORKING_SET},
999      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_FREQUENT},
1000      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RARE}.
1001      *
1002      * @hide
1003      */
1004     public static final int RESTRICTION_LEVEL_ADAPTIVE_BUCKET = 30;
1005 
1006     /**
1007      * The background restriction level where the apps will be placed in the restricted bucket
1008      * {@link android.app.usage.UsageStatsManager#STANDBY_BUCKET_RESTRICTED}.
1009      *
1010      * @hide
1011      */
1012     public static final int RESTRICTION_LEVEL_RESTRICTED_BUCKET = 40;
1013 
1014     /**
1015      * The background restricted level, where apps would get more restrictions,
1016      * such as not allowed to launch foreground services besides on TOP.
1017      *
1018      * @hide
1019      */
1020     public static final int RESTRICTION_LEVEL_BACKGROUND_RESTRICTED = 50;
1021 
1022     /**
1023      * The most restricted level where the apps are considered "in-hibernation",
1024      * its package visibility to the rest of the system is limited.
1025      *
1026      * @hide
1027      */
1028     public static final int RESTRICTION_LEVEL_HIBERNATION = 60;
1029 
1030     /**
1031      * Not a valid restriction level, it defines the maximum numerical value of restriction level.
1032      *
1033      * @hide
1034      */
1035     public static final int RESTRICTION_LEVEL_MAX = 100;
1036 
1037     /** @hide */
1038     @IntDef(prefix = { "RESTRICTION_LEVEL_" }, value = {
1039             RESTRICTION_LEVEL_UNKNOWN,
1040             RESTRICTION_LEVEL_UNRESTRICTED,
1041             RESTRICTION_LEVEL_EXEMPTED,
1042             RESTRICTION_LEVEL_ADAPTIVE_BUCKET,
1043             RESTRICTION_LEVEL_RESTRICTED_BUCKET,
1044             RESTRICTION_LEVEL_BACKGROUND_RESTRICTED,
1045             RESTRICTION_LEVEL_HIBERNATION,
1046             RESTRICTION_LEVEL_MAX,
1047     })
1048     @Retention(RetentionPolicy.SOURCE)
1049     public @interface RestrictionLevel{}
1050 
1051     /** @hide */
restrictionLevelToName(@estrictionLevel int level)1052     public static String restrictionLevelToName(@RestrictionLevel int level) {
1053         switch (level) {
1054             case RESTRICTION_LEVEL_UNKNOWN:
1055                 return "unknown";
1056             case RESTRICTION_LEVEL_UNRESTRICTED:
1057                 return "unrestricted";
1058             case RESTRICTION_LEVEL_EXEMPTED:
1059                 return "exempted";
1060             case RESTRICTION_LEVEL_ADAPTIVE_BUCKET:
1061                 return "adaptive_bucket";
1062             case RESTRICTION_LEVEL_RESTRICTED_BUCKET:
1063                 return "restricted_bucket";
1064             case RESTRICTION_LEVEL_BACKGROUND_RESTRICTED:
1065                 return "background_restricted";
1066             case RESTRICTION_LEVEL_HIBERNATION:
1067                 return "hibernation";
1068             case RESTRICTION_LEVEL_MAX:
1069                 return "max";
1070             default:
1071                 return "";
1072         }
1073     }
1074 
1075     /** @hide */
getFrontActivityScreenCompatMode()1076     public int getFrontActivityScreenCompatMode() {
1077         try {
1078             return getTaskService().getFrontActivityScreenCompatMode();
1079         } catch (RemoteException e) {
1080             throw e.rethrowFromSystemServer();
1081         }
1082     }
1083 
1084     /** @hide */
setFrontActivityScreenCompatMode(int mode)1085     public void setFrontActivityScreenCompatMode(int mode) {
1086         try {
1087             getTaskService().setFrontActivityScreenCompatMode(mode);
1088         } catch (RemoteException e) {
1089             throw e.rethrowFromSystemServer();
1090         }
1091     }
1092 
1093     /** @hide */
getPackageScreenCompatMode(String packageName)1094     public int getPackageScreenCompatMode(String packageName) {
1095         try {
1096             return getTaskService().getPackageScreenCompatMode(packageName);
1097         } catch (RemoteException e) {
1098             throw e.rethrowFromSystemServer();
1099         }
1100     }
1101 
1102     /** @hide */
setPackageScreenCompatMode(String packageName, int mode)1103     public void setPackageScreenCompatMode(String packageName, int mode) {
1104         try {
1105             getTaskService().setPackageScreenCompatMode(packageName, mode);
1106         } catch (RemoteException e) {
1107             throw e.rethrowFromSystemServer();
1108         }
1109     }
1110 
1111     /** @hide */
getPackageAskScreenCompat(String packageName)1112     public boolean getPackageAskScreenCompat(String packageName) {
1113         try {
1114             return getTaskService().getPackageAskScreenCompat(packageName);
1115         } catch (RemoteException e) {
1116             throw e.rethrowFromSystemServer();
1117         }
1118     }
1119 
1120     /** @hide */
setPackageAskScreenCompat(String packageName, boolean ask)1121     public void setPackageAskScreenCompat(String packageName, boolean ask) {
1122         try {
1123             getTaskService().setPackageAskScreenCompat(packageName, ask);
1124         } catch (RemoteException e) {
1125             throw e.rethrowFromSystemServer();
1126         }
1127     }
1128 
1129     /**
1130      * Return the approximate per-application memory class of the current
1131      * device.  This gives you an idea of how hard a memory limit you should
1132      * impose on your application to let the overall system work best.  The
1133      * returned value is in megabytes; the baseline Android memory class is
1134      * 16 (which happens to be the Java heap limit of those devices); some
1135      * devices with more memory may return 24 or even higher numbers.
1136      */
getMemoryClass()1137     public int getMemoryClass() {
1138         return staticGetMemoryClass();
1139     }
1140 
1141     /** @hide */
1142     @UnsupportedAppUsage
staticGetMemoryClass()1143     static public int staticGetMemoryClass() {
1144         // Really brain dead right now -- just take this from the configured
1145         // vm heap size, and assume it is in megabytes and thus ends with "m".
1146         String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
1147         if (vmHeapSize != null && !"".equals(vmHeapSize)) {
1148             return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
1149         }
1150         return staticGetLargeMemoryClass();
1151     }
1152 
1153     /**
1154      * Return the approximate per-application memory class of the current
1155      * device when an application is running with a large heap.  This is the
1156      * space available for memory-intensive applications; most applications
1157      * should not need this amount of memory, and should instead stay with the
1158      * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
1159      * This may be the same size as {@link #getMemoryClass()} on memory
1160      * constrained devices, or it may be significantly larger on devices with
1161      * a large amount of available RAM.
1162      *
1163      * <p>This is the size of the application's Dalvik heap if it has
1164      * specified <code>android:largeHeap="true"</code> in its manifest.
1165      */
getLargeMemoryClass()1166     public int getLargeMemoryClass() {
1167         return staticGetLargeMemoryClass();
1168     }
1169 
1170     /** @hide */
staticGetLargeMemoryClass()1171     static public int staticGetLargeMemoryClass() {
1172         // Really brain dead right now -- just take this from the configured
1173         // vm heap size, and assume it is in megabytes and thus ends with "m".
1174         String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
1175         return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1));
1176     }
1177 
1178     /**
1179      * Returns true if this is a low-RAM device.  Exactly whether a device is low-RAM
1180      * is ultimately up to the device configuration, but currently it generally means
1181      * something with 1GB or less of RAM.  This is mostly intended to be used by apps
1182      * to determine whether they should turn off certain features that require more RAM.
1183      */
isLowRamDevice()1184     public boolean isLowRamDevice() {
1185         return isLowRamDeviceStatic();
1186     }
1187 
1188     /** @hide */
1189     @UnsupportedAppUsage
isLowRamDeviceStatic()1190     public static boolean isLowRamDeviceStatic() {
1191         return RoSystemProperties.CONFIG_LOW_RAM ||
1192                 (Build.IS_DEBUGGABLE && DEVELOPMENT_FORCE_LOW_RAM);
1193     }
1194 
1195     /**
1196      * Returns true if this is a small battery device. Exactly whether a device is considered to be
1197      * small battery is ultimately up to the device configuration, but currently it generally means
1198      * something in the class of a device with 1000 mAh or less. This is mostly intended to be used
1199      * to determine whether certain features should be altered to account for a drastically smaller
1200      * battery.
1201      * @hide
1202      */
isSmallBatteryDevice()1203     public static boolean isSmallBatteryDevice() {
1204         return RoSystemProperties.CONFIG_SMALL_BATTERY;
1205     }
1206 
1207     /**
1208      * Used by persistent processes to determine if they are running on a
1209      * higher-end device so should be okay using hardware drawing acceleration
1210      * (which tends to consume a lot more RAM).
1211      * @hide
1212      */
1213     @TestApi
isHighEndGfx()1214     static public boolean isHighEndGfx() {
1215         return !isLowRamDeviceStatic()
1216                 && !RoSystemProperties.CONFIG_AVOID_GFX_ACCEL
1217                 && !Resources.getSystem()
1218                         .getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
1219     }
1220 
1221     /**
1222      * Return the total number of bytes of RAM this device has.
1223      * @hide
1224      */
1225     @TestApi
getTotalRam()1226     public long getTotalRam() {
1227         MemInfoReader memreader = new MemInfoReader();
1228         memreader.readMemInfo();
1229         return memreader.getTotalSize();
1230     }
1231 
1232     /**
1233      * TODO(b/80414790): Remove once no longer on hiddenapi-light-greylist.txt
1234      * @hide
1235      * @deprecated Use {@link ActivityTaskManager#getMaxRecentTasksStatic()}
1236      */
1237     @Deprecated
1238     @UnsupportedAppUsage
getMaxRecentTasksStatic()1239     static public int getMaxRecentTasksStatic() {
1240         return ActivityTaskManager.getMaxRecentTasksStatic();
1241     }
1242 
1243     /**
1244      * Information you can set and retrieve about the current activity within the recent task list.
1245      */
1246     public static class TaskDescription implements Parcelable {
1247         /** @hide */
1248         public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_";
1249         private static final String ATTR_TASKDESCRIPTIONLABEL =
1250                 ATTR_TASKDESCRIPTION_PREFIX + "label";
1251         private static final String ATTR_TASKDESCRIPTIONCOLOR_PRIMARY =
1252                 ATTR_TASKDESCRIPTION_PREFIX + "color";
1253         private static final String ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND =
1254                 ATTR_TASKDESCRIPTION_PREFIX + "color_background";
1255         private static final String ATTR_TASKDESCRIPTIONICON_FILENAME =
1256                 ATTR_TASKDESCRIPTION_PREFIX + "icon_filename";
1257         private static final String ATTR_TASKDESCRIPTIONICON_RESOURCE =
1258                 ATTR_TASKDESCRIPTION_PREFIX + "icon_resource";
1259         private static final String ATTR_TASKDESCRIPTIONICON_RESOURCE_PACKAGE =
1260                 ATTR_TASKDESCRIPTION_PREFIX + "icon_package";
1261         private static final String ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND_FLOATING =
1262                 ATTR_TASKDESCRIPTION_PREFIX + "color_background_floating";
1263 
1264         private String mLabel;
1265         @Nullable
1266         private Icon mIcon;
1267         private String mIconFilename;
1268         private int mColorPrimary;
1269         private int mColorBackground;
1270         private int mColorBackgroundFloating;
1271         private int mStatusBarColor;
1272         private int mNavigationBarColor;
1273         private boolean mEnsureStatusBarContrastWhenTransparent;
1274         private boolean mEnsureNavigationBarContrastWhenTransparent;
1275         private int mResizeMode;
1276         private int mMinWidth;
1277         private int mMinHeight;
1278 
1279         /**
1280          * Provides a convenient way to set the fields of a {@link TaskDescription} when creating a
1281          * new instance.
1282          */
1283         public static final class Builder {
1284             /**
1285              * Default values for the TaskDescription
1286              */
1287             @Nullable
1288             private String mLabel = null;
1289             @DrawableRes
1290             private int mIconRes = Resources.ID_NULL;
1291             private int mPrimaryColor = 0;
1292             private int mBackgroundColor = 0;
1293             private int mStatusBarColor = 0;
1294             private int mNavigationBarColor = 0;
1295 
1296             /**
1297              * Set the label to use in the TaskDescription.
1298              * @param label A label and description of the current state of this activity.
1299              * @return The same instance of the builder.
1300              */
1301             @NonNull
setLabel(@ullable String label)1302             public Builder setLabel(@Nullable String label) {
1303                 this.mLabel = label;
1304                 return this;
1305             }
1306 
1307             /**
1308              * Set the drawable resource of the icon to use in the TaskDescription.
1309              * @param iconRes A drawable resource of an icon that represents the current state of
1310              *                this activity.
1311              * @return The same instance of the builder.
1312              */
1313             @NonNull
setIcon(@rawableRes int iconRes)1314             public Builder setIcon(@DrawableRes int iconRes) {
1315                 this.mIconRes = iconRes;
1316                 return this;
1317             }
1318 
1319             /**
1320              * Set the primary color to use in the TaskDescription.
1321              * @param color A color to override the theme's primary color. The color must be opaque.
1322              * @return The same instance of the builder.
1323              */
1324             @NonNull
setPrimaryColor(@olorInt int color)1325             public Builder setPrimaryColor(@ColorInt int color) {
1326                 this.mPrimaryColor = color;
1327                 return this;
1328             }
1329 
1330             /**
1331              * Set the background color to use in the TaskDescription.
1332              * @param color A color to override the theme's background color. The color must be
1333              *              opaque.
1334              * @return The same instance of the builder.
1335              */
1336             @NonNull
setBackgroundColor(@olorInt int color)1337             public Builder setBackgroundColor(@ColorInt int color) {
1338                 this.mBackgroundColor = color;
1339                 return this;
1340             }
1341 
1342             /**
1343              * Set the status bar color to use in the TaskDescription.
1344              * @param color A color to override the theme's status bar color.
1345              * @return The same instance of the builder.
1346              */
1347             @NonNull
setStatusBarColor(@olorInt int color)1348             public Builder setStatusBarColor(@ColorInt int color) {
1349                 this.mStatusBarColor = color;
1350                 return this;
1351             }
1352 
1353             /**
1354              * Set the navigation bar color to use in the TaskDescription.
1355              * @param color A color to override the theme's navigation bar color.
1356              * @return The same instance of the builder.
1357              */
1358             @NonNull
setNavigationBarColor(@olorInt int color)1359             public Builder setNavigationBarColor(@ColorInt int color) {
1360                 this.mNavigationBarColor = color;
1361                 return this;
1362             }
1363 
1364             /**
1365              * Build the TaskDescription.
1366              * @return the TaskDescription object.
1367              */
1368             @NonNull
build()1369             public TaskDescription build() {
1370                 final Icon icon = mIconRes == Resources.ID_NULL ? null :
1371                         Icon.createWithResource(ActivityThread.currentPackageName(), mIconRes);
1372                 return new TaskDescription(mLabel, icon, mPrimaryColor, mBackgroundColor,
1373                         mStatusBarColor, mNavigationBarColor, false, false, RESIZE_MODE_RESIZEABLE,
1374                         -1, -1, 0);
1375             }
1376         }
1377 
1378         /**
1379          * Creates the TaskDescription to the specified values.
1380          *
1381          * @param label A label and description of the current state of this task.
1382          * @param iconRes A drawable resource of an icon that represents the current state of this
1383          *                activity.
1384          * @param colorPrimary A color to override the theme's primary color.  This color must be
1385          *                     opaque.
1386          *
1387          * @deprecated Use {@link Builder} instead.
1388          */
1389         @Deprecated
TaskDescription(String label, @DrawableRes int iconRes, int colorPrimary)1390         public TaskDescription(String label, @DrawableRes int iconRes, int colorPrimary) {
1391             this(label, Icon.createWithResource(ActivityThread.currentPackageName(), iconRes),
1392                     colorPrimary, 0, 0, 0, false, false, RESIZE_MODE_RESIZEABLE, -1, -1, 0);
1393             if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
1394                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
1395             }
1396         }
1397 
1398         /**
1399          * Creates the TaskDescription to the specified values.
1400          *
1401          * @param label A label and description of the current state of this activity.
1402          * @param iconRes A drawable resource of an icon that represents the current state of this
1403          *                activity.
1404          *
1405          * @deprecated Use {@link Builder} instead.
1406          */
1407         @Deprecated
TaskDescription(String label, @DrawableRes int iconRes)1408         public TaskDescription(String label, @DrawableRes int iconRes) {
1409             this(label, Icon.createWithResource(ActivityThread.currentPackageName(), iconRes),
1410                     0, 0, 0, 0, false, false, RESIZE_MODE_RESIZEABLE, -1, -1, 0);
1411         }
1412 
1413         /**
1414          * Creates the TaskDescription to the specified values.
1415          *
1416          * @param label A label and description of the current state of this activity.
1417          *
1418          * @deprecated Use {@link Builder} instead.
1419          */
1420         @Deprecated
TaskDescription(String label)1421         public TaskDescription(String label) {
1422             this(label, null, 0, 0, 0, 0, false, false, RESIZE_MODE_RESIZEABLE, -1, -1, 0);
1423         }
1424 
1425         /**
1426          * Creates an empty TaskDescription.
1427          *
1428          * @deprecated Use {@link Builder} instead.
1429          */
1430         @Deprecated
TaskDescription()1431         public TaskDescription() {
1432             this(null, null, 0, 0, 0, 0, false, false, RESIZE_MODE_RESIZEABLE, -1, -1, 0);
1433         }
1434 
1435         /**
1436          * Creates the TaskDescription to the specified values.
1437          *
1438          * @param label A label and description of the current state of this task.
1439          * @param icon An icon that represents the current state of this task.
1440          * @param colorPrimary A color to override the theme's primary color.  This color must be
1441          *                     opaque.
1442          *
1443          * @deprecated Use {@link Builder} instead.
1444          */
1445         @Deprecated
TaskDescription(String label, Bitmap icon, int colorPrimary)1446         public TaskDescription(String label, Bitmap icon, int colorPrimary) {
1447             this(label, icon != null ? Icon.createWithBitmap(icon) : null, colorPrimary, 0, 0, 0,
1448                     false, false, RESIZE_MODE_RESIZEABLE, -1, -1, 0);
1449             if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
1450                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
1451             }
1452         }
1453 
1454         /**
1455          * Creates the TaskDescription to the specified values.
1456          *
1457          * @param label A label and description of the current state of this activity.
1458          * @param icon An icon that represents the current state of this activity.
1459          *
1460          * @deprecated Use {@link Builder} instead.
1461          */
1462         @Deprecated
TaskDescription(String label, Bitmap icon)1463         public TaskDescription(String label, Bitmap icon) {
1464             this(label, icon != null ? Icon.createWithBitmap(icon) : null, 0, 0, 0, 0, false, false,
1465                     RESIZE_MODE_RESIZEABLE, -1, -1, 0);
1466         }
1467 
1468         /** @hide */
TaskDescription(@ullable String label, @Nullable Icon icon, int colorPrimary, int colorBackground, int statusBarColor, int navigationBarColor, boolean ensureStatusBarContrastWhenTransparent, boolean ensureNavigationBarContrastWhenTransparent, int resizeMode, int minWidth, int minHeight, int colorBackgroundFloating)1469         public TaskDescription(@Nullable String label, @Nullable Icon icon,
1470                 int colorPrimary, int colorBackground,
1471                 int statusBarColor, int navigationBarColor,
1472                 boolean ensureStatusBarContrastWhenTransparent,
1473                 boolean ensureNavigationBarContrastWhenTransparent, int resizeMode, int minWidth,
1474                 int minHeight, int colorBackgroundFloating) {
1475             mLabel = label;
1476             mIcon = icon;
1477             mColorPrimary = colorPrimary;
1478             mColorBackground = colorBackground;
1479             mStatusBarColor = statusBarColor;
1480             mNavigationBarColor = navigationBarColor;
1481             mEnsureStatusBarContrastWhenTransparent = ensureStatusBarContrastWhenTransparent;
1482             mEnsureNavigationBarContrastWhenTransparent =
1483                     ensureNavigationBarContrastWhenTransparent;
1484             mResizeMode = resizeMode;
1485             mMinWidth = minWidth;
1486             mMinHeight = minHeight;
1487             mColorBackgroundFloating = colorBackgroundFloating;
1488         }
1489 
1490         /**
1491          * Creates a copy of another TaskDescription.
1492          */
TaskDescription(TaskDescription td)1493         public TaskDescription(TaskDescription td) {
1494             copyFrom(td);
1495         }
1496 
1497         /**
1498          * Copies this the values from another TaskDescription.
1499          * @hide
1500          */
copyFrom(TaskDescription other)1501         public void copyFrom(TaskDescription other) {
1502             mLabel = other.mLabel;
1503             mIcon = other.mIcon;
1504             mIconFilename = other.mIconFilename;
1505             mColorPrimary = other.mColorPrimary;
1506             mColorBackground = other.mColorBackground;
1507             mStatusBarColor = other.mStatusBarColor;
1508             mNavigationBarColor = other.mNavigationBarColor;
1509             mEnsureStatusBarContrastWhenTransparent = other.mEnsureStatusBarContrastWhenTransparent;
1510             mEnsureNavigationBarContrastWhenTransparent =
1511                     other.mEnsureNavigationBarContrastWhenTransparent;
1512             mResizeMode = other.mResizeMode;
1513             mMinWidth = other.mMinWidth;
1514             mMinHeight = other.mMinHeight;
1515             mColorBackgroundFloating = other.mColorBackgroundFloating;
1516         }
1517 
1518         /**
1519          * Copies values from another TaskDescription, but preserves the hidden fields if they
1520          * weren't set on {@code other}. Public fields will be overwritten anyway.
1521          * @hide
1522          */
copyFromPreserveHiddenFields(TaskDescription other)1523         public void copyFromPreserveHiddenFields(TaskDescription other) {
1524             mLabel = other.mLabel;
1525             mIcon = other.mIcon;
1526             mIconFilename = other.mIconFilename;
1527             mColorPrimary = other.mColorPrimary;
1528 
1529             if (other.mColorBackground != 0) {
1530                 mColorBackground = other.mColorBackground;
1531             }
1532             if (other.mStatusBarColor != 0) {
1533                 mStatusBarColor = other.mStatusBarColor;
1534             }
1535             if (other.mNavigationBarColor != 0) {
1536                 mNavigationBarColor = other.mNavigationBarColor;
1537             }
1538 
1539             mEnsureStatusBarContrastWhenTransparent = other.mEnsureStatusBarContrastWhenTransparent;
1540             mEnsureNavigationBarContrastWhenTransparent =
1541                     other.mEnsureNavigationBarContrastWhenTransparent;
1542 
1543             if (other.mResizeMode != RESIZE_MODE_RESIZEABLE) {
1544                 mResizeMode = other.mResizeMode;
1545             }
1546             if (other.mMinWidth != -1) {
1547                 mMinWidth = other.mMinWidth;
1548             }
1549             if (other.mMinHeight != -1) {
1550                 mMinHeight = other.mMinHeight;
1551             }
1552             if (other.mColorBackgroundFloating != 0) {
1553                 mColorBackgroundFloating = other.mColorBackgroundFloating;
1554             }
1555         }
1556 
TaskDescription(Parcel source)1557         private TaskDescription(Parcel source) {
1558             readFromParcel(source);
1559         }
1560 
1561         /**
1562          * Sets the label for this task description.
1563          * @hide
1564          */
setLabel(String label)1565         public void setLabel(String label) {
1566             mLabel = label;
1567         }
1568 
1569         /**
1570          * Sets the primary color for this task description.
1571          * @hide
1572          */
setPrimaryColor(int primaryColor)1573         public void setPrimaryColor(int primaryColor) {
1574             // Ensure that the given color is valid
1575             if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) {
1576                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
1577             }
1578             mColorPrimary = primaryColor;
1579         }
1580 
1581         /**
1582          * Sets the background color for this task description.
1583          * @hide
1584          */
setBackgroundColor(int backgroundColor)1585         public void setBackgroundColor(int backgroundColor) {
1586             // Ensure that the given color is valid
1587             if ((backgroundColor != 0) && (Color.alpha(backgroundColor) != 255)) {
1588                 throw new RuntimeException("A TaskDescription's background color should be opaque");
1589             }
1590             mColorBackground = backgroundColor;
1591         }
1592 
1593         /**
1594          * Sets the background color floating for this task description.
1595          * @hide
1596          */
setBackgroundColorFloating(int backgroundColor)1597         public void setBackgroundColorFloating(int backgroundColor) {
1598             // Ensure that the given color is valid
1599             if ((backgroundColor != 0) && (Color.alpha(backgroundColor) != 255)) {
1600                 throw new RuntimeException(
1601                         "A TaskDescription's background color floating should be opaque");
1602             }
1603             mColorBackgroundFloating = backgroundColor;
1604         }
1605 
1606         /**
1607          * @hide
1608          */
setStatusBarColor(int statusBarColor)1609         public void setStatusBarColor(int statusBarColor) {
1610             mStatusBarColor = statusBarColor;
1611         }
1612 
1613         /**
1614          * @hide
1615          */
setNavigationBarColor(int navigationBarColor)1616         public void setNavigationBarColor(int navigationBarColor) {
1617             mNavigationBarColor = navigationBarColor;
1618         }
1619 
1620         /**
1621          * Sets the icon resource for this task description.
1622          * @hide
1623          */
setIcon(Icon icon)1624         public void setIcon(Icon icon) {
1625             mIcon = icon;
1626         }
1627 
1628         /**
1629          * Moves the icon bitmap reference from an actual Bitmap to a file containing the
1630          * bitmap.
1631          * @hide
1632          */
setIconFilename(String iconFilename)1633         public void setIconFilename(String iconFilename) {
1634             mIconFilename = iconFilename;
1635             if (iconFilename != null) {
1636                 // Only reset the icon if an actual persisted icon filepath was set
1637                 mIcon = null;
1638             }
1639         }
1640 
1641         /**
1642          * Sets the resize mode for this task description. Resize mode as in
1643          * {@link android.content.pm.ActivityInfo}.
1644          * @hide
1645          */
setResizeMode(int resizeMode)1646         public void setResizeMode(int resizeMode) {
1647             mResizeMode = resizeMode;
1648         }
1649 
1650         /**
1651          * The minimal width size to show the app content in freeform mode.
1652          * @param minWidth minimal width, -1 for system default.
1653          * @hide
1654          */
setMinWidth(int minWidth)1655         public void setMinWidth(int minWidth) {
1656             mMinWidth = minWidth;
1657         }
1658 
1659         /**
1660          * The minimal height size to show the app content in freeform mode.
1661          * @param minHeight minimal height, -1 for system default.
1662          * @hide
1663          */
setMinHeight(int minHeight)1664         public void setMinHeight(int minHeight) {
1665             mMinHeight = minHeight;
1666         }
1667 
1668         /**
1669          * @return The label and description of the current state of this task.
1670          */
getLabel()1671         public String getLabel() {
1672             return mLabel;
1673         }
1674 
1675         /**
1676          * @return The actual icon that represents the current state of this task if it is in memory
1677          *         or loads it from disk if available.
1678          * @hide
1679          */
loadIcon()1680         public Icon loadIcon() {
1681             if (mIcon != null) {
1682                 return mIcon;
1683             }
1684             Bitmap loadedIcon = loadTaskDescriptionIcon(mIconFilename, UserHandle.myUserId());
1685             if (loadedIcon != null) {
1686                 return Icon.createWithBitmap(loadedIcon);
1687             }
1688             return null;
1689         }
1690 
1691         /**
1692          * @return The in-memory or loaded icon that represents the current state of this task.
1693          * @deprecated This call is no longer supported. The caller should keep track of any icons
1694          *             it sets for the task descriptions internally.
1695          */
1696         @Deprecated
getIcon()1697         public Bitmap getIcon() {
1698             Bitmap icon = getInMemoryIcon();
1699             if (icon != null) {
1700                 return icon;
1701             }
1702             return loadTaskDescriptionIcon(mIconFilename, UserHandle.myUserId());
1703         }
1704 
1705         /** @hide */
1706         @Nullable
getRawIcon()1707         public Icon getRawIcon() {
1708             return mIcon;
1709         }
1710 
1711         /** @hide */
1712         @TestApi
1713         @Nullable
getIconResourcePackage()1714         public String getIconResourcePackage() {
1715             if (mIcon != null && mIcon.getType() == Icon.TYPE_RESOURCE) {
1716                 return mIcon.getResPackage();
1717             }
1718             return "";
1719         }
1720 
1721         /** @hide */
1722         @TestApi
getIconResource()1723         public int getIconResource() {
1724             if (mIcon != null && mIcon.getType() == Icon.TYPE_RESOURCE) {
1725                 return mIcon.getResId();
1726             }
1727             return 0;
1728         }
1729 
1730         /** @hide */
1731         @TestApi
getIconFilename()1732         public String getIconFilename() {
1733             return mIconFilename;
1734         }
1735 
1736         /** @hide */
1737         @UnsupportedAppUsage
getInMemoryIcon()1738         public Bitmap getInMemoryIcon() {
1739             if (mIcon != null && mIcon.getType() == Icon.TYPE_BITMAP) {
1740                 return mIcon.getBitmap();
1741             }
1742             return null;
1743         }
1744 
1745         /** @hide */
1746         @UnsupportedAppUsage
loadTaskDescriptionIcon(String iconFilename, int userId)1747         public static Bitmap loadTaskDescriptionIcon(String iconFilename, int userId) {
1748             if (iconFilename != null) {
1749                 try {
1750                     return getTaskService().getTaskDescriptionIcon(iconFilename,
1751                             userId);
1752                 } catch (RemoteException e) {
1753                     throw e.rethrowFromSystemServer();
1754                 }
1755             }
1756             return null;
1757         }
1758 
1759         /**
1760          * @return The color override on the theme's primary color.
1761          */
1762         @ColorInt
getPrimaryColor()1763         public int getPrimaryColor() {
1764             return mColorPrimary;
1765         }
1766 
1767         /**
1768          * @return The color override on the theme's background color.
1769          */
1770         @ColorInt
getBackgroundColor()1771         public int getBackgroundColor() {
1772             return mColorBackground;
1773         }
1774 
1775         /**
1776          * @return The background color floating.
1777          * @hide
1778          */
getBackgroundColorFloating()1779         public int getBackgroundColorFloating() {
1780             return mColorBackgroundFloating;
1781         }
1782 
1783         /**
1784          * @return The color override on the theme's status bar color.
1785          */
1786         @ColorInt
getStatusBarColor()1787         public int getStatusBarColor() {
1788             return mStatusBarColor;
1789         }
1790 
1791         /**
1792          * @return The color override on the theme's navigation bar color.
1793          */
1794         @ColorInt
getNavigationBarColor()1795         public int getNavigationBarColor() {
1796             return mNavigationBarColor;
1797         }
1798 
1799         /**
1800          * @hide
1801          */
getEnsureStatusBarContrastWhenTransparent()1802         public boolean getEnsureStatusBarContrastWhenTransparent() {
1803             return mEnsureStatusBarContrastWhenTransparent;
1804         }
1805 
1806         /**
1807          * @hide
1808          */
setEnsureStatusBarContrastWhenTransparent( boolean ensureStatusBarContrastWhenTransparent)1809         public void setEnsureStatusBarContrastWhenTransparent(
1810                 boolean ensureStatusBarContrastWhenTransparent) {
1811             mEnsureStatusBarContrastWhenTransparent = ensureStatusBarContrastWhenTransparent;
1812         }
1813 
1814         /**
1815          * @hide
1816          */
getEnsureNavigationBarContrastWhenTransparent()1817         public boolean getEnsureNavigationBarContrastWhenTransparent() {
1818             return mEnsureNavigationBarContrastWhenTransparent;
1819         }
1820 
1821         /**
1822          * @hide
1823          */
setEnsureNavigationBarContrastWhenTransparent( boolean ensureNavigationBarContrastWhenTransparent)1824         public void setEnsureNavigationBarContrastWhenTransparent(
1825                 boolean ensureNavigationBarContrastWhenTransparent) {
1826             mEnsureNavigationBarContrastWhenTransparent =
1827                     ensureNavigationBarContrastWhenTransparent;
1828         }
1829 
1830         /**
1831          * @hide
1832          */
getResizeMode()1833         public int getResizeMode() {
1834             return mResizeMode;
1835         }
1836 
1837         /**
1838          * @hide
1839          */
getMinWidth()1840         public int getMinWidth() {
1841             return mMinWidth;
1842         }
1843 
1844         /**
1845          * @hide
1846          */
getMinHeight()1847         public int getMinHeight() {
1848             return mMinHeight;
1849         }
1850 
1851         /** @hide */
saveToXml(TypedXmlSerializer out)1852         public void saveToXml(TypedXmlSerializer out) throws IOException {
1853             if (mLabel != null) {
1854                 out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel);
1855             }
1856             if (mColorPrimary != 0) {
1857                 out.attributeIntHex(null, ATTR_TASKDESCRIPTIONCOLOR_PRIMARY, mColorPrimary);
1858             }
1859             if (mColorBackground != 0) {
1860                 out.attributeIntHex(null, ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND, mColorBackground);
1861             }
1862             if (mColorBackgroundFloating != 0) {
1863                 out.attributeIntHex(null, ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND_FLOATING,
1864                         mColorBackgroundFloating);
1865             }
1866             if (mIconFilename != null) {
1867                 out.attribute(null, ATTR_TASKDESCRIPTIONICON_FILENAME, mIconFilename);
1868             }
1869             if (mIcon != null && mIcon.getType() == Icon.TYPE_RESOURCE) {
1870                 out.attributeInt(null, ATTR_TASKDESCRIPTIONICON_RESOURCE, mIcon.getResId());
1871                 out.attribute(null, ATTR_TASKDESCRIPTIONICON_RESOURCE_PACKAGE,
1872                         mIcon.getResPackage());
1873             }
1874         }
1875 
1876         /** @hide */
restoreFromXml(TypedXmlPullParser in)1877         public void restoreFromXml(TypedXmlPullParser in) {
1878             final String label = in.getAttributeValue(null, ATTR_TASKDESCRIPTIONLABEL);
1879             if (label != null) {
1880                 setLabel(label);
1881             }
1882             final int colorPrimary = in.getAttributeIntHex(null,
1883                     ATTR_TASKDESCRIPTIONCOLOR_PRIMARY, 0);
1884             if (colorPrimary != 0) {
1885                 setPrimaryColor(colorPrimary);
1886             }
1887             final int colorBackground = in.getAttributeIntHex(null,
1888                     ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND, 0);
1889             if (colorBackground != 0) {
1890                 setBackgroundColor(colorBackground);
1891             }
1892             final int colorBackgroundFloating = in.getAttributeIntHex(null,
1893                     ATTR_TASKDESCRIPTIONCOLOR_BACKGROUND_FLOATING, 0);
1894             if (colorBackgroundFloating != 0) {
1895                 setBackgroundColorFloating(colorBackgroundFloating);
1896             }
1897             final String iconFilename = in.getAttributeValue(null,
1898                     ATTR_TASKDESCRIPTIONICON_FILENAME);
1899             if (iconFilename != null) {
1900                 setIconFilename(iconFilename);
1901             }
1902             final int iconResourceId = in.getAttributeInt(null,
1903                     ATTR_TASKDESCRIPTIONICON_RESOURCE, Resources.ID_NULL);
1904             final String iconResourcePackage = in.getAttributeValue(null,
1905                     ATTR_TASKDESCRIPTIONICON_RESOURCE_PACKAGE);
1906             if (iconResourceId != Resources.ID_NULL && iconResourcePackage != null) {
1907                 setIcon(Icon.createWithResource(iconResourcePackage,
1908                         iconResourceId));
1909             }
1910         }
1911 
1912         @Override
describeContents()1913         public int describeContents() {
1914             return 0;
1915         }
1916 
1917         @Override
writeToParcel(Parcel dest, int flags)1918         public void writeToParcel(Parcel dest, int flags) {
1919             if (mLabel == null) {
1920                 dest.writeInt(0);
1921             } else {
1922                 dest.writeInt(1);
1923                 dest.writeString(mLabel);
1924             }
1925             final Bitmap bitmapIcon = getInMemoryIcon();
1926             if (mIcon == null || (bitmapIcon != null && bitmapIcon.isRecycled())) {
1927                 // If there is no icon, or if the icon is a bitmap that has been recycled, then
1928                 // don't write anything to disk
1929                 dest.writeInt(0);
1930             } else {
1931                 dest.writeInt(1);
1932                 mIcon.writeToParcel(dest, 0);
1933             }
1934             dest.writeInt(mColorPrimary);
1935             dest.writeInt(mColorBackground);
1936             dest.writeInt(mStatusBarColor);
1937             dest.writeInt(mNavigationBarColor);
1938             dest.writeBoolean(mEnsureStatusBarContrastWhenTransparent);
1939             dest.writeBoolean(mEnsureNavigationBarContrastWhenTransparent);
1940             dest.writeInt(mResizeMode);
1941             dest.writeInt(mMinWidth);
1942             dest.writeInt(mMinHeight);
1943             if (mIconFilename == null) {
1944                 dest.writeInt(0);
1945             } else {
1946                 dest.writeInt(1);
1947                 dest.writeString(mIconFilename);
1948             }
1949             dest.writeInt(mColorBackgroundFloating);
1950         }
1951 
readFromParcel(Parcel source)1952         public void readFromParcel(Parcel source) {
1953             mLabel = source.readInt() > 0 ? source.readString() : null;
1954             if (source.readInt() > 0) {
1955                 mIcon = Icon.CREATOR.createFromParcel(source);
1956             }
1957             mColorPrimary = source.readInt();
1958             mColorBackground = source.readInt();
1959             mStatusBarColor = source.readInt();
1960             mNavigationBarColor = source.readInt();
1961             mEnsureStatusBarContrastWhenTransparent = source.readBoolean();
1962             mEnsureNavigationBarContrastWhenTransparent = source.readBoolean();
1963             mResizeMode = source.readInt();
1964             mMinWidth = source.readInt();
1965             mMinHeight = source.readInt();
1966             mIconFilename = source.readInt() > 0 ? source.readString() : null;
1967             mColorBackgroundFloating = source.readInt();
1968         }
1969 
1970         public static final @android.annotation.NonNull Creator<TaskDescription> CREATOR
1971                 = new Creator<TaskDescription>() {
1972             public TaskDescription createFromParcel(Parcel source) {
1973                 return new TaskDescription(source);
1974             }
1975             public TaskDescription[] newArray(int size) {
1976                 return new TaskDescription[size];
1977             }
1978         };
1979 
1980         @Override
toString()1981         public String toString() {
1982             return "TaskDescription Label: " + mLabel + " Icon: " + mIcon
1983                     + " IconFilename: " + mIconFilename
1984                     + " colorPrimary: " + mColorPrimary + " colorBackground: " + mColorBackground
1985                     + " statusBarColor: " + mStatusBarColor
1986                     + (mEnsureStatusBarContrastWhenTransparent ? " (contrast when transparent)"
1987                             : "") + " navigationBarColor: " + mNavigationBarColor
1988                     + (mEnsureNavigationBarContrastWhenTransparent
1989                             ? " (contrast when transparent)" : "")
1990                     + " resizeMode: " + ActivityInfo.resizeModeToString(mResizeMode)
1991                     + " minWidth: " + mMinWidth + " minHeight: " + mMinHeight
1992                     + " colorBackgrounFloating: " + mColorBackgroundFloating;
1993         }
1994 
1995         @Override
equals(@ullable Object obj)1996         public boolean equals(@Nullable Object obj) {
1997             if (!(obj instanceof TaskDescription)) {
1998                 return false;
1999             }
2000 
2001             TaskDescription other = (TaskDescription) obj;
2002             return TextUtils.equals(mLabel, other.mLabel)
2003                     && TextUtils.equals(mIconFilename, other.mIconFilename)
2004                     && mIcon == other.mIcon
2005                     && mColorPrimary == other.mColorPrimary
2006                     && mColorBackground == other.mColorBackground
2007                     && mStatusBarColor == other.mStatusBarColor
2008                     && mNavigationBarColor == other.mNavigationBarColor
2009                     && mEnsureStatusBarContrastWhenTransparent
2010                             == other.mEnsureStatusBarContrastWhenTransparent
2011                     && mEnsureNavigationBarContrastWhenTransparent
2012                             == other.mEnsureNavigationBarContrastWhenTransparent
2013                     && mResizeMode == other.mResizeMode
2014                     && mMinWidth == other.mMinWidth
2015                     && mMinHeight == other.mMinHeight
2016                     && mColorBackgroundFloating == other.mColorBackgroundFloating;
2017         }
2018 
2019         /** @hide */
equals(TaskDescription td1, TaskDescription td2)2020         public static boolean equals(TaskDescription td1, TaskDescription td2) {
2021             if (td1 == null && td2 == null) {
2022                 return true;
2023             } else if (td1 != null && td2 != null) {
2024                 return td1.equals(td2);
2025             }
2026             return false;
2027         }
2028     }
2029 
2030     /**
2031      * Information you can retrieve about tasks that the user has most recently
2032      * started or visited.
2033      */
2034     public static class RecentTaskInfo extends TaskInfo implements Parcelable {
2035         /**
2036          * @hide
2037          */
2038         public static class PersistedTaskSnapshotData {
2039             /**
2040              * The bounds of the task when the last snapshot was taken, may be null if the task is
2041              * not yet attached to the hierarchy.
2042              * @see {@link android.window.TaskSnapshot#mTaskSize}.
2043              * @hide
2044              */
2045             public @Nullable Point taskSize;
2046 
2047             /**
2048              * The content insets of the task when the task snapshot was taken.
2049              * @see {@link android.window.TaskSnapshot#mContentInsets}.
2050              * @hide
2051              */
2052             public @Nullable Rect contentInsets;
2053 
2054             /**
2055              * The size of the last snapshot taken, may be null if there is no associated snapshot.
2056              * @see {@link android.window.TaskSnapshot#mSnapshot}.
2057              * @hide
2058              */
2059             public @Nullable Point bufferSize;
2060 
2061             /**
2062              * Sets the data from the other data.
2063              * @hide
2064              */
set(PersistedTaskSnapshotData other)2065             public void set(PersistedTaskSnapshotData other) {
2066                 taskSize = other.taskSize;
2067                 contentInsets = other.contentInsets;
2068                 bufferSize = other.bufferSize;
2069             }
2070 
2071             /**
2072              * Sets the data from the provided {@param snapshot}.
2073              * @hide
2074              */
set(TaskSnapshot snapshot)2075             public void set(TaskSnapshot snapshot) {
2076                 if (snapshot == null) {
2077                     taskSize = null;
2078                     contentInsets = null;
2079                     bufferSize = null;
2080                     return;
2081                 }
2082                 final HardwareBuffer buffer = snapshot.getHardwareBuffer();
2083                 taskSize = new Point(snapshot.getTaskSize());
2084                 contentInsets = new Rect(snapshot.getContentInsets());
2085                 bufferSize = buffer != null
2086                         ? new Point(buffer.getWidth(), buffer.getHeight())
2087                         : null;
2088             }
2089         }
2090 
2091         /**
2092          * If this task is currently running, this is the identifier for it.
2093          * If it is not running, this will be -1.
2094          *
2095          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, use
2096          * {@link RecentTaskInfo#taskId} to get the task id and {@link RecentTaskInfo#isRunning}
2097          * to determine if it is running.
2098          */
2099         @Deprecated
2100         public int id;
2101 
2102         /**
2103          * The true identifier of this task, valid even if it is not running.
2104          *
2105          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, use
2106          * {@link RecentTaskInfo#taskId}.
2107          */
2108         @Deprecated
2109         public int persistentId;
2110 
2111         /**
2112          * Description of the task's last state.
2113          *
2114          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, currently always null.
2115          */
2116         @Deprecated
2117         public CharSequence description;
2118 
2119         /**
2120          * Task affiliation for grouping with other tasks.
2121          *
2122          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, currently always 0.
2123          */
2124         @Deprecated
2125         public int affiliatedTaskId;
2126 
2127         /**
2128          * Information of organized child tasks.
2129          *
2130          * @hide
2131          */
2132         public ArrayList<RecentTaskInfo> childrenTaskInfos = new ArrayList<>();
2133 
2134         /**
2135          * Information about the last snapshot taken for this task.
2136          * @hide
2137          */
2138         public PersistedTaskSnapshotData lastSnapshotData = new PersistedTaskSnapshotData();
2139 
RecentTaskInfo()2140         public RecentTaskInfo() {
2141         }
2142 
RecentTaskInfo(Parcel source)2143         private RecentTaskInfo(Parcel source) {
2144             readFromParcel(source);
2145         }
2146 
2147         @Override
describeContents()2148         public int describeContents() {
2149             return 0;
2150         }
2151 
readFromParcel(Parcel source)2152         public void readFromParcel(Parcel source) {
2153             id = source.readInt();
2154             persistentId = source.readInt();
2155             childrenTaskInfos = source.readArrayList(RecentTaskInfo.class.getClassLoader(), android.app.ActivityManager.RecentTaskInfo.class);
2156             lastSnapshotData.taskSize = source.readTypedObject(Point.CREATOR);
2157             lastSnapshotData.contentInsets = source.readTypedObject(Rect.CREATOR);
2158             lastSnapshotData.bufferSize = source.readTypedObject(Point.CREATOR);
2159             super.readFromParcel(source);
2160         }
2161 
2162         @Override
writeToParcel(Parcel dest, int flags)2163         public void writeToParcel(Parcel dest, int flags) {
2164             dest.writeInt(id);
2165             dest.writeInt(persistentId);
2166             dest.writeList(childrenTaskInfos);
2167             dest.writeTypedObject(lastSnapshotData.taskSize, flags);
2168             dest.writeTypedObject(lastSnapshotData.contentInsets, flags);
2169             dest.writeTypedObject(lastSnapshotData.bufferSize, flags);
2170             super.writeToParcel(dest, flags);
2171         }
2172 
2173         public static final @android.annotation.NonNull Creator<RecentTaskInfo> CREATOR
2174                 = new Creator<RecentTaskInfo>() {
2175             public RecentTaskInfo createFromParcel(Parcel source) {
2176                 return new RecentTaskInfo(source);
2177             }
2178             public RecentTaskInfo[] newArray(int size) {
2179                 return new RecentTaskInfo[size];
2180             }
2181         };
2182 
2183         /**
2184          * @hide
2185          */
dump(PrintWriter pw, String indent)2186         public void dump(PrintWriter pw, String indent) {
2187             pw.println(); pw.print("   ");
2188             pw.print(" id="); pw.print(persistentId);
2189             pw.print(" userId="); pw.print(userId);
2190             pw.print(" hasTask="); pw.print((id != -1));
2191             pw.print(" lastActiveTime="); pw.println(lastActiveTime);
2192             pw.print("   "); pw.print(" baseIntent="); pw.println(baseIntent);
2193             if (baseActivity != null) {
2194                 pw.print("   "); pw.print(" baseActivity=");
2195                 pw.println(baseActivity.toShortString());
2196             }
2197             if (topActivity != null) {
2198                 pw.print("   "); pw.print(" topActivity="); pw.println(topActivity.toShortString());
2199             }
2200             if (origActivity != null) {
2201                 pw.print("   "); pw.print(" origActivity=");
2202                 pw.println(origActivity.toShortString());
2203             }
2204             if (realActivity != null) {
2205                 pw.print("   "); pw.print(" realActivity=");
2206                 pw.println(realActivity.toShortString());
2207             }
2208             pw.print("   ");
2209             pw.print(" isExcluded=");
2210             pw.print(((baseIntent.getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) != 0));
2211             pw.print(" activityType="); pw.print(activityTypeToString(getActivityType()));
2212             pw.print(" windowingMode="); pw.print(windowingModeToString(getWindowingMode()));
2213             pw.print(" supportsMultiWindow=");
2214             pw.println(supportsMultiWindow);
2215             if (taskDescription != null) {
2216                 pw.print("   ");
2217                 final ActivityManager.TaskDescription td = taskDescription;
2218                 pw.print(" taskDescription {");
2219                 pw.print(" colorBackground=#");
2220                 pw.print(Integer.toHexString(td.getBackgroundColor()));
2221                 pw.print(" colorPrimary=#");
2222                 pw.print(Integer.toHexString(td.getPrimaryColor()));
2223                 pw.print(" iconRes=");
2224                 pw.print(td.getIconResourcePackage() + "/" + td.getIconResource());
2225                 pw.print(" iconBitmap=");
2226                 pw.print(td.getIconFilename() != null || td.getInMemoryIcon() != null);
2227                 pw.print(" resizeMode=");
2228                 pw.print(ActivityInfo.resizeModeToString(td.getResizeMode()));
2229                 pw.print(" minWidth="); pw.print(td.getMinWidth());
2230                 pw.print(" minHeight="); pw.print(td.getMinHeight());
2231                 pw.print(" colorBackgroundFloating=#");
2232                 pw.print(Integer.toHexString(td.getBackgroundColorFloating()));
2233                 pw.println(" }");
2234             }
2235             pw.print("   ");
2236             pw.print(" lastSnapshotData {");
2237             pw.print(" taskSize=" + lastSnapshotData.taskSize);
2238             pw.print(" contentInsets=" + lastSnapshotData.contentInsets);
2239             pw.print(" bufferSize=" + lastSnapshotData.bufferSize);
2240             pw.println(" }");
2241         }
2242     }
2243 
2244     /**
2245      * Flag for use with {@link #getRecentTasks}: return all tasks, even those
2246      * that have set their
2247      * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
2248      */
2249     public static final int RECENT_WITH_EXCLUDED = 0x0001;
2250 
2251     /**
2252      * Provides a list that does not contain any
2253      * recent tasks that currently are not available to the user.
2254      */
2255     public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
2256 
2257     /**
2258      * <p></p>Return a list of the tasks that the user has recently launched, with
2259      * the most recent being first and older ones after in order.
2260      *
2261      * <p><b>Note: this method is only intended for debugging and presenting
2262      * task management user interfaces</b>.  This should never be used for
2263      * core logic in an application, such as deciding between different
2264      * behaviors based on the information found here.  Such uses are
2265      * <em>not</em> supported, and will likely break in the future.  For
2266      * example, if multiple applications can be actively running at the
2267      * same time, assumptions made about the meaning of the data here for
2268      * purposes of control flow will be incorrect.</p>
2269      *
2270      * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
2271      * no longer available to third party applications: the introduction of
2272      * document-centric recents means
2273      * it can leak personal information to the caller.  For backwards compatibility,
2274      * it will still return a small subset of its data: at least the caller's
2275      * own tasks (though see {@link #getAppTasks()} for the correct supported
2276      * way to retrieve that information), and possibly some other tasks
2277      * such as home that are known to not be sensitive.
2278      *
2279      * @param maxNum The maximum number of entries to return in the list.  The
2280      * actual number returned may be smaller, depending on how many tasks the
2281      * user has started and the maximum number the system can remember.
2282      * @param flags Information about what to return.  May be any combination
2283      * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
2284      *
2285      * @return Returns a list of RecentTaskInfo records describing each of
2286      * the recent tasks.
2287      */
2288     @Deprecated
getRecentTasks(int maxNum, int flags)2289     public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags) throws SecurityException {
2290         if (maxNum < 0) {
2291             throw new IllegalArgumentException("The requested number of tasks should be >= 0");
2292         }
2293         return ActivityTaskManager.getInstance().getRecentTasks(
2294                 maxNum, flags, mContext.getUserId());
2295     }
2296 
2297     /**
2298      * Information you can retrieve about a particular task that is currently
2299      * "running" in the system.  Note that a running task does not mean the
2300      * given task actually has a process it is actively running in; it simply
2301      * means that the user has gone to it and never closed it, but currently
2302      * the system may have killed its process and is only holding on to its
2303      * last state in order to restart it when the user returns.
2304      */
2305     public static class RunningTaskInfo extends TaskInfo implements Parcelable {
2306 
2307         /**
2308          * A unique identifier for this task.
2309          *
2310          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, use
2311          * {@link RunningTaskInfo#taskId}.
2312          */
2313         @Deprecated
2314         public int id;
2315 
2316         /**
2317          * Thumbnail representation of the task's current state.
2318          *
2319          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, currently always null.
2320          */
2321         @Deprecated
2322         public Bitmap thumbnail;
2323 
2324         /**
2325          * Description of the task's current state.
2326          *
2327          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, currently always null.
2328          */
2329         @Deprecated
2330         public CharSequence description;
2331 
2332         /**
2333          * Number of activities that are currently running (not stopped and persisted) in this task.
2334          *
2335          * @deprecated As of {@link android.os.Build.VERSION_CODES#Q}, currently always 0.
2336          */
2337         @Deprecated
2338         public int numRunning;
2339 
RunningTaskInfo()2340         public RunningTaskInfo() {
2341         }
2342 
RunningTaskInfo(Parcel source)2343         private RunningTaskInfo(Parcel source) {
2344             readFromParcel(source);
2345         }
2346 
2347         @Override
describeContents()2348         public int describeContents() {
2349             return 0;
2350         }
2351 
readFromParcel(Parcel source)2352         public void readFromParcel(Parcel source) {
2353             id = source.readInt();
2354             super.readFromParcel(source);
2355         }
2356 
2357         @Override
writeToParcel(Parcel dest, int flags)2358         public void writeToParcel(Parcel dest, int flags) {
2359             dest.writeInt(id);
2360             super.writeToParcel(dest, flags);
2361         }
2362 
2363         public static final @android.annotation.NonNull Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
2364             public RunningTaskInfo createFromParcel(Parcel source) {
2365                 return new RunningTaskInfo(source);
2366             }
2367             public RunningTaskInfo[] newArray(int size) {
2368                 return new RunningTaskInfo[size];
2369             }
2370         };
2371     }
2372 
2373     /**
2374      * Get the list of tasks associated with the calling application.
2375      *
2376      * @return The list of tasks associated with the application making this call.
2377      * @throws SecurityException
2378      */
getAppTasks()2379     public List<ActivityManager.AppTask> getAppTasks() {
2380         ArrayList<AppTask> tasks = new ArrayList<AppTask>();
2381         List<IBinder> appTasks;
2382         try {
2383             appTasks = getTaskService().getAppTasks(mContext.getOpPackageName());
2384         } catch (RemoteException e) {
2385             throw e.rethrowFromSystemServer();
2386         }
2387         int numAppTasks = appTasks.size();
2388         for (int i = 0; i < numAppTasks; i++) {
2389             tasks.add(new AppTask(IAppTask.Stub.asInterface(appTasks.get(i))));
2390         }
2391         return tasks;
2392     }
2393 
2394     /**
2395      * Return the current design dimensions for {@link AppTask} thumbnails, for use
2396      * with {@link #addAppTask}.
2397      */
getAppTaskThumbnailSize()2398     public Size getAppTaskThumbnailSize() {
2399         synchronized (this) {
2400             ensureAppTaskThumbnailSizeLocked();
2401             return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
2402         }
2403     }
2404 
ensureAppTaskThumbnailSizeLocked()2405     private void ensureAppTaskThumbnailSizeLocked() {
2406         if (mAppTaskThumbnailSize == null) {
2407             try {
2408                 mAppTaskThumbnailSize = getTaskService().getAppTaskThumbnailSize();
2409             } catch (RemoteException e) {
2410                 throw e.rethrowFromSystemServer();
2411             }
2412         }
2413     }
2414 
2415     /**
2416      * Add a new {@link AppTask} for the calling application.  This will create a new
2417      * recents entry that is added to the <b>end</b> of all existing recents.
2418      *
2419      * @param activity The activity that is adding the entry.   This is used to help determine
2420      * the context that the new recents entry will be in.
2421      * @param intent The Intent that describes the recents entry.  This is the same Intent that
2422      * you would have used to launch the activity for it.  In generally you will want to set
2423      * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
2424      * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
2425      * entry will exist without an activity, so it doesn't make sense to not retain it when
2426      * its activity disappears.  The given Intent here also must have an explicit ComponentName
2427      * set on it.
2428      * @param description Optional additional description information.
2429      * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
2430      * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
2431      * recreated in your process, probably in a way you don't like, before the recents entry
2432      * is added.
2433      *
2434      * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
2435      * most likely cause of failure is that there is no more room for more tasks for your app.
2436      */
addAppTask(@onNull Activity activity, @NonNull Intent intent, @Nullable TaskDescription description, @NonNull Bitmap thumbnail)2437     public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
2438             @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
2439         Point size;
2440         synchronized (this) {
2441             ensureAppTaskThumbnailSizeLocked();
2442             size = mAppTaskThumbnailSize;
2443         }
2444         final int tw = thumbnail.getWidth();
2445         final int th = thumbnail.getHeight();
2446         if (tw != size.x || th != size.y) {
2447             Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
2448 
2449             // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
2450             float scale;
2451             float dx = 0, dy = 0;
2452             if (tw * size.x > size.y * th) {
2453                 scale = (float) size.x / (float) th;
2454                 dx = (size.y - tw * scale) * 0.5f;
2455             } else {
2456                 scale = (float) size.y / (float) tw;
2457                 dy = (size.x - th * scale) * 0.5f;
2458             }
2459             Matrix matrix = new Matrix();
2460             matrix.setScale(scale, scale);
2461             matrix.postTranslate((int) (dx + 0.5f), 0);
2462 
2463             Canvas canvas = new Canvas(bm);
2464             canvas.drawBitmap(thumbnail, matrix, null);
2465             canvas.setBitmap(null);
2466 
2467             thumbnail = bm;
2468         }
2469         if (description == null) {
2470             description = new TaskDescription();
2471         }
2472         try {
2473             return getTaskService().addAppTask(activity.getActivityToken(),
2474                     intent, description, thumbnail);
2475         } catch (RemoteException e) {
2476             throw e.rethrowFromSystemServer();
2477         }
2478     }
2479 
2480     /**
2481      * Return a list of the tasks that are currently running, with
2482      * the most recent being first and older ones after in order.  Note that
2483      * "running" does not mean any of the task's code is currently loaded or
2484      * activity -- the task may have been frozen by the system, so that it
2485      * can be restarted in its previous state when next brought to the
2486      * foreground.
2487      *
2488      * <p><b>Note: this method is only intended for debugging and presenting
2489      * task management user interfaces</b>.  This should never be used for
2490      * core logic in an application, such as deciding between different
2491      * behaviors based on the information found here.  Such uses are
2492      * <em>not</em> supported, and will likely break in the future.  For
2493      * example, if multiple applications can be actively running at the
2494      * same time, assumptions made about the meaning of the data here for
2495      * purposes of control flow will be incorrect.</p>
2496      *
2497      * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
2498      * is no longer available to third party
2499      * applications: the introduction of document-centric recents means
2500      * it can leak person information to the caller.  For backwards compatibility,
2501      * it will still return a small subset of its data: at least the caller's
2502      * own tasks, and possibly some other tasks
2503      * such as home that are known to not be sensitive.
2504      *
2505      * @param maxNum The maximum number of entries to return in the list.  The
2506      * actual number returned may be smaller, depending on how many tasks the
2507      * user has started.
2508      *
2509      * @return Returns a list of RunningTaskInfo records describing each of
2510      * the running tasks.
2511      */
2512     @Deprecated
getRunningTasks(int maxNum)2513     public List<RunningTaskInfo> getRunningTasks(int maxNum)
2514             throws SecurityException {
2515         return ActivityTaskManager.getInstance().getTasks(maxNum);
2516     }
2517 
2518     /** @hide */
2519     @IntDef(flag = true, prefix = { "MOVE_TASK_" }, value = {
2520             MOVE_TASK_WITH_HOME,
2521             MOVE_TASK_NO_USER_ACTION,
2522     })
2523     @Retention(RetentionPolicy.SOURCE)
2524     public @interface MoveTaskFlags {}
2525 
2526     /**
2527      * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
2528      * activity along with the task, so it is positioned immediately behind
2529      * the task.
2530      */
2531     public static final int MOVE_TASK_WITH_HOME = 0x00000001;
2532 
2533     /**
2534      * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
2535      * user-instigated action, so the current activity will not receive a
2536      * hint that the user is leaving.
2537      */
2538     public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
2539 
2540     /**
2541      * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
2542      * with a null options argument.
2543      *
2544      * @param taskId The identifier of the task to be moved, as found in
2545      * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
2546      * @param flags Additional operational flags.
2547      */
2548     @RequiresPermission(android.Manifest.permission.REORDER_TASKS)
moveTaskToFront(int taskId, @MoveTaskFlags int flags)2549     public void moveTaskToFront(int taskId, @MoveTaskFlags int flags) {
2550         moveTaskToFront(taskId, flags, null);
2551     }
2552 
2553     /**
2554      * Ask that the task associated with a given task ID be moved to the
2555      * front of the stack, so it is now visible to the user.
2556      *
2557      * @param taskId The identifier of the task to be moved, as found in
2558      * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
2559      * @param flags Additional operational flags.
2560      * @param options Additional options for the operation, either null or
2561      * as per {@link Context#startActivity(Intent, android.os.Bundle)
2562      * Context.startActivity(Intent, Bundle)}.
2563      */
2564     @RequiresPermission(android.Manifest.permission.REORDER_TASKS)
moveTaskToFront(int taskId, @MoveTaskFlags int flags, Bundle options)2565     public void moveTaskToFront(int taskId, @MoveTaskFlags int flags, Bundle options) {
2566         try {
2567             ActivityThread thread = ActivityThread.currentActivityThread();
2568             IApplicationThread appThread = thread.getApplicationThread();
2569             String packageName = mContext.getOpPackageName();
2570             getTaskService().moveTaskToFront(appThread, packageName, taskId, flags, options);
2571         } catch (RemoteException e) {
2572             throw e.rethrowFromSystemServer();
2573         }
2574     }
2575 
2576     /**
2577      * Check if the context is allowed to start an activity on specified display. Some launch
2578      * restrictions may apply to secondary displays that are private, virtual, or owned by the
2579      * system, in which case an activity start may throw a {@link SecurityException}. Call this
2580      * method prior to starting an activity on a secondary display to check if the current context
2581      * has access to it.
2582      *
2583      * @see ActivityOptions#setLaunchDisplayId(int)
2584      * @see android.view.Display#FLAG_PRIVATE
2585      *
2586      * @param context Source context, from which an activity will be started.
2587      * @param displayId Target display id.
2588      * @param intent Intent used to launch an activity.
2589      * @return {@code true} if a call to start an activity on the target display is allowed for the
2590      * provided context and no {@link SecurityException} will be thrown, {@code false} otherwise.
2591      */
isActivityStartAllowedOnDisplay(@onNull Context context, int displayId, @NonNull Intent intent)2592     public boolean isActivityStartAllowedOnDisplay(@NonNull Context context, int displayId,
2593             @NonNull Intent intent) {
2594         try {
2595             return getTaskService().isActivityStartAllowedOnDisplay(displayId, intent,
2596                     intent.resolveTypeIfNeeded(context.getContentResolver()), context.getUserId());
2597         } catch (RemoteException e) {
2598             e.rethrowFromSystemServer();
2599         }
2600         return false;
2601     }
2602 
2603     /**
2604      * Information you can retrieve about a particular Service that is
2605      * currently running in the system.
2606      */
2607     public static class RunningServiceInfo implements Parcelable {
2608         /**
2609          * The service component.
2610          */
2611         public ComponentName service;
2612 
2613         /**
2614          * If non-zero, this is the process the service is running in.
2615          */
2616         public int pid;
2617 
2618         /**
2619          * The UID that owns this service.
2620          */
2621         public int uid;
2622 
2623         /**
2624          * The name of the process this service runs in.
2625          */
2626         public String process;
2627 
2628         /**
2629          * Set to true if the service has asked to run as a foreground process.
2630          */
2631         public boolean foreground;
2632 
2633         /**
2634          * The time when the service was first made active, either by someone
2635          * starting or binding to it.  This
2636          * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
2637          */
2638         public long activeSince;
2639 
2640         /**
2641          * Set to true if this service has been explicitly started.
2642          */
2643         public boolean started;
2644 
2645         /**
2646          * Number of clients connected to the service.
2647          */
2648         public int clientCount;
2649 
2650         /**
2651          * Number of times the service's process has crashed while the service
2652          * is running.
2653          */
2654         public int crashCount;
2655 
2656         /**
2657          * The time when there was last activity in the service (either
2658          * explicit requests to start it or clients binding to it).  This
2659          * is in units of {@link android.os.SystemClock#uptimeMillis()}.
2660          */
2661         public long lastActivityTime;
2662 
2663         /**
2664          * If non-zero, this service is not currently running, but scheduled to
2665          * restart at the given time.
2666          */
2667         public long restarting;
2668 
2669         /**
2670          * Bit for {@link #flags}: set if this service has been
2671          * explicitly started.
2672          */
2673         public static final int FLAG_STARTED = 1<<0;
2674 
2675         /**
2676          * Bit for {@link #flags}: set if the service has asked to
2677          * run as a foreground process.
2678          */
2679         public static final int FLAG_FOREGROUND = 1<<1;
2680 
2681         /**
2682          * Bit for {@link #flags}: set if the service is running in a
2683          * core system process.
2684          */
2685         public static final int FLAG_SYSTEM_PROCESS = 1<<2;
2686 
2687         /**
2688          * Bit for {@link #flags}: set if the service is running in a
2689          * persistent process.
2690          */
2691         public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
2692 
2693         /**
2694          * Running flags.
2695          */
2696         public int flags;
2697 
2698         /**
2699          * For special services that are bound to by system code, this is
2700          * the package that holds the binding.
2701          */
2702         public String clientPackage;
2703 
2704         /**
2705          * For special services that are bound to by system code, this is
2706          * a string resource providing a user-visible label for who the
2707          * client is.
2708          */
2709         public int clientLabel;
2710 
RunningServiceInfo()2711         public RunningServiceInfo() {
2712         }
2713 
describeContents()2714         public int describeContents() {
2715             return 0;
2716         }
2717 
writeToParcel(Parcel dest, int flags)2718         public void writeToParcel(Parcel dest, int flags) {
2719             ComponentName.writeToParcel(service, dest);
2720             dest.writeInt(pid);
2721             dest.writeInt(uid);
2722             dest.writeString(process);
2723             dest.writeInt(foreground ? 1 : 0);
2724             dest.writeLong(activeSince);
2725             dest.writeInt(started ? 1 : 0);
2726             dest.writeInt(clientCount);
2727             dest.writeInt(crashCount);
2728             dest.writeLong(lastActivityTime);
2729             dest.writeLong(restarting);
2730             dest.writeInt(this.flags);
2731             dest.writeString(clientPackage);
2732             dest.writeInt(clientLabel);
2733         }
2734 
readFromParcel(Parcel source)2735         public void readFromParcel(Parcel source) {
2736             service = ComponentName.readFromParcel(source);
2737             pid = source.readInt();
2738             uid = source.readInt();
2739             process = source.readString();
2740             foreground = source.readInt() != 0;
2741             activeSince = source.readLong();
2742             started = source.readInt() != 0;
2743             clientCount = source.readInt();
2744             crashCount = source.readInt();
2745             lastActivityTime = source.readLong();
2746             restarting = source.readLong();
2747             flags = source.readInt();
2748             clientPackage = source.readString();
2749             clientLabel = source.readInt();
2750         }
2751 
2752         public static final @android.annotation.NonNull Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
2753             public RunningServiceInfo createFromParcel(Parcel source) {
2754                 return new RunningServiceInfo(source);
2755             }
2756             public RunningServiceInfo[] newArray(int size) {
2757                 return new RunningServiceInfo[size];
2758             }
2759         };
2760 
RunningServiceInfo(Parcel source)2761         private RunningServiceInfo(Parcel source) {
2762             readFromParcel(source);
2763         }
2764     }
2765 
2766     /**
2767      * Return a list of the services that are currently running.
2768      *
2769      * <p><b>Note: this method is only intended for debugging or implementing
2770      * service management type user interfaces.</b></p>
2771      *
2772      * @deprecated As of {@link android.os.Build.VERSION_CODES#O}, this method
2773      * is no longer available to third party applications.  For backwards compatibility,
2774      * it will still return the caller's own services.
2775      *
2776      * @param maxNum The maximum number of entries to return in the list.  The
2777      * actual number returned may be smaller, depending on how many services
2778      * are running.
2779      *
2780      * @return Returns a list of RunningServiceInfo records describing each of
2781      * the running tasks.
2782      */
2783     @Deprecated
getRunningServices(int maxNum)2784     public List<RunningServiceInfo> getRunningServices(int maxNum)
2785             throws SecurityException {
2786         try {
2787             return getService()
2788                     .getServices(maxNum, 0);
2789         } catch (RemoteException e) {
2790             throw e.rethrowFromSystemServer();
2791         }
2792     }
2793 
2794     /**
2795      * Returns a PendingIntent you can start to show a control panel for the
2796      * given running service.  If the service does not have a control panel,
2797      * null is returned.
2798      */
getRunningServiceControlPanel(ComponentName service)2799     public PendingIntent getRunningServiceControlPanel(ComponentName service)
2800             throws SecurityException {
2801         try {
2802             return getService()
2803                     .getRunningServiceControlPanel(service);
2804         } catch (RemoteException e) {
2805             throw e.rethrowFromSystemServer();
2806         }
2807     }
2808 
2809     /**
2810      * Information you can retrieve about the available memory through
2811      * {@link ActivityManager#getMemoryInfo}.
2812      */
2813     public static class MemoryInfo implements Parcelable {
2814         /**
2815          * The available memory on the system.  This number should not
2816          * be considered absolute: due to the nature of the kernel, a significant
2817          * portion of this memory is actually in use and needed for the overall
2818          * system to run well.
2819          */
2820         public long availMem;
2821 
2822         /**
2823          * The total memory accessible by the kernel.  This is basically the
2824          * RAM size of the device, not including below-kernel fixed allocations
2825          * like DMA buffers, RAM for the baseband CPU, etc.
2826          */
2827         public long totalMem;
2828 
2829         /**
2830          * The threshold of {@link #availMem} at which we consider memory to be
2831          * low and start killing background services and other non-extraneous
2832          * processes.
2833          */
2834         public long threshold;
2835 
2836         /**
2837          * Set to true if the system considers itself to currently be in a low
2838          * memory situation.
2839          */
2840         public boolean lowMemory;
2841 
2842         /** @hide */
2843         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2844         public long hiddenAppThreshold;
2845         /** @hide */
2846         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2847         public long secondaryServerThreshold;
2848         /** @hide */
2849         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2850         public long visibleAppThreshold;
2851         /** @hide */
2852         @UnsupportedAppUsage
2853         public long foregroundAppThreshold;
2854 
MemoryInfo()2855         public MemoryInfo() {
2856         }
2857 
describeContents()2858         public int describeContents() {
2859             return 0;
2860         }
2861 
writeToParcel(Parcel dest, int flags)2862         public void writeToParcel(Parcel dest, int flags) {
2863             dest.writeLong(availMem);
2864             dest.writeLong(totalMem);
2865             dest.writeLong(threshold);
2866             dest.writeInt(lowMemory ? 1 : 0);
2867             dest.writeLong(hiddenAppThreshold);
2868             dest.writeLong(secondaryServerThreshold);
2869             dest.writeLong(visibleAppThreshold);
2870             dest.writeLong(foregroundAppThreshold);
2871         }
2872 
readFromParcel(Parcel source)2873         public void readFromParcel(Parcel source) {
2874             availMem = source.readLong();
2875             totalMem = source.readLong();
2876             threshold = source.readLong();
2877             lowMemory = source.readInt() != 0;
2878             hiddenAppThreshold = source.readLong();
2879             secondaryServerThreshold = source.readLong();
2880             visibleAppThreshold = source.readLong();
2881             foregroundAppThreshold = source.readLong();
2882         }
2883 
2884         public static final @android.annotation.NonNull Creator<MemoryInfo> CREATOR
2885                 = new Creator<MemoryInfo>() {
2886             public MemoryInfo createFromParcel(Parcel source) {
2887                 return new MemoryInfo(source);
2888             }
2889             public MemoryInfo[] newArray(int size) {
2890                 return new MemoryInfo[size];
2891             }
2892         };
2893 
MemoryInfo(Parcel source)2894         private MemoryInfo(Parcel source) {
2895             readFromParcel(source);
2896         }
2897     }
2898 
2899     /**
2900      * Return general information about the memory state of the system.  This
2901      * can be used to help decide how to manage your own memory, though note
2902      * that polling is not recommended and
2903      * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2904      * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
2905      * Also see {@link #getMyMemoryState} for how to retrieve the current trim
2906      * level of your process as needed, which gives a better hint for how to
2907      * manage its memory.
2908      */
getMemoryInfo(MemoryInfo outInfo)2909     public void getMemoryInfo(MemoryInfo outInfo) {
2910         try {
2911             getService().getMemoryInfo(outInfo);
2912         } catch (RemoteException e) {
2913             throw e.rethrowFromSystemServer();
2914         }
2915     }
2916 
2917     /**
2918      * @hide
2919      */
2920     @RequiresPermission(anyOf={Manifest.permission.CLEAR_APP_USER_DATA,
2921             Manifest.permission.ACCESS_INSTANT_APPS})
2922     @UnsupportedAppUsage
clearApplicationUserData(String packageName, IPackageDataObserver observer)2923     public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
2924         try {
2925             return getService().clearApplicationUserData(packageName, false,
2926                     observer, mContext.getUserId());
2927         } catch (RemoteException e) {
2928             throw e.rethrowFromSystemServer();
2929         }
2930     }
2931 
2932     /**
2933      * Permits an application to erase its own data from disk.  This is equivalent to
2934      * the user choosing to clear the app's data from within the device settings UI.  It
2935      * erases all dynamic data associated with the app -- its private data and data in its
2936      * private area on external storage -- but does not remove the installed application
2937      * itself, nor any OBB files. It also revokes all runtime permissions that the app has acquired,
2938      * clears all notifications and removes all Uri grants related to this application.
2939      *
2940      * @return {@code true} if the application successfully requested that the application's
2941      *     data be erased; {@code false} otherwise.
2942      */
clearApplicationUserData()2943     public boolean clearApplicationUserData() {
2944         return clearApplicationUserData(mContext.getPackageName(), null);
2945     }
2946 
2947     /**
2948      * Permits an application to get the persistent URI permissions granted to another.
2949      *
2950      * <p>Typically called by Settings or DocumentsUI, requires
2951      * {@code GET_APP_GRANTED_URI_PERMISSIONS}.
2952      *
2953      * @param packageName application to look for the granted permissions, or {@code null} to get
2954      * granted permissions for all applications
2955      * @return list of granted URI permissions
2956      *
2957      * @hide
2958      * @deprecated use {@link UriGrantsManager#getGrantedUriPermissions(String)} instead.
2959      */
2960     @Deprecated
getGrantedUriPermissions( @ullable String packageName)2961     public ParceledListSlice<GrantedUriPermission> getGrantedUriPermissions(
2962             @Nullable String packageName) {
2963         return ((UriGrantsManager) mContext.getSystemService(Context.URI_GRANTS_SERVICE))
2964                 .getGrantedUriPermissions(packageName);
2965     }
2966 
2967     /**
2968      * Permits an application to clear the persistent URI permissions granted to another.
2969      *
2970      * <p>Typically called by Settings, requires {@code CLEAR_APP_GRANTED_URI_PERMISSIONS}.
2971      *
2972      * @param packageName application to clear its granted permissions
2973      *
2974      * @hide
2975      * @deprecated use {@link UriGrantsManager#clearGrantedUriPermissions(String)} instead.
2976      */
2977     @Deprecated
clearGrantedUriPermissions(String packageName)2978     public void clearGrantedUriPermissions(String packageName) {
2979         ((UriGrantsManager) mContext.getSystemService(Context.URI_GRANTS_SERVICE))
2980                 .clearGrantedUriPermissions(packageName);
2981     }
2982 
2983     /**
2984      * Information you can retrieve about any processes that are in an error condition.
2985      */
2986     public static class ProcessErrorStateInfo implements Parcelable {
2987         /**
2988          * Condition codes
2989          */
2990         public static final int NO_ERROR = 0;
2991         public static final int CRASHED = 1;
2992         public static final int NOT_RESPONDING = 2;
2993 
2994         /**
2995          * The condition that the process is in.
2996          */
2997         public int condition;
2998 
2999         /**
3000          * The process name in which the crash or error occurred.
3001          */
3002         public String processName;
3003 
3004         /**
3005          * The pid of this process; 0 if none
3006          */
3007         public int pid;
3008 
3009         /**
3010          * The kernel user-ID that has been assigned to this process;
3011          * currently this is not a unique ID (multiple applications can have
3012          * the same uid).
3013          */
3014         public int uid;
3015 
3016         /**
3017          * The activity name associated with the error, if known.  May be null.
3018          */
3019         public String tag;
3020 
3021         /**
3022          * A short message describing the error condition.
3023          */
3024         public String shortMsg;
3025 
3026         /**
3027          * A long message describing the error condition.
3028          */
3029         public String longMsg;
3030 
3031         /**
3032          * The stack trace where the error originated.  May be null.
3033          */
3034         public String stackTrace;
3035 
3036         /**
3037          * to be deprecated: This value will always be null.
3038          */
3039         public byte[] crashData = null;
3040 
ProcessErrorStateInfo()3041         public ProcessErrorStateInfo() {
3042         }
3043 
3044         @Override
describeContents()3045         public int describeContents() {
3046             return 0;
3047         }
3048 
3049         @Override
writeToParcel(Parcel dest, int flags)3050         public void writeToParcel(Parcel dest, int flags) {
3051             dest.writeInt(condition);
3052             dest.writeString(processName);
3053             dest.writeInt(pid);
3054             dest.writeInt(uid);
3055             dest.writeString(tag);
3056             dest.writeString(shortMsg);
3057             dest.writeString(longMsg);
3058             dest.writeString(stackTrace);
3059         }
3060 
readFromParcel(Parcel source)3061         public void readFromParcel(Parcel source) {
3062             condition = source.readInt();
3063             processName = source.readString();
3064             pid = source.readInt();
3065             uid = source.readInt();
3066             tag = source.readString();
3067             shortMsg = source.readString();
3068             longMsg = source.readString();
3069             stackTrace = source.readString();
3070         }
3071 
3072         public static final @android.annotation.NonNull Creator<ProcessErrorStateInfo> CREATOR =
3073                 new Creator<ProcessErrorStateInfo>() {
3074             public ProcessErrorStateInfo createFromParcel(Parcel source) {
3075                 return new ProcessErrorStateInfo(source);
3076             }
3077             public ProcessErrorStateInfo[] newArray(int size) {
3078                 return new ProcessErrorStateInfo[size];
3079             }
3080         };
3081 
ProcessErrorStateInfo(Parcel source)3082         private ProcessErrorStateInfo(Parcel source) {
3083             readFromParcel(source);
3084         }
3085     }
3086 
3087     /**
3088      * Returns a list of any processes that are currently in an error condition.  The result
3089      * will be null if all processes are running properly at this time.
3090      *
3091      * <p>As of {@link android.os.Build.VERSION_CODES#TIRAMISU Android TIRAMISU}, for regular apps
3092      * this method will only return {@link ProcessErrorStateInfo} records for the processes running
3093      * as the caller's uid, unless the caller has the permission
3094      * {@link android.Manifest.permission#DUMP}.
3095      * </p>
3096      *
3097      * @return Returns a list of {@link ProcessErrorStateInfo} records, or null if there are no
3098      * current error conditions (it will not return an empty list).  This list ordering is not
3099      * specified.
3100      */
getProcessesInErrorState()3101     public List<ProcessErrorStateInfo> getProcessesInErrorState() {
3102         try {
3103             return getService().getProcessesInErrorState();
3104         } catch (RemoteException e) {
3105             throw e.rethrowFromSystemServer();
3106         }
3107     }
3108 
3109     /**
3110      * Information you can retrieve about a running process.
3111      */
3112     public static class RunningAppProcessInfo implements Parcelable {
3113         /**
3114          * The name of the process that this object is associated with
3115          */
3116         public String processName;
3117 
3118         /**
3119          * The pid of this process; 0 if none
3120          */
3121         public int pid;
3122 
3123         /**
3124          * The user id of this process.
3125          */
3126         public int uid;
3127 
3128         /**
3129          * All packages that have been loaded into the process.
3130          */
3131         public String pkgList[];
3132 
3133         /**
3134          * Constant for {@link #flags}: this is an app that is unable to
3135          * correctly save its state when going to the background,
3136          * so it can not be killed while in the background.
3137          * @hide
3138          */
3139         public static final int FLAG_CANT_SAVE_STATE = 1<<0;
3140 
3141         /**
3142          * Constant for {@link #flags}: this process is associated with a
3143          * persistent system app.
3144          * @hide
3145          */
3146         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3147         public static final int FLAG_PERSISTENT = 1<<1;
3148 
3149         /**
3150          * Constant for {@link #flags}: this process is associated with a
3151          * persistent system app.
3152          * @hide
3153          */
3154         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3155         public static final int FLAG_HAS_ACTIVITIES = 1<<2;
3156 
3157         /**
3158          * Flags of information.  May be any of
3159          * {@link #FLAG_CANT_SAVE_STATE}.
3160          * @hide
3161          */
3162         @UnsupportedAppUsage
3163         public int flags;
3164 
3165         /**
3166          * Last memory trim level reported to the process: corresponds to
3167          * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
3168          * ComponentCallbacks2.onTrimMemory(int)}.
3169          */
3170         public int lastTrimLevel;
3171 
3172         /** @hide */
3173         @IntDef(prefix = { "IMPORTANCE_" }, value = {
3174                 IMPORTANCE_FOREGROUND,
3175                 IMPORTANCE_FOREGROUND_SERVICE,
3176                 IMPORTANCE_TOP_SLEEPING,
3177                 IMPORTANCE_VISIBLE,
3178                 IMPORTANCE_PERCEPTIBLE,
3179                 IMPORTANCE_CANT_SAVE_STATE,
3180                 IMPORTANCE_SERVICE,
3181                 IMPORTANCE_CACHED,
3182                 IMPORTANCE_GONE,
3183         })
3184         @Retention(RetentionPolicy.SOURCE)
3185         public @interface Importance {}
3186 
3187         /**
3188          * Constant for {@link #importance}: This process is running the
3189          * foreground UI; that is, it is the thing currently at the top of the screen
3190          * that the user is interacting with.
3191          */
3192         public static final int IMPORTANCE_FOREGROUND = 100;
3193 
3194         /**
3195          * Constant for {@link #importance}: This process is running a foreground
3196          * service, for example to perform music playback even while the user is
3197          * not immediately in the app.  This generally indicates that the process
3198          * is doing something the user actively cares about.
3199          */
3200         public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
3201 
3202         /**
3203          * @deprecated Pre-{@link android.os.Build.VERSION_CODES#P} version of
3204          * {@link #IMPORTANCE_TOP_SLEEPING}.  As of Android
3205          * {@link android.os.Build.VERSION_CODES#P}, this is considered much less
3206          * important since we want to reduce what apps can do when the screen is off.
3207          */
3208         @Deprecated
3209         public static final int IMPORTANCE_TOP_SLEEPING_PRE_28 = 150;
3210 
3211         /**
3212          * Constant for {@link #importance}: This process is running something
3213          * that is actively visible to the user, though not in the immediate
3214          * foreground.  This may be running a window that is behind the current
3215          * foreground (so paused and with its state saved, not interacting with
3216          * the user, but visible to them to some degree); it may also be running
3217          * other services under the system's control that it inconsiders important.
3218          */
3219         public static final int IMPORTANCE_VISIBLE = 200;
3220 
3221         /**
3222          * Constant for {@link #importance}: {@link #IMPORTANCE_PERCEPTIBLE} had this wrong value
3223          * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
3224          * the value of {@link #IMPORTANCE_PERCEPTIBLE} has been fixed.
3225          *
3226          * <p>The system will return this value instead of {@link #IMPORTANCE_PERCEPTIBLE}
3227          * on Android versions below {@link Build.VERSION_CODES#O}.
3228          *
3229          * <p>On Android version {@link Build.VERSION_CODES#O} and later, this value will still be
3230          * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
3231          * For apps targeting version {@link Build.VERSION_CODES#O} and later,
3232          * the correct value {@link #IMPORTANCE_PERCEPTIBLE} will be returned.
3233          */
3234         public static final int IMPORTANCE_PERCEPTIBLE_PRE_26 = 130;
3235 
3236         /**
3237          * Constant for {@link #importance}: This process is not something the user
3238          * is directly aware of, but is otherwise perceptible to them to some degree.
3239          */
3240         public static final int IMPORTANCE_PERCEPTIBLE = 230;
3241 
3242         /**
3243          * Constant for {@link #importance}: {@link #IMPORTANCE_CANT_SAVE_STATE} had
3244          * this wrong value
3245          * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
3246          * the value of {@link #IMPORTANCE_CANT_SAVE_STATE} has been fixed.
3247          *
3248          * <p>The system will return this value instead of {@link #IMPORTANCE_CANT_SAVE_STATE}
3249          * on Android versions below {@link Build.VERSION_CODES#O}.
3250          *
3251          * <p>On Android version {@link Build.VERSION_CODES#O} after, this value will still be
3252          * returned for apps with the target API level below {@link Build.VERSION_CODES#O}.
3253          * For apps targeting version {@link Build.VERSION_CODES#O} and later,
3254          * the correct value {@link #IMPORTANCE_CANT_SAVE_STATE} will be returned.
3255          *
3256          * @hide
3257          */
3258         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3259         @TestApi
3260         public static final int IMPORTANCE_CANT_SAVE_STATE_PRE_26 = 170;
3261 
3262         /**
3263          * Constant for {@link #importance}: This process contains services
3264          * that should remain running.  These are background services apps have
3265          * started, not something the user is aware of, so they may be killed by
3266          * the system relatively freely (though it is generally desired that they
3267          * stay running as long as they want to).
3268          */
3269         public static final int IMPORTANCE_SERVICE = 300;
3270 
3271         /**
3272          * Constant for {@link #importance}: This process is running the foreground
3273          * UI, but the device is asleep so it is not visible to the user.  Though the
3274          * system will try hard to keep its process from being killed, in all other
3275          * ways we consider it a kind of cached process, with the limitations that go
3276          * along with that state: network access, running background services, etc.
3277          */
3278         public static final int IMPORTANCE_TOP_SLEEPING = 325;
3279 
3280         /**
3281          * Constant for {@link #importance}: This process is running an
3282          * application that can not save its state, and thus can't be killed
3283          * while in the background.  This will be used with apps that have
3284          * {@link android.R.attr#cantSaveState} set on their application tag.
3285          */
3286         public static final int IMPORTANCE_CANT_SAVE_STATE = 350;
3287 
3288         /**
3289          * Constant for {@link #importance}: This process process contains
3290          * cached code that is expendable, not actively running any app components
3291          * we care about.
3292          */
3293         public static final int IMPORTANCE_CACHED = 400;
3294 
3295         /**
3296          * @deprecated Renamed to {@link #IMPORTANCE_CACHED}.
3297          */
3298         public static final int IMPORTANCE_BACKGROUND = IMPORTANCE_CACHED;
3299 
3300         /**
3301          * Constant for {@link #importance}: This process is empty of any
3302          * actively running code.
3303          * @deprecated This value is no longer reported, use {@link #IMPORTANCE_CACHED} instead.
3304          */
3305         @Deprecated
3306         public static final int IMPORTANCE_EMPTY = 500;
3307 
3308         /**
3309          * Constant for {@link #importance}: This process does not exist.
3310          */
3311         public static final int IMPORTANCE_GONE = 1000;
3312 
3313         /**
3314          * Convert a proc state to the correspondent IMPORTANCE_* constant.  If the return value
3315          * will be passed to a client, use {@link #procStateToImportanceForClient}.
3316          * @hide
3317          */
3318         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
procStateToImportance(int procState)3319         public static @Importance int procStateToImportance(int procState) {
3320             if (procState == PROCESS_STATE_NONEXISTENT) {
3321                 return IMPORTANCE_GONE;
3322             } else if (procState >= PROCESS_STATE_HOME) {
3323                 return IMPORTANCE_CACHED;
3324             } else if (procState == PROCESS_STATE_HEAVY_WEIGHT) {
3325                 return IMPORTANCE_CANT_SAVE_STATE;
3326             } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
3327                 return IMPORTANCE_TOP_SLEEPING;
3328             } else if (procState >= PROCESS_STATE_SERVICE) {
3329                 return IMPORTANCE_SERVICE;
3330             } else if (procState >= PROCESS_STATE_TRANSIENT_BACKGROUND) {
3331                 return IMPORTANCE_PERCEPTIBLE;
3332             } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
3333                 return IMPORTANCE_VISIBLE;
3334             } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
3335                 return IMPORTANCE_FOREGROUND_SERVICE;
3336             } else {
3337                 return IMPORTANCE_FOREGROUND;
3338             }
3339         }
3340 
3341         /**
3342          * Convert a proc state to the correspondent IMPORTANCE_* constant for a client represented
3343          * by a given {@link Context}, with converting {@link #IMPORTANCE_PERCEPTIBLE}
3344          * and {@link #IMPORTANCE_CANT_SAVE_STATE} to the corresponding "wrong" value if the
3345          * client's target SDK < {@link VERSION_CODES#O}.
3346          * @hide
3347          */
procStateToImportanceForClient(int procState, Context clientContext)3348         public static @Importance int procStateToImportanceForClient(int procState,
3349                 Context clientContext) {
3350             return procStateToImportanceForTargetSdk(procState,
3351                     clientContext.getApplicationInfo().targetSdkVersion);
3352         }
3353 
3354         /**
3355          * See {@link #procStateToImportanceForClient}.
3356          * @hide
3357          */
procStateToImportanceForTargetSdk(int procState, int targetSdkVersion)3358         public static @Importance int procStateToImportanceForTargetSdk(int procState,
3359                 int targetSdkVersion) {
3360             final int importance = procStateToImportance(procState);
3361 
3362             // For pre O apps, convert to the old, wrong values.
3363             if (targetSdkVersion < VERSION_CODES.O) {
3364                 switch (importance) {
3365                     case IMPORTANCE_PERCEPTIBLE:
3366                         return IMPORTANCE_PERCEPTIBLE_PRE_26;
3367                     case IMPORTANCE_TOP_SLEEPING:
3368                         return IMPORTANCE_TOP_SLEEPING_PRE_28;
3369                     case IMPORTANCE_CANT_SAVE_STATE:
3370                         return IMPORTANCE_CANT_SAVE_STATE_PRE_26;
3371                 }
3372             }
3373             return importance;
3374         }
3375 
3376         /** @hide */
importanceToProcState(@mportance int importance)3377         public static int importanceToProcState(@Importance int importance) {
3378             if (importance == IMPORTANCE_GONE) {
3379                 return PROCESS_STATE_NONEXISTENT;
3380             } else if (importance >= IMPORTANCE_CACHED) {
3381                 return PROCESS_STATE_HOME;
3382             } else if (importance >= IMPORTANCE_CANT_SAVE_STATE) {
3383                 return PROCESS_STATE_HEAVY_WEIGHT;
3384             } else if (importance >= IMPORTANCE_TOP_SLEEPING) {
3385                 return PROCESS_STATE_TOP_SLEEPING;
3386             } else if (importance >= IMPORTANCE_SERVICE) {
3387                 return PROCESS_STATE_SERVICE;
3388             } else if (importance >= IMPORTANCE_PERCEPTIBLE) {
3389                 return PROCESS_STATE_TRANSIENT_BACKGROUND;
3390             } else if (importance >= IMPORTANCE_VISIBLE) {
3391                 return PROCESS_STATE_IMPORTANT_FOREGROUND;
3392             } else if (importance >= IMPORTANCE_TOP_SLEEPING_PRE_28) {
3393                 return PROCESS_STATE_IMPORTANT_FOREGROUND;
3394             } else if (importance >= IMPORTANCE_FOREGROUND_SERVICE) {
3395                 return PROCESS_STATE_FOREGROUND_SERVICE;
3396                 // TODO: Asymmetrical mapping for LOCATION service type. Ok?
3397             } else {
3398                 return PROCESS_STATE_TOP;
3399             }
3400         }
3401 
3402         /**
3403          * The relative importance level that the system places on this process.
3404          * These constants are numbered so that "more important" values are
3405          * always smaller than "less important" values.
3406          */
3407         public @Importance int importance;
3408 
3409         /**
3410          * An additional ordering within a particular {@link #importance}
3411          * category, providing finer-grained information about the relative
3412          * utility of processes within a category.  This number means nothing
3413          * except that a smaller values are more recently used (and thus
3414          * more important).  Currently an LRU value is only maintained for
3415          * the {@link #IMPORTANCE_CACHED} category, though others may
3416          * be maintained in the future.
3417          */
3418         public int lru;
3419 
3420         /**
3421          * Constant for {@link #importanceReasonCode}: nothing special has
3422          * been specified for the reason for this level.
3423          */
3424         public static final int REASON_UNKNOWN = 0;
3425 
3426         /**
3427          * Constant for {@link #importanceReasonCode}: one of the application's
3428          * content providers is being used by another process.  The pid of
3429          * the client process is in {@link #importanceReasonPid} and the
3430          * target provider in this process is in
3431          * {@link #importanceReasonComponent}.
3432          */
3433         public static final int REASON_PROVIDER_IN_USE = 1;
3434 
3435         /**
3436          * Constant for {@link #importanceReasonCode}: one of the application's
3437          * content providers is being used by another process.  The pid of
3438          * the client process is in {@link #importanceReasonPid} and the
3439          * target provider in this process is in
3440          * {@link #importanceReasonComponent}.
3441          */
3442         public static final int REASON_SERVICE_IN_USE = 2;
3443 
3444         /**
3445          * The reason for {@link #importance}, if any.
3446          */
3447         public int importanceReasonCode;
3448 
3449         /**
3450          * For the specified values of {@link #importanceReasonCode}, this
3451          * is the process ID of the other process that is a client of this
3452          * process.  This will be 0 if no other process is using this one.
3453          */
3454         public int importanceReasonPid;
3455 
3456         /**
3457          * For the specified values of {@link #importanceReasonCode}, this
3458          * is the name of the component that is being used in this process.
3459          */
3460         public ComponentName importanceReasonComponent;
3461 
3462         /**
3463          * When {@link #importanceReasonPid} is non-0, this is the importance
3464          * of the other pid. @hide
3465          */
3466         public int importanceReasonImportance;
3467 
3468         /**
3469          * Current process state, as per PROCESS_STATE_* constants.
3470          * @hide
3471          */
3472         @UnsupportedAppUsage
3473         public int processState;
3474 
3475         /**
3476          * Whether the app is focused in multi-window environment.
3477          * @hide
3478          */
3479         public boolean isFocused;
3480 
3481         /**
3482          * Copy of {@link com.android.server.am.ProcessRecord#lastActivityTime} of the process.
3483          * @hide
3484          */
3485         public long lastActivityTime;
3486 
RunningAppProcessInfo()3487         public RunningAppProcessInfo() {
3488             importance = IMPORTANCE_FOREGROUND;
3489             importanceReasonCode = REASON_UNKNOWN;
3490             processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
3491             isFocused = false;
3492             lastActivityTime = 0;
3493         }
3494 
RunningAppProcessInfo(String pProcessName, int pPid, String pArr[])3495         public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
3496             processName = pProcessName;
3497             pid = pPid;
3498             pkgList = pArr;
3499             isFocused = false;
3500             lastActivityTime = 0;
3501         }
3502 
describeContents()3503         public int describeContents() {
3504             return 0;
3505         }
3506 
writeToParcel(Parcel dest, int flags)3507         public void writeToParcel(Parcel dest, int flags) {
3508             dest.writeString(processName);
3509             dest.writeInt(pid);
3510             dest.writeInt(uid);
3511             dest.writeStringArray(pkgList);
3512             dest.writeInt(this.flags);
3513             dest.writeInt(lastTrimLevel);
3514             dest.writeInt(importance);
3515             dest.writeInt(lru);
3516             dest.writeInt(importanceReasonCode);
3517             dest.writeInt(importanceReasonPid);
3518             ComponentName.writeToParcel(importanceReasonComponent, dest);
3519             dest.writeInt(importanceReasonImportance);
3520             dest.writeInt(processState);
3521             dest.writeInt(isFocused ? 1 : 0);
3522             dest.writeLong(lastActivityTime);
3523         }
3524 
readFromParcel(Parcel source)3525         public void readFromParcel(Parcel source) {
3526             processName = source.readString();
3527             pid = source.readInt();
3528             uid = source.readInt();
3529             pkgList = source.readStringArray();
3530             flags = source.readInt();
3531             lastTrimLevel = source.readInt();
3532             importance = source.readInt();
3533             lru = source.readInt();
3534             importanceReasonCode = source.readInt();
3535             importanceReasonPid = source.readInt();
3536             importanceReasonComponent = ComponentName.readFromParcel(source);
3537             importanceReasonImportance = source.readInt();
3538             processState = source.readInt();
3539             isFocused = source.readInt() != 0;
3540             lastActivityTime = source.readLong();
3541         }
3542 
3543         public static final @android.annotation.NonNull Creator<RunningAppProcessInfo> CREATOR =
3544             new Creator<RunningAppProcessInfo>() {
3545             public RunningAppProcessInfo createFromParcel(Parcel source) {
3546                 return new RunningAppProcessInfo(source);
3547             }
3548             public RunningAppProcessInfo[] newArray(int size) {
3549                 return new RunningAppProcessInfo[size];
3550             }
3551         };
3552 
RunningAppProcessInfo(Parcel source)3553         private RunningAppProcessInfo(Parcel source) {
3554             readFromParcel(source);
3555         }
3556     }
3557 
3558     /**
3559      * Returns a list of application processes installed on external media
3560      * that are running on the device.
3561      *
3562      * <p><b>Note: this method is only intended for debugging or building
3563      * a user-facing process management UI.</b></p>
3564      *
3565      * @return Returns a list of ApplicationInfo records, or null if none
3566      * This list ordering is not specified.
3567      * @hide
3568      */
getRunningExternalApplications()3569     public List<ApplicationInfo> getRunningExternalApplications() {
3570         try {
3571             return getService().getRunningExternalApplications();
3572         } catch (RemoteException e) {
3573             throw e.rethrowFromSystemServer();
3574         }
3575     }
3576 
3577     /**
3578      * Query whether the user has enabled background restrictions for this app.
3579      *
3580      * <p> The user may chose to do this, if they see that an app is consuming an unreasonable
3581      * amount of battery while in the background. </p>
3582      *
3583      * <p> If true, any work that the app tries to do will be aggressively restricted while it is in
3584      * the background. At a minimum, jobs and alarms will not execute and foreground services
3585      * cannot be started unless an app activity is in the foreground. </p>
3586      *
3587      * <p><b> Note that these restrictions stay in effect even when the device is charging.</b></p>
3588      *
3589      * @return true if user has enforced background restrictions for this app, false otherwise.
3590      */
isBackgroundRestricted()3591     public boolean isBackgroundRestricted() {
3592         try {
3593             return getService().isBackgroundRestricted(mContext.getOpPackageName());
3594         } catch (RemoteException e) {
3595             throw e.rethrowFromSystemServer();
3596         }
3597     }
3598 
3599     /**
3600      * Sets the memory trim mode for a process and schedules a memory trim operation.
3601      *
3602      * <p><b>Note: this method is only intended for testing framework.</b></p>
3603      *
3604      * @return Returns true if successful.
3605      * @hide
3606      */
setProcessMemoryTrimLevel(String process, int userId, int level)3607     public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
3608         try {
3609             return getService().setProcessMemoryTrimLevel(process, userId,
3610                     level);
3611         } catch (RemoteException e) {
3612             throw e.rethrowFromSystemServer();
3613         }
3614     }
3615 
3616     /**
3617      * Returns a list of application processes that are running on the device.
3618      *
3619      * <p><b>Note: this method is only intended for debugging or building
3620      * a user-facing process management UI.</b></p>
3621      *
3622      * @return Returns a list of RunningAppProcessInfo records, or null if there are no
3623      * running processes (it will not return an empty list).  This list ordering is not
3624      * specified.
3625      */
getRunningAppProcesses()3626     public List<RunningAppProcessInfo> getRunningAppProcesses() {
3627         try {
3628             return getService().getRunningAppProcesses();
3629         } catch (RemoteException e) {
3630             throw e.rethrowFromSystemServer();
3631         }
3632     }
3633 
3634     /**
3635      * Return a list of {@link ApplicationExitInfo} records containing the reasons for the most
3636      * recent app deaths.
3637      *
3638      * <p class="note"> Note: System stores this historical information in a ring buffer and only
3639      * the most recent records will be returned. </p>
3640      *
3641      * <p class="note"> Note: In the case that this application was bound to an external service
3642      * with flag {@link android.content.Context#BIND_EXTERNAL_SERVICE}, the process of that external
3643      * service will be included in this package's exit info. </p>
3644      *
3645      * @param packageName Optional, a null value means match all packages belonging to the
3646      *                    caller's UID. If this package belongs to another UID, you must hold
3647      *                    {@link android.Manifest.permission#DUMP} in order to retrieve it.
3648      * @param pid         A process ID that used to belong to this package but died later; a value
3649      *                    of 0 means to ignore this parameter and return all matching records.
3650      * @param maxNum      The maximum number of results to be returned; a value of 0
3651      *                    means to ignore this parameter and return all matching records
3652      *
3653      * @return a list of {@link ApplicationExitInfo} records matching the criteria, sorted in
3654      *         the order from most recent to least recent.
3655      */
3656     @NonNull
getHistoricalProcessExitReasons(@ullable String packageName, @IntRange(from = 0) int pid, @IntRange(from = 0) int maxNum)3657     public List<ApplicationExitInfo> getHistoricalProcessExitReasons(@Nullable String packageName,
3658             @IntRange(from = 0) int pid, @IntRange(from = 0) int maxNum) {
3659         try {
3660             ParceledListSlice<ApplicationExitInfo> r = getService().getHistoricalProcessExitReasons(
3661                     packageName, pid, maxNum, mContext.getUserId());
3662             return r == null ? Collections.emptyList() : r.getList();
3663         } catch (RemoteException e) {
3664             throw e.rethrowFromSystemServer();
3665         }
3666     }
3667 
3668     /**
3669      * Set custom state data for this process. It will be included in the record of
3670      * {@link ApplicationExitInfo} on the death of the current calling process; the new process
3671      * of the app can retrieve this state data by calling
3672      * {@link android.app.ApplicationExitInfo#getProcessStateSummary()
3673      * ApplicationExitInfo.getProcessStateSummary()} on the record returned by
3674      * {@link #getHistoricalProcessExitReasons}.
3675      *
3676      * <p> This would be useful for the calling app to save its stateful data: if it's
3677      * killed later for any reason, the new process of the app can know what the
3678      * previous process of the app was doing. For instance, you could use this to encode
3679      * the current level in a game, or a set of features/experiments that were enabled. Later you
3680      * could analyze under what circumstances the app tends to crash or use too much memory.
3681      * However, it's not suggested to rely on this to restore the applications previous UI state
3682      * or so, it's only meant for analyzing application healthy status.</p>
3683      *
3684      * <p> System might decide to throttle the calls to this API; so call this API in a reasonable
3685      * manner, excessive calls to this API could result a {@link java.lang.RuntimeException}.
3686      * </p>
3687      *
3688      * @param state The state data. To be advised, <b>DO NOT</b> include sensitive information/data
3689      * (PII, SPII, or other sensitive user data) here. Maximum length is 128 bytes.
3690      */
setProcessStateSummary(@ullable byte[] state)3691     public void setProcessStateSummary(@Nullable byte[] state) {
3692         try {
3693             getService().setProcessStateSummary(state);
3694         } catch (RemoteException e) {
3695             throw e.rethrowFromSystemServer();
3696         }
3697     }
3698 
3699     /**
3700      * @return Whether or not the low memory kill will be reported in
3701      * {@link #getHistoricalProcessExitReasons}.
3702      *
3703      * @see ApplicationExitInfo#REASON_LOW_MEMORY
3704      */
isLowMemoryKillReportSupported()3705     public static boolean isLowMemoryKillReportSupported() {
3706         return SystemProperties.getBoolean("persist.sys.lmk.reportkills", false);
3707     }
3708 
3709     /**
3710      * Returns the process state of this uid.
3711      *
3712      * If the caller does not hold {@link Manifest.permission#INTERACT_ACROSS_USERS_FULL}
3713      * permission, they can only query process state of UIDs running in the same user as the caller.
3714      *
3715      * @hide
3716      */
3717     @TestApi
3718     @RequiresPermission(allOf = {
3719             Manifest.permission.PACKAGE_USAGE_STATS,
3720             Manifest.permission.INTERACT_ACROSS_USERS_FULL
3721     }, conditional = true)
getUidProcessState(int uid)3722     public int getUidProcessState(int uid) {
3723         try {
3724             return getService().getUidProcessState(uid, mContext.getOpPackageName());
3725         } catch (RemoteException e) {
3726             throw e.rethrowFromSystemServer();
3727         }
3728     }
3729 
3730     /**
3731      * Returns the process capability of this uid.
3732      *
3733      * If the caller does not hold {@link Manifest.permission#INTERACT_ACROSS_USERS_FULL}
3734      * permission, they can only query process capabilities of UIDs running in the same user
3735      * as the caller.
3736      *
3737      * @hide
3738      */
3739     @TestApi
3740     @RequiresPermission(allOf = {
3741             Manifest.permission.PACKAGE_USAGE_STATS,
3742             Manifest.permission.INTERACT_ACROSS_USERS_FULL
3743     }, conditional = true)
getUidProcessCapabilities(int uid)3744     public @ProcessCapability int getUidProcessCapabilities(int uid) {
3745         try {
3746             return getService().getUidProcessCapabilities(uid, mContext.getOpPackageName());
3747         } catch (RemoteException e) {
3748             throw e.rethrowFromSystemServer();
3749         }
3750     }
3751 
3752     /**
3753      * Return the importance of a given package name, based on the processes that are
3754      * currently running.  The return value is one of the importance constants defined
3755      * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3756      * processes that this package has code running inside of.  If there are no processes
3757      * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3758      * @hide
3759      */
3760     @SystemApi
3761     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
getPackageImportance(String packageName)3762     public @RunningAppProcessInfo.Importance int getPackageImportance(String packageName) {
3763         try {
3764             int procState = getService().getPackageProcessState(packageName,
3765                     mContext.getOpPackageName());
3766             return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3767         } catch (RemoteException e) {
3768             throw e.rethrowFromSystemServer();
3769         }
3770     }
3771 
3772     /**
3773      * Return the importance of a given uid, based on the processes that are
3774      * currently running.  The return value is one of the importance constants defined
3775      * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3776      * processes that this uid has running.  If there are no processes
3777      * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3778      * @hide
3779      */
3780     @SystemApi
3781     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
getUidImportance(int uid)3782     public @RunningAppProcessInfo.Importance int getUidImportance(int uid) {
3783         try {
3784             int procState = getService().getUidProcessState(uid,
3785                     mContext.getOpPackageName());
3786             return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3787         } catch (RemoteException e) {
3788             throw e.rethrowFromSystemServer();
3789         }
3790     }
3791 
3792     /**
3793      * Callback to get reports about changes to the importance of a uid.  Use with
3794      * {@link #addOnUidImportanceListener}.
3795      * @hide
3796      */
3797     @SystemApi
3798     public interface OnUidImportanceListener {
3799         /**
3800          * The importance if a given uid has changed.  Will be one of the importance
3801          * values in {@link RunningAppProcessInfo};
3802          * {@link RunningAppProcessInfo#IMPORTANCE_GONE IMPORTANCE_GONE} will be reported
3803          * when the uid is no longer running at all.  This callback will happen on a thread
3804          * from a thread pool, not the main UI thread.
3805          * @param uid The uid whose importance has changed.
3806          * @param importance The new importance value as per {@link RunningAppProcessInfo}.
3807          */
onUidImportance(int uid, @RunningAppProcessInfo.Importance int importance)3808         void onUidImportance(int uid, @RunningAppProcessInfo.Importance int importance);
3809     }
3810 
3811     /**
3812      * Start monitoring changes to the imoportance of uids running in the system.
3813      * @param listener The listener callback that will receive change reports.
3814      * @param importanceCutpoint The level of importance in which the caller is interested
3815      * in differences.  For example, if {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}
3816      * is used here, you will receive a call each time a uids importance transitions between
3817      * being <= {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE} and
3818      * > {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}.
3819      *
3820      * <p>The caller must hold the {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
3821      * permission to use this feature.</p>
3822      *
3823      * @throws IllegalArgumentException If the listener is already registered.
3824      * @throws SecurityException If the caller does not hold
3825      * {@link android.Manifest.permission#PACKAGE_USAGE_STATS}.
3826      * @hide
3827      */
3828     @SystemApi
3829     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
addOnUidImportanceListener(OnUidImportanceListener listener, @RunningAppProcessInfo.Importance int importanceCutpoint)3830     public void addOnUidImportanceListener(OnUidImportanceListener listener,
3831             @RunningAppProcessInfo.Importance int importanceCutpoint) {
3832         synchronized (this) {
3833             if (mImportanceListeners.containsKey(listener)) {
3834                 throw new IllegalArgumentException("Listener already registered: " + listener);
3835             }
3836             // TODO: implement the cut point in the system process to avoid IPCs.
3837             UidObserver observer = new UidObserver(listener, mContext);
3838             try {
3839                 getService().registerUidObserver(observer,
3840                         UID_OBSERVER_PROCSTATE | UID_OBSERVER_GONE,
3841                         RunningAppProcessInfo.importanceToProcState(importanceCutpoint),
3842                         mContext.getOpPackageName());
3843             } catch (RemoteException e) {
3844                 throw e.rethrowFromSystemServer();
3845             }
3846             mImportanceListeners.put(listener, observer);
3847         }
3848     }
3849 
3850     /**
3851      * Remove an importance listener that was previously registered with
3852      * {@link #addOnUidImportanceListener}.
3853      *
3854      * @throws IllegalArgumentException If the listener is not registered.
3855      * @hide
3856      */
3857     @SystemApi
3858     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
removeOnUidImportanceListener(OnUidImportanceListener listener)3859     public void removeOnUidImportanceListener(OnUidImportanceListener listener) {
3860         synchronized (this) {
3861             UidObserver observer = mImportanceListeners.remove(listener);
3862             if (observer == null) {
3863                 throw new IllegalArgumentException("Listener not registered: " + listener);
3864             }
3865             try {
3866                 getService().unregisterUidObserver(observer);
3867             } catch (RemoteException e) {
3868                 throw e.rethrowFromSystemServer();
3869             }
3870         }
3871     }
3872 
3873     /**
3874      * Return global memory state information for the calling process.  This
3875      * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
3876      * only fields that will be filled in are
3877      * {@link RunningAppProcessInfo#pid},
3878      * {@link RunningAppProcessInfo#uid},
3879      * {@link RunningAppProcessInfo#lastTrimLevel},
3880      * {@link RunningAppProcessInfo#importance},
3881      * {@link RunningAppProcessInfo#lru}, and
3882      * {@link RunningAppProcessInfo#importanceReasonCode}.
3883      */
getMyMemoryState(RunningAppProcessInfo outState)3884     static public void getMyMemoryState(RunningAppProcessInfo outState) {
3885         try {
3886             getService().getMyMemoryState(outState);
3887         } catch (RemoteException e) {
3888             throw e.rethrowFromSystemServer();
3889         }
3890     }
3891 
3892     /**
3893      * Return information about the memory usage of one or more processes.
3894      *
3895      * <p><b>Note: this method is only intended for debugging or building
3896      * a user-facing process management UI.</b></p>
3897      *
3898      * <p>As of {@link android.os.Build.VERSION_CODES#Q Android Q}, for regular apps this method
3899      * will only return information about the memory info for the processes running as the
3900      * caller's uid; no other process memory info is available and will be zero.
3901      * Also of {@link android.os.Build.VERSION_CODES#Q Android Q} the sample rate allowed
3902      * by this API is significantly limited, if called faster the limit you will receive the
3903      * same data as the previous call.</p>
3904      *
3905      * @param pids The pids of the processes whose memory usage is to be
3906      * retrieved.
3907      * @return Returns an array of memory information, one for each
3908      * requested pid.
3909      */
getProcessMemoryInfo(int[] pids)3910     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3911         try {
3912             return getService().getProcessMemoryInfo(pids);
3913         } catch (RemoteException e) {
3914             throw e.rethrowFromSystemServer();
3915         }
3916     }
3917 
3918     /**
3919      * @deprecated This is now just a wrapper for
3920      * {@link #killBackgroundProcesses(String)}; the previous behavior here
3921      * is no longer available to applications because it allows them to
3922      * break other applications by removing their alarms, stopping their
3923      * services, etc.
3924      */
3925     @Deprecated
restartPackage(String packageName)3926     public void restartPackage(String packageName) {
3927         killBackgroundProcesses(packageName);
3928     }
3929 
3930     /**
3931      * Have the system immediately kill all background processes associated
3932      * with the given package.  This is the same as the kernel killing those
3933      * processes to reclaim memory; the system will take care of restarting
3934      * these processes in the future as needed.
3935      *
3936      * <p class="note">Third party applications can only use this API to kill their own processes.
3937      * </p>
3938      *
3939      * @param packageName The name of the package whose processes are to
3940      * be killed.
3941      */
3942     @RequiresPermission(Manifest.permission.KILL_BACKGROUND_PROCESSES)
killBackgroundProcesses(String packageName)3943     public void killBackgroundProcesses(String packageName) {
3944         try {
3945             getService().killBackgroundProcesses(packageName,
3946                     mContext.getUserId());
3947         } catch (RemoteException e) {
3948             throw e.rethrowFromSystemServer();
3949         }
3950     }
3951 
3952     /**
3953      * Kills the specified UID.
3954      * @param uid The UID to kill.
3955      * @param reason The reason for the kill.
3956      *
3957      * @hide
3958      */
3959     @SystemApi
3960     @RequiresPermission(Manifest.permission.KILL_UID)
killUid(int uid, String reason)3961     public void killUid(int uid, String reason) {
3962         try {
3963             getService().killUid(UserHandle.getAppId(uid),
3964                     UserHandle.getUserId(uid), reason);
3965         } catch (RemoteException e) {
3966             throw e.rethrowFromSystemServer();
3967         }
3968     }
3969 
3970     /**
3971      * Have the system perform a force stop of everything associated with
3972      * the given application package.  All processes that share its uid
3973      * will be killed, all services it has running stopped, all activities
3974      * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
3975      * broadcast will be sent, so that any of its registered alarms can
3976      * be stopped, notifications removed, etc.
3977      *
3978      * <p>You must hold the permission
3979      * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
3980      * call this method.
3981      *
3982      * @param packageName The name of the package to be stopped.
3983      * @param userId The user for which the running package is to be stopped.
3984      *
3985      * @hide This is not available to third party applications due to
3986      * it allowing them to break other applications by stopping their
3987      * services, removing their alarms, etc.
3988      */
3989     @UnsupportedAppUsage
forceStopPackageAsUser(String packageName, int userId)3990     public void forceStopPackageAsUser(String packageName, int userId) {
3991         try {
3992             getService().forceStopPackage(packageName, userId);
3993         } catch (RemoteException e) {
3994             throw e.rethrowFromSystemServer();
3995         }
3996     }
3997 
3998     /**
3999      * @see #forceStopPackageAsUser(String, int)
4000      * @hide
4001      */
4002     @SystemApi
4003     @RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
forceStopPackage(String packageName)4004     public void forceStopPackage(String packageName) {
4005         forceStopPackageAsUser(packageName, mContext.getUserId());
4006     }
4007 
4008     /**
4009      * Sets the current locales of the device. Calling app must have the permission
4010      * {@code android.permission.CHANGE_CONFIGURATION} and
4011      * {@code android.permission.WRITE_SETTINGS}.
4012      *
4013      * @hide
4014      */
4015     @SystemApi
setDeviceLocales(@onNull LocaleList locales)4016     public void setDeviceLocales(@NonNull LocaleList locales) {
4017         LocalePicker.updateLocales(locales);
4018     }
4019 
4020     /**
4021      * Returns a list of supported locales by this system. It includes all locales that are
4022      * selectable by the user, potentially including locales that the framework does not have
4023      * translated resources for. To get locales that the framework has translated resources for, use
4024      * {@code Resources.getSystem().getAssets().getLocales()} instead.
4025      *
4026      * @hide
4027      */
4028     @SystemApi
getSupportedLocales()4029     public @NonNull Collection<Locale> getSupportedLocales() {
4030         ArrayList<Locale> locales = new ArrayList<>();
4031         for (String localeTag : LocalePicker.getSupportedLocales(mContext)) {
4032             locales.add(Locale.forLanguageTag(localeTag));
4033         }
4034         return locales;
4035     }
4036 
4037     /**
4038      * Get the device configuration attributes.
4039      */
getDeviceConfigurationInfo()4040     public ConfigurationInfo getDeviceConfigurationInfo() {
4041         try {
4042             return getTaskService().getDeviceConfigurationInfo();
4043         } catch (RemoteException e) {
4044             throw e.rethrowFromSystemServer();
4045         }
4046     }
4047 
4048     /**
4049      * Get the preferred density of icons for the launcher. This is used when
4050      * custom drawables are created (e.g., for shortcuts).
4051      *
4052      * @return density in terms of DPI
4053      */
getLauncherLargeIconDensity()4054     public int getLauncherLargeIconDensity() {
4055         final Resources res = mContext.getResources();
4056         final int density = res.getDisplayMetrics().densityDpi;
4057         final int sw = res.getConfiguration().smallestScreenWidthDp;
4058 
4059         if (sw < 600) {
4060             // Smaller than approx 7" tablets, use the regular icon size.
4061             return density;
4062         }
4063 
4064         switch (density) {
4065             case DisplayMetrics.DENSITY_LOW:
4066                 return DisplayMetrics.DENSITY_MEDIUM;
4067             case DisplayMetrics.DENSITY_MEDIUM:
4068                 return DisplayMetrics.DENSITY_HIGH;
4069             case DisplayMetrics.DENSITY_TV:
4070                 return DisplayMetrics.DENSITY_XHIGH;
4071             case DisplayMetrics.DENSITY_HIGH:
4072                 return DisplayMetrics.DENSITY_XHIGH;
4073             case DisplayMetrics.DENSITY_XHIGH:
4074                 return DisplayMetrics.DENSITY_XXHIGH;
4075             case DisplayMetrics.DENSITY_XXHIGH:
4076                 return DisplayMetrics.DENSITY_XHIGH * 2;
4077             default:
4078                 // The density is some abnormal value.  Return some other
4079                 // abnormal value that is a reasonable scaling of it.
4080                 return (int)((density*1.5f)+.5f);
4081         }
4082     }
4083 
4084     /**
4085      * Get the preferred launcher icon size. This is used when custom drawables
4086      * are created (e.g., for shortcuts).
4087      *
4088      * @return dimensions of square icons in terms of pixels
4089      */
getLauncherLargeIconSize()4090     public int getLauncherLargeIconSize() {
4091         return getLauncherLargeIconSizeInner(mContext);
4092     }
4093 
getLauncherLargeIconSizeInner(Context context)4094     static int getLauncherLargeIconSizeInner(Context context) {
4095         final Resources res = context.getResources();
4096         final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
4097         final int sw = res.getConfiguration().smallestScreenWidthDp;
4098 
4099         if (sw < 600) {
4100             // Smaller than approx 7" tablets, use the regular icon size.
4101             return size;
4102         }
4103 
4104         final int density = res.getDisplayMetrics().densityDpi;
4105 
4106         switch (density) {
4107             case DisplayMetrics.DENSITY_LOW:
4108                 return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
4109             case DisplayMetrics.DENSITY_MEDIUM:
4110                 return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
4111             case DisplayMetrics.DENSITY_TV:
4112                 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
4113             case DisplayMetrics.DENSITY_HIGH:
4114                 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
4115             case DisplayMetrics.DENSITY_XHIGH:
4116                 return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
4117             case DisplayMetrics.DENSITY_XXHIGH:
4118                 return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
4119             default:
4120                 // The density is some abnormal value.  Return some other
4121                 // abnormal value that is a reasonable scaling of it.
4122                 return (int)((size*1.5f) + .5f);
4123         }
4124     }
4125 
4126     /**
4127      * Returns "true" if the user interface is currently being messed with
4128      * by a monkey.
4129      */
isUserAMonkey()4130     public static boolean isUserAMonkey() {
4131         try {
4132             return getService().isUserAMonkey();
4133         } catch (RemoteException e) {
4134             throw e.rethrowFromSystemServer();
4135         }
4136     }
4137 
4138     /**
4139      * Returns "true" if device is running in a test harness.
4140      *
4141      * @deprecated this method is false for all user builds. Users looking to check if their device
4142      * is running in a device farm should see {@link #isRunningInUserTestHarness()}.
4143      */
4144     @Deprecated
isRunningInTestHarness()4145     public static boolean isRunningInTestHarness() {
4146         return SystemProperties.getBoolean("ro.test_harness", false);
4147     }
4148 
4149     /**
4150      * Returns "true" if the device is running in Test Harness Mode.
4151      *
4152      * <p>Test Harness Mode is a feature that allows devices to run without human interaction in a
4153      * device farm/testing harness (such as Firebase Test Lab). You should check this method if you
4154      * want your app to behave differently when running in a test harness to skip setup screens that
4155      * would impede UI testing. e.g. a keyboard application that has a full screen setup page for
4156      * the first time it is launched.
4157      *
4158      * <p>Note that you should <em>not</em> use this to determine whether or not your app is running
4159      * an instrumentation test, as it is not set for a standard device running a test.
4160      */
isRunningInUserTestHarness()4161     public static boolean isRunningInUserTestHarness() {
4162         return SystemProperties.getBoolean("persist.sys.test_harness", false);
4163     }
4164 
4165     /**
4166      * Unsupported compiled sdk warning should always be shown for the intput activity
4167      * even in cases where the system would normally not show the warning. E.g. when running in a
4168      * test harness.
4169      *
4170      * @param activity The component name of the activity to always show the warning for.
4171      *
4172      * @hide
4173      */
4174     @TestApi
alwaysShowUnsupportedCompileSdkWarning(ComponentName activity)4175     public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4176         try {
4177             getTaskService().alwaysShowUnsupportedCompileSdkWarning(activity);
4178         } catch (RemoteException e) {
4179             throw e.rethrowFromSystemServer();
4180         }
4181     }
4182 
4183     /**
4184      * Returns the launch count of each installed package.
4185      *
4186      * @hide
4187      */
4188     /*public Map<String, Integer> getAllPackageLaunchCounts() {
4189         try {
4190             IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
4191                     ServiceManager.getService("usagestats"));
4192             if (usageStatsService == null) {
4193                 return new HashMap<String, Integer>();
4194             }
4195 
4196             UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
4197                     ActivityThread.currentPackageName());
4198             if (allPkgUsageStats == null) {
4199                 return new HashMap<String, Integer>();
4200             }
4201 
4202             Map<String, Integer> launchCounts = new HashMap<String, Integer>();
4203             for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
4204                 launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
4205             }
4206 
4207             return launchCounts;
4208         } catch (RemoteException e) {
4209             Log.w(TAG, "Could not query launch counts", e);
4210             return new HashMap<String, Integer>();
4211         }
4212     }*/
4213 
4214     /** @hide */
4215     @UnsupportedAppUsage
checkComponentPermission(String permission, int uid, int owningUid, boolean exported)4216     public static int checkComponentPermission(String permission, int uid,
4217             int owningUid, boolean exported) {
4218         // Root, system server get to do everything.
4219         final int appId = UserHandle.getAppId(uid);
4220         if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
4221             return PackageManager.PERMISSION_GRANTED;
4222         }
4223         // Isolated processes don't get any permissions.
4224         if (UserHandle.isIsolated(uid)) {
4225             return PackageManager.PERMISSION_DENIED;
4226         }
4227         // If there is a uid that owns whatever is being accessed, it has
4228         // blanket access to it regardless of the permissions it requires.
4229         if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
4230             return PackageManager.PERMISSION_GRANTED;
4231         }
4232         // If the target is not exported, then nobody else can get to it.
4233         if (!exported) {
4234             /*
4235             RuntimeException here = new RuntimeException("here");
4236             here.fillInStackTrace();
4237             Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
4238                     here);
4239             */
4240             return PackageManager.PERMISSION_DENIED;
4241         }
4242         if (permission == null) {
4243             return PackageManager.PERMISSION_GRANTED;
4244         }
4245         try {
4246             return AppGlobals.getPackageManager()
4247                     .checkUidPermission(permission, uid);
4248         } catch (RemoteException e) {
4249             throw e.rethrowFromSystemServer();
4250         }
4251     }
4252 
4253     /** @hide */
checkUidPermission(String permission, int uid)4254     public static int checkUidPermission(String permission, int uid) {
4255         try {
4256             return AppGlobals.getPackageManager()
4257                     .checkUidPermission(permission, uid);
4258         } catch (RemoteException e) {
4259             throw e.rethrowFromSystemServer();
4260         }
4261     }
4262 
4263     /**
4264      * @hide
4265      * Helper for dealing with incoming user arguments to system service calls.
4266      * Takes care of checking permissions and converting USER_CURRENT to the
4267      * actual current user.
4268      *
4269      * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
4270      * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
4271      * @param userId The user id argument supplied by the caller -- this is the user
4272      * they want to run as.
4273      * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
4274      * to get a USER_ALL returned and deal with it correctly.  If false,
4275      * an exception will be thrown if USER_ALL is supplied.
4276      * @param requireFull If true, the caller must hold
4277      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
4278      * different user than their current process; otherwise they must hold
4279      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
4280      * @param name Optional textual name of the incoming call; only for generating error messages.
4281      * @param callerPackage Optional package name of caller; only for error messages.
4282      *
4283      * @return Returns the user ID that the call should run as.  Will always be a concrete
4284      * user number, unless <var>allowAll</var> is true in which case it could also be
4285      * USER_ALL.
4286      */
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)4287     public static int handleIncomingUser(int callingPid, int callingUid, int userId,
4288             boolean allowAll, boolean requireFull, String name, String callerPackage) {
4289         if (UserHandle.getUserId(callingUid) == userId) {
4290             return userId;
4291         }
4292         try {
4293             return getService().handleIncomingUser(callingPid,
4294                     callingUid, userId, allowAll, requireFull, name, callerPackage);
4295         } catch (RemoteException e) {
4296             throw e.rethrowFromSystemServer();
4297         }
4298     }
4299 
4300     /**
4301      * Gets the userId of the current foreground user. Requires system permissions.
4302      * @hide
4303      */
4304     @SystemApi
4305     @RequiresPermission(anyOf = {
4306             "android.permission.INTERACT_ACROSS_USERS",
4307             "android.permission.INTERACT_ACROSS_USERS_FULL"
4308     })
getCurrentUser()4309     public static int getCurrentUser() {
4310         try {
4311             return getService().getCurrentUserId();
4312         } catch (RemoteException e) {
4313             throw e.rethrowFromSystemServer();
4314         }
4315     }
4316 
4317     /**
4318      * @param userid the user's id. Zero indicates the default user.
4319      * @hide
4320      */
4321     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
switchUser(int userid)4322     public boolean switchUser(int userid) {
4323         try {
4324             return getService().switchUser(userid);
4325         } catch (RemoteException e) {
4326             throw e.rethrowFromSystemServer();
4327         }
4328     }
4329 
4330     /**
4331      * Returns whether switching to provided user was successful.
4332      *
4333      * @param user the user to switch to.
4334      *
4335      * @throws IllegalArgumentException if the user is null.
4336      * @hide
4337      */
4338     @SystemApi
4339     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4340             android.Manifest.permission.CREATE_USERS})
switchUser(@onNull UserHandle user)4341     public boolean switchUser(@NonNull UserHandle user) {
4342         if (user == null) {
4343             throw new IllegalArgumentException("UserHandle cannot be null.");
4344         }
4345         return switchUser(user.getIdentifier());
4346     }
4347 
4348     /**
4349      * Gets the message that is shown when a user is switched from.
4350      *
4351      * @hide
4352      */
4353     @RequiresPermission(Manifest.permission.MANAGE_USERS)
getSwitchingFromUserMessage()4354     public @Nullable String getSwitchingFromUserMessage() {
4355         try {
4356             return getService().getSwitchingFromUserMessage();
4357         } catch (RemoteException re) {
4358             throw re.rethrowFromSystemServer();
4359         }
4360     }
4361 
4362     /**
4363      * Gets the message that is shown when a user is switched to.
4364      *
4365      * @hide
4366      */
4367     @RequiresPermission(Manifest.permission.MANAGE_USERS)
getSwitchingToUserMessage()4368     public @Nullable String getSwitchingToUserMessage() {
4369         try {
4370             return getService().getSwitchingToUserMessage();
4371         } catch (RemoteException re) {
4372             throw re.rethrowFromSystemServer();
4373         }
4374     }
4375 
4376     /**
4377      * Uses the value defined by the platform.
4378      *
4379      * @hide
4380      */
4381     @TestApi
4382     public static final int STOP_USER_ON_SWITCH_DEFAULT = -1;
4383 
4384     /**
4385      * Overrides value defined by the platform and stop user on switch.
4386      *
4387      * @hide
4388      */
4389     @TestApi
4390     public static final int STOP_USER_ON_SWITCH_TRUE = 1;
4391 
4392     /**
4393      * Overrides value defined by the platform and don't stop user on switch.
4394      *
4395      * @hide
4396      */
4397     @TestApi
4398     public static final int STOP_USER_ON_SWITCH_FALSE = 0;
4399 
4400     /** @hide */
4401     @IntDef(prefix = { "STOP_USER_ON_SWITCH_" }, value = {
4402             STOP_USER_ON_SWITCH_DEFAULT,
4403             STOP_USER_ON_SWITCH_TRUE,
4404             STOP_USER_ON_SWITCH_FALSE
4405     })
4406     public @interface StopUserOnSwitch {}
4407 
4408     /**
4409      * Sets whether the current foreground user (and its profiles) should be stopped after switched
4410      * out.
4411      *
4412      * <p>Should only be used on tests. Doesn't apply to {@link UserHandle#SYSTEM system user}.
4413      *
4414      * @hide
4415      */
4416     @TestApi
4417     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4418             android.Manifest.permission.INTERACT_ACROSS_USERS})
setStopUserOnSwitch(@topUserOnSwitch int value)4419     public void setStopUserOnSwitch(@StopUserOnSwitch int value) {
4420         try {
4421             getService().setStopUserOnSwitch(value);
4422         } catch (RemoteException re) {
4423             throw re.rethrowFromSystemServer();
4424         }
4425     }
4426 
4427     /**
4428      * Starts a profile.
4429      * To be used with non-managed profiles, managed profiles should use
4430      * {@link UserManager#requestQuietModeEnabled}
4431      *
4432      * @param userHandle user handle of the profile.
4433      * @return true if the profile has been successfully started or if the profile is already
4434      * running, false if profile failed to start.
4435      * @throws IllegalArgumentException if {@code userHandle} is not a profile.
4436      *
4437      * @hide
4438      */
4439     @SystemApi
4440     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4441             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL})
startProfile(@onNull UserHandle userHandle)4442     public boolean startProfile(@NonNull UserHandle userHandle) {
4443         try {
4444             return getService().startProfile(userHandle.getIdentifier());
4445         } catch (RemoteException re) {
4446             throw re.rethrowFromSystemServer();
4447         }
4448     }
4449 
4450     /**
4451      * Stops a running profile.
4452      * To be used with non-managed profiles, managed profiles should use
4453      * {@link UserManager#requestQuietModeEnabled}
4454      *
4455      * @param userHandle user handle of the profile.
4456      * @return true if the profile has been successfully stopped or is already stopped. Otherwise
4457      * the exceptions listed below are thrown.
4458      * @throws IllegalArgumentException if {@code userHandle} is not a profile.
4459      *
4460      * @hide
4461      */
4462     @SystemApi
4463     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4464             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL})
stopProfile(@onNull UserHandle userHandle)4465     public boolean stopProfile(@NonNull UserHandle userHandle) {
4466         try {
4467             return getService().stopProfile(userHandle.getIdentifier());
4468         } catch (RemoteException re) {
4469             throw re.rethrowFromSystemServer();
4470         }
4471     }
4472 
4473     /**
4474      * Updates the MCC (Mobile Country Code) and MNC (Mobile Network Code) in the
4475      * system configuration.
4476      *
4477      * @param mcc The new MCC.
4478      * @param mnc The new MNC.
4479      * @throws RemoteException; IllegalArgumentException if mcc or mnc is null;
4480      * @return Returns {@code true} if the configuration was updated successfully;
4481      *         {@code false} otherwise.
4482      * @hide
4483      */
4484     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
4485     @TestApi
4486     @RequiresPermission(android.Manifest.permission.CHANGE_CONFIGURATION)
updateMccMncConfiguration(@onNull String mcc, @NonNull String mnc)4487     public boolean updateMccMncConfiguration(@NonNull String mcc, @NonNull String mnc) {
4488         if (mcc == null || mnc == null) {
4489             throw new IllegalArgumentException("mcc or mnc cannot be null.");
4490         }
4491         try {
4492             return getService().updateMccMncConfiguration(mcc, mnc);
4493         } catch (RemoteException e) {
4494             throw e.rethrowFromSystemServer();
4495         }
4496     }
4497 
4498     /**
4499      * Stops the given {@code userId}.
4500      *
4501      * @hide
4502      */
4503     @TestApi
4504     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
stopUser(@serIdInt int userId, boolean force)4505     public boolean stopUser(@UserIdInt int userId, boolean force) {
4506         if (userId == UserHandle.USER_SYSTEM) {
4507             return false;
4508         }
4509         try {
4510             return USER_OP_SUCCESS == getService().stopUser(
4511                     userId, force, /* callback= */ null);
4512         } catch (RemoteException e) {
4513             throw e.rethrowFromSystemServer();
4514         }
4515     }
4516 
4517     /** {@hide} */
4518     public static final int FLAG_OR_STOPPED = 1 << 0;
4519     /** {@hide} */
4520     public static final int FLAG_AND_LOCKED = 1 << 1;
4521     /** {@hide} */
4522     public static final int FLAG_AND_UNLOCKED = 1 << 2;
4523     /** {@hide} */
4524     public static final int FLAG_AND_UNLOCKING_OR_UNLOCKED = 1 << 3;
4525 
4526     /**
4527      * Return whether the given user is actively running.  This means that
4528      * the user is in the "started" state, not "stopped" -- it is currently
4529      * allowed to run code through scheduled alarms, receiving broadcasts,
4530      * etc.  A started user may be either the current foreground user or a
4531      * background user; the result here does not distinguish between the two.
4532      * @param userId the user's id. Zero indicates the default user.
4533      * @hide
4534      */
4535     @UnsupportedAppUsage
isUserRunning(int userId)4536     public boolean isUserRunning(int userId) {
4537         try {
4538             return getService().isUserRunning(userId, 0);
4539         } catch (RemoteException e) {
4540             throw e.rethrowFromSystemServer();
4541         }
4542     }
4543 
4544     /** {@hide} */
isVrModePackageEnabled(ComponentName component)4545     public boolean isVrModePackageEnabled(ComponentName component) {
4546         try {
4547             return getService().isVrModePackageEnabled(component);
4548         } catch (RemoteException e) {
4549             throw e.rethrowFromSystemServer();
4550         }
4551     }
4552 
4553     /**
4554      * Perform a system dump of various state associated with the given application
4555      * package name.  This call blocks while the dump is being performed, so should
4556      * not be done on a UI thread.  The data will be written to the given file
4557      * descriptor as text.
4558      * @param fd The file descriptor that the dump should be written to.  The file
4559      * descriptor is <em>not</em> closed by this function; the caller continues to
4560      * own it.
4561      * @param packageName The name of the package that is to be dumped.
4562      */
4563     @RequiresPermission(Manifest.permission.DUMP)
dumpPackageState(FileDescriptor fd, String packageName)4564     public void dumpPackageState(FileDescriptor fd, String packageName) {
4565         dumpPackageStateStatic(fd, packageName);
4566     }
4567 
4568     /**
4569      * @hide
4570      */
dumpPackageStateStatic(FileDescriptor fd, String packageName)4571     public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
4572         FileOutputStream fout = new FileOutputStream(fd);
4573         PrintWriter pw = new FastPrintWriter(fout);
4574         dumpService(pw, fd, "package", new String[] { packageName });
4575         pw.println();
4576         dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
4577                 "-a", "package", packageName });
4578         pw.println();
4579         dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
4580         pw.println();
4581         dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
4582         pw.println();
4583         dumpService(pw, fd, "usagestats", new String[] { packageName });
4584         pw.println();
4585         dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
4586         pw.flush();
4587     }
4588 
4589     /**
4590      * @hide
4591      */
isSystemReady()4592     public static boolean isSystemReady() {
4593         if (!sSystemReady) {
4594             if (ActivityThread.isSystem()) {
4595                 sSystemReady =
4596                         LocalServices.getService(ActivityManagerInternal.class).isSystemReady();
4597             } else {
4598                 // Since this is being called from outside system server, system should be
4599                 // ready by now.
4600                 sSystemReady = true;
4601             }
4602         }
4603         return sSystemReady;
4604     }
4605 
4606     /**
4607      * @hide
4608      */
broadcastStickyIntent(Intent intent, int userId)4609     public static void broadcastStickyIntent(Intent intent, int userId) {
4610         broadcastStickyIntent(intent, AppOpsManager.OP_NONE, userId);
4611     }
4612 
4613     /**
4614      * Convenience for sending a sticky broadcast.  For internal use only.
4615      *
4616      * @hide
4617      */
broadcastStickyIntent(Intent intent, int appOp, int userId)4618     public static void broadcastStickyIntent(Intent intent, int appOp, int userId) {
4619         try {
4620             getService().broadcastIntentWithFeature(
4621                     null, null, intent, null, null, Activity.RESULT_OK, null, null,
4622                     null /*requiredPermissions*/, null /*excludedPermissions*/,
4623                     null /*excludedPackages*/, appOp, null, false, true, userId);
4624         } catch (RemoteException ex) {
4625         }
4626     }
4627 
4628     /**
4629      * @hide
4630      */
4631     @TestApi
resumeAppSwitches()4632     public static void resumeAppSwitches() throws RemoteException {
4633         getService().resumeAppSwitches();
4634     }
4635 
4636     /**
4637      * @hide
4638      */
noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)4639     public static void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid,
4640             String sourcePkg, String tag) {
4641         try {
4642             getService().noteWakeupAlarm((ps != null) ? ps.getTarget() : null, workSource,
4643                     sourceUid, sourcePkg, tag);
4644         } catch (RemoteException ex) {
4645         }
4646     }
4647 
4648     /**
4649      * @hide
4650      */
noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)4651     public static void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid,
4652             String tag) {
4653         try {
4654             getService().noteAlarmStart((ps != null) ? ps.getTarget() : null, workSource,
4655                     sourceUid, tag);
4656         } catch (RemoteException ex) {
4657         }
4658     }
4659 
4660 
4661     /**
4662      * @hide
4663      */
noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)4664     public static void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid,
4665             String tag) {
4666         try {
4667             getService().noteAlarmFinish((ps != null) ? ps.getTarget() : null, workSource,
4668                     sourceUid, tag);
4669         } catch (RemoteException ex) {
4670         }
4671     }
4672 
4673     /**
4674      * @hide
4675      */
4676     @UnsupportedAppUsage
getService()4677     public static IActivityManager getService() {
4678         return IActivityManagerSingleton.get();
4679     }
4680 
getTaskService()4681     private static IActivityTaskManager getTaskService() {
4682         return ActivityTaskManager.getService();
4683     }
4684 
4685     @UnsupportedAppUsage
4686     private static final Singleton<IActivityManager> IActivityManagerSingleton =
4687             new Singleton<IActivityManager>() {
4688                 @Override
4689                 protected IActivityManager create() {
4690                     final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
4691                     final IActivityManager am = IActivityManager.Stub.asInterface(b);
4692                     return am;
4693                 }
4694             };
4695 
dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args)4696     private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
4697         pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
4698         IBinder service = ServiceManager.checkService(name);
4699         if (service == null) {
4700             pw.println("  (Service not found)");
4701             pw.flush();
4702             return;
4703         }
4704         pw.flush();
4705         if (service instanceof Binder) {
4706             // If this is a local object, it doesn't make sense to do an async dump with it,
4707             // just directly dump.
4708             try {
4709                 service.dump(fd, args);
4710             } catch (Throwable e) {
4711                 pw.println("Failure dumping service:");
4712                 e.printStackTrace(pw);
4713                 pw.flush();
4714             }
4715         } else {
4716             // Otherwise, it is remote, do the dump asynchronously to avoid blocking.
4717             TransferPipe tp = null;
4718             try {
4719                 pw.flush();
4720                 tp = new TransferPipe();
4721                 tp.setBufferPrefix("  ");
4722                 service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
4723                 tp.go(fd, 10000);
4724             } catch (Throwable e) {
4725                 if (tp != null) {
4726                     tp.kill();
4727                 }
4728                 pw.println("Failure dumping service:");
4729                 e.printStackTrace(pw);
4730             }
4731         }
4732     }
4733 
4734     /**
4735      * Request that the system start watching for the calling process to exceed a pss
4736      * size as given here.  Once called, the system will look for any occasions where it
4737      * sees the associated process with a larger pss size and, when this happens, automatically
4738      * pull a heap dump from it and allow the user to share the data.  Note that this request
4739      * continues running even if the process is killed and restarted.  To remove the watch,
4740      * use {@link #clearWatchHeapLimit()}.
4741      *
4742      * <p>This API only works if the calling process has been marked as
4743      * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
4744      * (userdebug or eng) build.</p>
4745      *
4746      * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
4747      * handle heap limit reports themselves.</p>
4748      *
4749      * @param pssSize The size in bytes to set the limit at.
4750      */
setWatchHeapLimit(long pssSize)4751     public void setWatchHeapLimit(long pssSize) {
4752         try {
4753             getService().setDumpHeapDebugLimit(null, 0, pssSize,
4754                     mContext.getPackageName());
4755         } catch (RemoteException e) {
4756             throw e.rethrowFromSystemServer();
4757         }
4758     }
4759 
4760     /**
4761      * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
4762      * If your package has an activity handling this action, it will be launched with the
4763      * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
4764      * match, the activity must support this action and a MIME type of "*&#47;*".
4765      */
4766     public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
4767 
4768     /**
4769      * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
4770      */
clearWatchHeapLimit()4771     public void clearWatchHeapLimit() {
4772         try {
4773             getService().setDumpHeapDebugLimit(null, 0, 0, null);
4774         } catch (RemoteException e) {
4775             throw e.rethrowFromSystemServer();
4776         }
4777     }
4778 
4779     /**
4780      * Return whether currently in lock task mode.  When in this mode
4781      * no new tasks can be created or switched to.
4782      *
4783      * @see Activity#startLockTask()
4784      *
4785      * @deprecated Use {@link #getLockTaskModeState} instead.
4786      */
4787     @Deprecated
isInLockTaskMode()4788     public boolean isInLockTaskMode() {
4789         return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
4790     }
4791 
4792     /**
4793      * Return the current state of task locking. The three possible outcomes
4794      * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
4795      * and {@link #LOCK_TASK_MODE_PINNED}.
4796      *
4797      * @see Activity#startLockTask()
4798      */
getLockTaskModeState()4799     public int getLockTaskModeState() {
4800         try {
4801             return getTaskService().getLockTaskModeState();
4802         } catch (RemoteException e) {
4803             throw e.rethrowFromSystemServer();
4804         }
4805     }
4806 
4807     /**
4808      * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads. Only one
4809      * thread can be a VR thread in a process at a time, and that thread may be subject to
4810      * restrictions on the amount of time it can run.
4811      *
4812      * If persistent VR mode is set, whatever thread has been granted aggressive scheduling via this
4813      * method will return to normal operation, and calling this method will do nothing while
4814      * persistent VR mode is enabled.
4815      *
4816      * To reset the VR thread for an application, a tid of 0 can be passed.
4817      *
4818      * @see android.os.Process#myTid()
4819      * @param tid tid of the VR thread
4820      */
setVrThread(int tid)4821     public static void setVrThread(int tid) {
4822         try {
4823             getTaskService().setVrThread(tid);
4824         } catch (RemoteException e) {
4825             // pass
4826         }
4827     }
4828 
4829     /**
4830      * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads that persist
4831      * beyond a single process. Only one thread can be a
4832      * persistent VR thread at a time, and that thread may be subject to restrictions on the amount
4833      * of time it can run. Calling this method will disable aggressive scheduling for non-persistent
4834      * VR threads set via {@link #setVrThread}. If persistent VR mode is disabled then the
4835      * persistent VR thread loses its new scheduling priority; this method must be called again to
4836      * set the persistent thread.
4837      *
4838      * To reset the persistent VR thread, a tid of 0 can be passed.
4839      *
4840      * @see android.os.Process#myTid()
4841      * @param tid tid of the VR thread
4842      * @hide
4843      */
4844     @SystemApi
4845     @RequiresPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
setPersistentVrThread(int tid)4846     public static void setPersistentVrThread(int tid) {
4847         try {
4848             getService().setPersistentVrThread(tid);
4849         } catch (RemoteException e) {
4850             // pass
4851         }
4852     }
4853 
4854     /**
4855      * @hide
4856      */
4857     @TestApi
4858     @RequiresPermission(Manifest.permission.CHANGE_CONFIGURATION)
scheduleApplicationInfoChanged(List<String> packages, int userId)4859     public void scheduleApplicationInfoChanged(List<String> packages, int userId) {
4860         try {
4861             getService().scheduleApplicationInfoChanged(packages, userId);
4862         } catch (RemoteException e) {
4863             throw e.rethrowFromSystemServer();
4864         }
4865     }
4866 
4867     /**
4868      * Return if a given profile is in the foreground.
4869      * @param userHandle UserHandle to check
4870      * @return Returns the boolean result.
4871      * @hide
4872      */
4873     @RequiresPermission(anyOf = {
4874             android.Manifest.permission.MANAGE_USERS,
4875             android.Manifest.permission.CREATE_USERS
4876     })
isProfileForeground(@onNull UserHandle userHandle)4877     public boolean isProfileForeground(@NonNull UserHandle userHandle) {
4878         UserManager userManager = mContext.getSystemService(UserManager.class);
4879         if (userManager != null) {
4880             for (UserInfo userInfo : userManager.getProfiles(getCurrentUser())) {
4881                 if (userInfo.id == userHandle.getIdentifier()) {
4882                     return true;
4883                 }
4884             }
4885         }
4886         return false;
4887     }
4888 
4889     /**
4890      * Kill the given PIDs, but the killing will be delayed until the device is idle
4891      * and the given process is imperceptible.
4892      *
4893      * <p>You must hold the permission
4894      * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
4895      * call this method.
4896      * </p>
4897      *
4898      * @param pids The list of the pids to be killed
4899      * @pram reason The reason of the kill
4900      *
4901      * @hide
4902      */
4903     @SystemApi
4904     @RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
killProcessesWhenImperceptible(@onNull int[] pids, @NonNull String reason)4905     public void killProcessesWhenImperceptible(@NonNull int[] pids, @NonNull String reason) {
4906         try {
4907             getService().killProcessesWhenImperceptible(pids, reason);
4908         } catch (RemoteException e) {
4909             throw e.rethrowFromSystemServer();
4910         }
4911     }
4912 
4913     /** @hide */
isProcStateConsideredInteraction(@rocessState int procState)4914     public static boolean isProcStateConsideredInteraction(@ProcessState int procState) {
4915         return (procState <= PROCESS_STATE_TOP || procState == PROCESS_STATE_BOUND_TOP);
4916     }
4917 
4918     /** @hide */
procStateToString(int procState)4919     public static String procStateToString(int procState) {
4920         final String procStateStr;
4921         switch (procState) {
4922             case ActivityManager.PROCESS_STATE_PERSISTENT:
4923                 procStateStr = "PER ";
4924                 break;
4925             case ActivityManager.PROCESS_STATE_PERSISTENT_UI:
4926                 procStateStr = "PERU";
4927                 break;
4928             case ActivityManager.PROCESS_STATE_TOP:
4929                 procStateStr = "TOP ";
4930                 break;
4931             case ActivityManager.PROCESS_STATE_BOUND_TOP:
4932                 procStateStr = "BTOP";
4933                 break;
4934             case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE:
4935                 procStateStr = "FGS ";
4936                 break;
4937             case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
4938                 procStateStr = "BFGS";
4939                 break;
4940             case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND:
4941                 procStateStr = "IMPF";
4942                 break;
4943             case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND:
4944                 procStateStr = "IMPB";
4945                 break;
4946             case ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND:
4947                 procStateStr = "TRNB";
4948                 break;
4949             case ActivityManager.PROCESS_STATE_BACKUP:
4950                 procStateStr = "BKUP";
4951                 break;
4952             case ActivityManager.PROCESS_STATE_SERVICE:
4953                 procStateStr = "SVC ";
4954                 break;
4955             case ActivityManager.PROCESS_STATE_RECEIVER:
4956                 procStateStr = "RCVR";
4957                 break;
4958             case ActivityManager.PROCESS_STATE_TOP_SLEEPING:
4959                 procStateStr = "TPSL";
4960                 break;
4961             case ActivityManager.PROCESS_STATE_HEAVY_WEIGHT:
4962                 procStateStr = "HVY ";
4963                 break;
4964             case ActivityManager.PROCESS_STATE_HOME:
4965                 procStateStr = "HOME";
4966                 break;
4967             case ActivityManager.PROCESS_STATE_LAST_ACTIVITY:
4968                 procStateStr = "LAST";
4969                 break;
4970             case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY:
4971                 procStateStr = "CAC ";
4972                 break;
4973             case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
4974                 procStateStr = "CACC";
4975                 break;
4976             case ActivityManager.PROCESS_STATE_CACHED_RECENT:
4977                 procStateStr = "CRE ";
4978                 break;
4979             case ActivityManager.PROCESS_STATE_CACHED_EMPTY:
4980                 procStateStr = "CEM ";
4981                 break;
4982             case ActivityManager.PROCESS_STATE_NONEXISTENT:
4983                 procStateStr = "NONE";
4984                 break;
4985             default:
4986                 procStateStr = "??";
4987                 break;
4988         }
4989         return procStateStr;
4990     }
4991 
4992     /**
4993      * The AppTask allows you to manage your own application's tasks.
4994      * See {@link android.app.ActivityManager#getAppTasks()}
4995      */
4996     public static class AppTask {
4997         private IAppTask mAppTaskImpl;
4998 
4999         /** @hide */
AppTask(IAppTask task)5000         public AppTask(IAppTask task) {
5001             mAppTaskImpl = task;
5002         }
5003 
5004         /**
5005          * Finishes all activities in this task and removes it from the recent tasks list.
5006          */
finishAndRemoveTask()5007         public void finishAndRemoveTask() {
5008             try {
5009                 mAppTaskImpl.finishAndRemoveTask();
5010             } catch (RemoteException e) {
5011                 throw e.rethrowFromSystemServer();
5012             }
5013         }
5014 
5015         /**
5016          * Get the RecentTaskInfo associated with this task.
5017          *
5018          * @return The RecentTaskInfo for this task, or null if the task no longer exists.
5019          */
getTaskInfo()5020         public RecentTaskInfo getTaskInfo() {
5021             try {
5022                 return mAppTaskImpl.getTaskInfo();
5023             } catch (RemoteException e) {
5024                 throw e.rethrowFromSystemServer();
5025             }
5026         }
5027 
5028         /**
5029          * Bring this task to the foreground.  If it contains activities, they will be
5030          * brought to the foreground with it and their instances re-created if needed.
5031          * If it doesn't contain activities, the root activity of the task will be
5032          * re-launched.
5033          */
moveToFront()5034         public void moveToFront() {
5035             try {
5036                 ActivityThread thread = ActivityThread.currentActivityThread();
5037                 IApplicationThread appThread = thread.getApplicationThread();
5038                 String packageName = ActivityThread.currentPackageName();
5039                 mAppTaskImpl.moveToFront(appThread, packageName);
5040             } catch (RemoteException e) {
5041                 throw e.rethrowFromSystemServer();
5042             }
5043         }
5044 
5045         /**
5046          * Start an activity in this task.  Brings the task to the foreground.  If this task
5047          * is not currently active (that is, its id < 0), then a new activity for the given
5048          * Intent will be launched as the root of the task and the task brought to the
5049          * foreground.  Otherwise, if this task is currently active and the Intent does not specify
5050          * an activity to launch in a new task, then a new activity for the given Intent will
5051          * be launched on top of the task and the task brought to the foreground.  If this
5052          * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
5053          * or would otherwise be launched in to a new task, then the activity not launched but
5054          * this task be brought to the foreground and a new intent delivered to the top
5055          * activity if appropriate.
5056          *
5057          * <p>In other words, you generally want to use an Intent here that does not specify
5058          * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
5059          * and let the system do the right thing.</p>
5060          *
5061          * @param intent The Intent describing the new activity to be launched on the task.
5062          * @param options Optional launch options.
5063          *
5064          * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
5065          */
startActivity(Context context, Intent intent, Bundle options)5066         public void startActivity(Context context, Intent intent, Bundle options) {
5067             ActivityThread thread = ActivityThread.currentActivityThread();
5068             thread.getInstrumentation().execStartActivityFromAppTask(context,
5069                     thread.getApplicationThread(), mAppTaskImpl, intent, options);
5070         }
5071 
5072         /**
5073          * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
5074          * Intent of this AppTask.
5075          *
5076          * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
5077          * be set; otherwise, it will be cleared.
5078          */
setExcludeFromRecents(boolean exclude)5079         public void setExcludeFromRecents(boolean exclude) {
5080             try {
5081                 mAppTaskImpl.setExcludeFromRecents(exclude);
5082             } catch (RemoteException e) {
5083                 throw e.rethrowFromSystemServer();
5084             }
5085         }
5086     }
5087 
5088     /**
5089      * Get packages of bugreport-allowlisted apps to handle a bug report.
5090      *
5091      * @return packages of bugreport-allowlisted apps to handle a bug report.
5092      * @hide
5093      */
getBugreportWhitelistedPackages()5094     public List<String> getBugreportWhitelistedPackages() {
5095         try {
5096             return getService().getBugreportWhitelistedPackages();
5097         } catch (RemoteException e) {
5098             throw e.rethrowFromSystemServer();
5099         }
5100     }
5101 
5102     /**
5103      * Method for the app to tell system that it's wedged and would like to trigger an ANR.
5104      *
5105      * @param reason The description of that what happened
5106      */
appNotResponding(@onNull final String reason)5107     public void appNotResponding(@NonNull final String reason) {
5108         try {
5109             getService().appNotResponding(reason);
5110         } catch (RemoteException e) {
5111             throw e.rethrowFromSystemServer();
5112         }
5113     }
5114 
5115     /**
5116      * Register to be notified when the visibility of the home screen changes.
5117      *
5118      * @param executor The executor on which the listener should be called.
5119      * @param listener The listener that is called when home visibility changes.
5120      * @hide
5121      */
5122     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5123     @TestApi
5124     @RequiresPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
addHomeVisibilityListener(@onNull Executor executor, @NonNull HomeVisibilityListener listener)5125     public void addHomeVisibilityListener(@NonNull Executor executor,
5126             @NonNull HomeVisibilityListener listener) {
5127         Preconditions.checkNotNull(listener);
5128         Preconditions.checkNotNull(executor);
5129         try {
5130             listener.init(mContext, executor);
5131             getService().registerProcessObserver(listener.mObserver);
5132             // Notify upon first registration.
5133             executor.execute(() ->
5134                     listener.onHomeVisibilityChanged(listener.mIsHomeActivityVisible));
5135         } catch (RemoteException e) {
5136             throw e.rethrowFromSystemServer();
5137         }
5138     }
5139 
5140     /**
5141      * Removes a listener that was previously added with {@link #addHomeVisibilityListener}.
5142      *
5143      * @param listener The listener that was previously added.
5144      * @hide
5145      */
5146     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5147     @TestApi
5148     @RequiresPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
removeHomeVisibilityListener(@onNull HomeVisibilityListener listener)5149     public void removeHomeVisibilityListener(@NonNull HomeVisibilityListener listener) {
5150         Preconditions.checkNotNull(listener);
5151         try {
5152             getService().unregisterProcessObserver(listener.mObserver);
5153         } catch (RemoteException e) {
5154             throw e.rethrowFromSystemServer();
5155         }
5156     }
5157 
5158     /**
5159      * Resets the state of the {@link com.android.server.am.AppErrors} instance.
5160      * This is intended for use with CTS only.
5161      * @hide
5162      */
5163     @TestApi
5164     @RequiresPermission(Manifest.permission.RESET_APP_ERRORS)
resetAppErrors()5165     public void resetAppErrors() {
5166         try {
5167             getService().resetAppErrors();
5168         } catch (RemoteException e) {
5169             throw e.rethrowFromSystemServer();
5170         }
5171     }
5172 
5173     /**
5174      * Holds the AM lock for the specified amount of milliseconds.
5175      * This is intended for use by the tests that need to imitate lock contention.
5176      * The token should be obtained by
5177      * {@link android.content.pm.PackageManager#getHoldLockToken()}.
5178      * @hide
5179      */
5180     @TestApi
holdLock(IBinder token, int durationMs)5181     public void holdLock(IBinder token, int durationMs) {
5182         try {
5183             getService().holdLock(token, durationMs);
5184         } catch (RemoteException e) {
5185             throw e.rethrowFromSystemServer();
5186         }
5187     }
5188 
5189     /**
5190      * Blocks until all broadcast queues become idle.
5191      *
5192      * @hide
5193      */
5194     @TestApi
5195     @RequiresPermission(android.Manifest.permission.DUMP)
waitForBroadcastIdle()5196     public void waitForBroadcastIdle() {
5197         try {
5198             getService().waitForBroadcastIdle();
5199         } catch (RemoteException e) {
5200             e.rethrowFromSystemServer();
5201         }
5202     }
5203 
5204     /**
5205      * @return The reason code of whether or not the given UID should be exempted from background
5206      * restrictions here.
5207      *
5208      * <p>
5209      * Note: Call it with caution as it'll try to acquire locks in other services.
5210      * </p>
5211      *
5212      * @hide
5213      */
5214     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
5215     @ReasonCode
getBackgroundRestrictionExemptionReason(int uid)5216     public int getBackgroundRestrictionExemptionReason(int uid) {
5217         try {
5218             return getService().getBackgroundRestrictionExemptionReason(uid);
5219         } catch (RemoteException e) {
5220             e.rethrowFromSystemServer();
5221         }
5222         return PowerExemptionManager.REASON_DENIED;
5223     }
5224 
5225     /**
5226      * A subset of immutable pending intent information suitable for caching on the client side.
5227      *
5228      * @hide
5229      */
5230     public static final class PendingIntentInfo implements Parcelable {
5231 
5232         @Nullable private final String mCreatorPackage;
5233         private final int mCreatorUid;
5234         private final boolean mImmutable;
5235         private final int mIntentSenderType;
5236 
PendingIntentInfo(@ullable String creatorPackage, int creatorUid, boolean immutable, int intentSenderType)5237         public PendingIntentInfo(@Nullable String creatorPackage, int creatorUid, boolean immutable,
5238                 int intentSenderType) {
5239             mCreatorPackage = creatorPackage;
5240             mCreatorUid = creatorUid;
5241             mImmutable = immutable;
5242             mIntentSenderType = intentSenderType;
5243         }
5244 
5245         @Nullable
getCreatorPackage()5246         public String getCreatorPackage() {
5247             return mCreatorPackage;
5248         }
5249 
getCreatorUid()5250         public int getCreatorUid() {
5251             return mCreatorUid;
5252         }
5253 
isImmutable()5254         public boolean isImmutable() {
5255             return mImmutable;
5256         }
5257 
getIntentSenderType()5258         public int getIntentSenderType() {
5259             return mIntentSenderType;
5260         }
5261 
5262         @Override
describeContents()5263         public int describeContents() {
5264             return 0;
5265         }
5266 
5267         @Override
writeToParcel(@onNull Parcel parcel, int flags)5268         public void writeToParcel(@NonNull Parcel parcel, int flags) {
5269             parcel.writeString(mCreatorPackage);
5270             parcel.writeInt(mCreatorUid);
5271             parcel.writeBoolean(mImmutable);
5272             parcel.writeInt(mIntentSenderType);
5273         }
5274 
5275         public static final @NonNull Creator<PendingIntentInfo> CREATOR =
5276                 new Creator<PendingIntentInfo>() {
5277                     @Override
5278                     public PendingIntentInfo createFromParcel(Parcel in) {
5279                         return new PendingIntentInfo(
5280                                 /* creatorPackage= */ in.readString(),
5281                                 /* creatorUid= */ in.readInt(),
5282                                 /* immutable= */ in.readBoolean(),
5283                                 /* intentSenderType= */ in.readInt());
5284                     }
5285 
5286                     @Override
5287                     public PendingIntentInfo[] newArray(int size) {
5288                         return new PendingIntentInfo[size];
5289                     }
5290                 };
5291     }
5292 }
5293