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