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