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