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