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