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