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