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