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.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.SystemApi;
22 import android.graphics.Canvas;
23 import android.graphics.Matrix;
24 import android.graphics.Point;
25 import android.os.BatteryStats;
26 import android.os.IBinder;
27 import android.os.ParcelFileDescriptor;
28 
29 import com.android.internal.app.ProcessStats;
30 import com.android.internal.os.TransferPipe;
31 import com.android.internal.util.FastPrintWriter;
32 
33 import android.content.ComponentName;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.pm.ApplicationInfo;
37 import android.content.pm.ConfigurationInfo;
38 import android.content.pm.IPackageDataObserver;
39 import android.content.pm.PackageManager;
40 import android.content.pm.UserInfo;
41 import android.content.res.Resources;
42 import android.graphics.Bitmap;
43 import android.graphics.Color;
44 import android.graphics.Rect;
45 import android.os.Bundle;
46 import android.os.Debug;
47 import android.os.Handler;
48 import android.os.Parcel;
49 import android.os.Parcelable;
50 import android.os.Process;
51 import android.os.RemoteException;
52 import android.os.ServiceManager;
53 import android.os.SystemProperties;
54 import android.os.UserHandle;
55 import android.text.TextUtils;
56 import android.util.DisplayMetrics;
57 import android.util.Size;
58 import android.util.Slog;
59 import org.xmlpull.v1.XmlSerializer;
60 
61 import java.io.FileDescriptor;
62 import java.io.FileOutputStream;
63 import java.io.IOException;
64 import java.io.PrintWriter;
65 import java.util.ArrayList;
66 import java.util.List;
67 
68 /**
69  * Interact with the overall activities running in the system.
70  */
71 public class ActivityManager {
72     private static String TAG = "ActivityManager";
73     private static boolean localLOGV = false;
74 
75     private static int gMaxRecentTasks = -1;
76 
77     private final Context mContext;
78     private final Handler mHandler;
79 
80     /**
81      * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
82      * &lt;meta-data>}</a> name for a 'home' Activity that declares a package that is to be
83      * uninstalled in lieu of the declaring one.  The package named here must be
84      * signed with the same certificate as the one declaring the {@code &lt;meta-data>}.
85      */
86     public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
87 
88     /**
89      * Result for IActivityManager.startActivity: trying to start an activity under voice
90      * control when that activity does not support the VOICE category.
91      * @hide
92      */
93     public static final int START_NOT_VOICE_COMPATIBLE = -7;
94 
95     /**
96      * Result for IActivityManager.startActivity: an error where the
97      * start had to be canceled.
98      * @hide
99      */
100     public static final int START_CANCELED = -6;
101 
102     /**
103      * Result for IActivityManager.startActivity: an error where the
104      * thing being started is not an activity.
105      * @hide
106      */
107     public static final int START_NOT_ACTIVITY = -5;
108 
109     /**
110      * Result for IActivityManager.startActivity: an error where the
111      * caller does not have permission to start the activity.
112      * @hide
113      */
114     public static final int START_PERMISSION_DENIED = -4;
115 
116     /**
117      * Result for IActivityManager.startActivity: an error where the
118      * caller has requested both to forward a result and to receive
119      * a result.
120      * @hide
121      */
122     public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
123 
124     /**
125      * Result for IActivityManager.startActivity: an error where the
126      * requested class is not found.
127      * @hide
128      */
129     public static final int START_CLASS_NOT_FOUND = -2;
130 
131     /**
132      * Result for IActivityManager.startActivity: an error where the
133      * given Intent could not be resolved to an activity.
134      * @hide
135      */
136     public static final int START_INTENT_NOT_RESOLVED = -1;
137 
138     /**
139      * Result for IActivityManaqer.startActivity: the activity was started
140      * successfully as normal.
141      * @hide
142      */
143     public static final int START_SUCCESS = 0;
144 
145     /**
146      * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
147      * be executed if it is the recipient, and that is indeed the case.
148      * @hide
149      */
150     public static final int START_RETURN_INTENT_TO_CALLER = 1;
151 
152     /**
153      * Result for IActivityManaqer.startActivity: activity wasn't really started, but
154      * a task was simply brought to the foreground.
155      * @hide
156      */
157     public static final int START_TASK_TO_FRONT = 2;
158 
159     /**
160      * Result for IActivityManaqer.startActivity: activity wasn't really started, but
161      * the given Intent was given to the existing top activity.
162      * @hide
163      */
164     public static final int START_DELIVERED_TO_TOP = 3;
165 
166     /**
167      * Result for IActivityManaqer.startActivity: request was canceled because
168      * app switches are temporarily canceled to ensure the user's last request
169      * (such as pressing home) is performed.
170      * @hide
171      */
172     public static final int START_SWITCHES_CANCELED = 4;
173 
174     /**
175      * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
176      * while in Lock Task Mode.
177      * @hide
178      */
179     public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION = 5;
180 
181     /**
182      * Flag for IActivityManaqer.startActivity: do special start mode where
183      * a new activity is launched only if it is needed.
184      * @hide
185      */
186     public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
187 
188     /**
189      * Flag for IActivityManaqer.startActivity: launch the app for
190      * debugging.
191      * @hide
192      */
193     public static final int START_FLAG_DEBUG = 1<<1;
194 
195     /**
196      * Flag for IActivityManaqer.startActivity: launch the app for
197      * OpenGL tracing.
198      * @hide
199      */
200     public static final int START_FLAG_OPENGL_TRACES = 1<<2;
201 
202     /**
203      * Result for IActivityManaqer.broadcastIntent: success!
204      * @hide
205      */
206     public static final int BROADCAST_SUCCESS = 0;
207 
208     /**
209      * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
210      * a sticky intent without appropriate permission.
211      * @hide
212      */
213     public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
214 
215     /**
216      * Result for IActivityManager.broadcastIntent: trying to send a broadcast
217      * to a stopped user. Fail.
218      * @hide
219      */
220     public static final int BROADCAST_FAILED_USER_STOPPED = -2;
221 
222     /**
223      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
224      * for a sendBroadcast operation.
225      * @hide
226      */
227     public static final int INTENT_SENDER_BROADCAST = 1;
228 
229     /**
230      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
231      * for a startActivity operation.
232      * @hide
233      */
234     public static final int INTENT_SENDER_ACTIVITY = 2;
235 
236     /**
237      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
238      * for an activity result operation.
239      * @hide
240      */
241     public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
242 
243     /**
244      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
245      * for a startService operation.
246      * @hide
247      */
248     public static final int INTENT_SENDER_SERVICE = 4;
249 
250     /** @hide User operation call: success! */
251     public static final int USER_OP_SUCCESS = 0;
252 
253     /** @hide User operation call: given user id is not known. */
254     public static final int USER_OP_UNKNOWN_USER = -1;
255 
256     /** @hide User operation call: given user id is the current user, can't be stopped. */
257     public static final int USER_OP_IS_CURRENT = -2;
258 
259     /** @hide Process is a persistent system process. */
260     public static final int PROCESS_STATE_PERSISTENT = 0;
261 
262     /** @hide Process is a persistent system process and is doing UI. */
263     public static final int PROCESS_STATE_PERSISTENT_UI = 1;
264 
265     /** @hide Process is hosting the current top activities.  Note that this covers
266      * all activities that are visible to the user. */
267     public static final int PROCESS_STATE_TOP = 2;
268 
269     /** @hide Process is important to the user, and something they are aware of. */
270     public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 3;
271 
272     /** @hide Process is important to the user, but not something they are aware of. */
273     public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 4;
274 
275     /** @hide Process is in the background running a backup/restore operation. */
276     public static final int PROCESS_STATE_BACKUP = 5;
277 
278     /** @hide Process is in the background, but it can't restore its state so we want
279      * to try to avoid killing it. */
280     public static final int PROCESS_STATE_HEAVY_WEIGHT = 6;
281 
282     /** @hide Process is in the background running a service.  Unlike oom_adj, this level
283      * is used for both the normal running in background state and the executing
284      * operations state. */
285     public static final int PROCESS_STATE_SERVICE = 7;
286 
287     /** @hide Process is in the background running a receiver.   Note that from the
288      * perspective of oom_adj receivers run at a higher foreground level, but for our
289      * prioritization here that is not necessary and putting them below services means
290      * many fewer changes in some process states as they receive broadcasts. */
291     public static final int PROCESS_STATE_RECEIVER = 8;
292 
293     /** @hide Process is in the background but hosts the home activity. */
294     public static final int PROCESS_STATE_HOME = 9;
295 
296     /** @hide Process is in the background but hosts the last shown activity. */
297     public static final int PROCESS_STATE_LAST_ACTIVITY = 10;
298 
299     /** @hide Process is being cached for later use and contains activities. */
300     public static final int PROCESS_STATE_CACHED_ACTIVITY = 11;
301 
302     /** @hide Process is being cached for later use and is a client of another cached
303      * process that contains activities. */
304     public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 12;
305 
306     /** @hide Process is being cached for later use and is empty. */
307     public static final int PROCESS_STATE_CACHED_EMPTY = 13;
308 
309     Point mAppTaskThumbnailSize;
310 
ActivityManager(Context context, Handler handler)311     /*package*/ ActivityManager(Context context, Handler handler) {
312         mContext = context;
313         mHandler = handler;
314     }
315 
316     /**
317      * Screen compatibility mode: the application most always run in
318      * compatibility mode.
319      * @hide
320      */
321     public static final int COMPAT_MODE_ALWAYS = -1;
322 
323     /**
324      * Screen compatibility mode: the application can never run in
325      * compatibility mode.
326      * @hide
327      */
328     public static final int COMPAT_MODE_NEVER = -2;
329 
330     /**
331      * Screen compatibility mode: unknown.
332      * @hide
333      */
334     public static final int COMPAT_MODE_UNKNOWN = -3;
335 
336     /**
337      * Screen compatibility mode: the application currently has compatibility
338      * mode disabled.
339      * @hide
340      */
341     public static final int COMPAT_MODE_DISABLED = 0;
342 
343     /**
344      * Screen compatibility mode: the application currently has compatibility
345      * mode enabled.
346      * @hide
347      */
348     public static final int COMPAT_MODE_ENABLED = 1;
349 
350     /**
351      * Screen compatibility mode: request to toggle the application's
352      * compatibility mode.
353      * @hide
354      */
355     public static final int COMPAT_MODE_TOGGLE = 2;
356 
357     /** @hide */
getFrontActivityScreenCompatMode()358     public int getFrontActivityScreenCompatMode() {
359         try {
360             return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
361         } catch (RemoteException e) {
362             // System dead, we will be dead too soon!
363             return 0;
364         }
365     }
366 
367     /** @hide */
setFrontActivityScreenCompatMode(int mode)368     public void setFrontActivityScreenCompatMode(int mode) {
369         try {
370             ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
371         } catch (RemoteException e) {
372             // System dead, we will be dead too soon!
373         }
374     }
375 
376     /** @hide */
getPackageScreenCompatMode(String packageName)377     public int getPackageScreenCompatMode(String packageName) {
378         try {
379             return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
380         } catch (RemoteException e) {
381             // System dead, we will be dead too soon!
382             return 0;
383         }
384     }
385 
386     /** @hide */
setPackageScreenCompatMode(String packageName, int mode)387     public void setPackageScreenCompatMode(String packageName, int mode) {
388         try {
389             ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
390         } catch (RemoteException e) {
391             // System dead, we will be dead too soon!
392         }
393     }
394 
395     /** @hide */
getPackageAskScreenCompat(String packageName)396     public boolean getPackageAskScreenCompat(String packageName) {
397         try {
398             return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
399         } catch (RemoteException e) {
400             // System dead, we will be dead too soon!
401             return false;
402         }
403     }
404 
405     /** @hide */
setPackageAskScreenCompat(String packageName, boolean ask)406     public void setPackageAskScreenCompat(String packageName, boolean ask) {
407         try {
408             ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
409         } catch (RemoteException e) {
410             // System dead, we will be dead too soon!
411         }
412     }
413 
414     /**
415      * Return the approximate per-application memory class of the current
416      * device.  This gives you an idea of how hard a memory limit you should
417      * impose on your application to let the overall system work best.  The
418      * returned value is in megabytes; the baseline Android memory class is
419      * 16 (which happens to be the Java heap limit of those devices); some
420      * device with more memory may return 24 or even higher numbers.
421      */
getMemoryClass()422     public int getMemoryClass() {
423         return staticGetMemoryClass();
424     }
425 
426     /** @hide */
staticGetMemoryClass()427     static public int staticGetMemoryClass() {
428         // Really brain dead right now -- just take this from the configured
429         // vm heap size, and assume it is in megabytes and thus ends with "m".
430         String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
431         if (vmHeapSize != null && !"".equals(vmHeapSize)) {
432             return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
433         }
434         return staticGetLargeMemoryClass();
435     }
436 
437     /**
438      * Return the approximate per-application memory class of the current
439      * device when an application is running with a large heap.  This is the
440      * space available for memory-intensive applications; most applications
441      * should not need this amount of memory, and should instead stay with the
442      * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
443      * This may be the same size as {@link #getMemoryClass()} on memory
444      * constrained devices, or it may be significantly larger on devices with
445      * a large amount of available RAM.
446      *
447      * <p>The is the size of the application's Dalvik heap if it has
448      * specified <code>android:largeHeap="true"</code> in its manifest.
449      */
getLargeMemoryClass()450     public int getLargeMemoryClass() {
451         return staticGetLargeMemoryClass();
452     }
453 
454     /** @hide */
staticGetLargeMemoryClass()455     static public int staticGetLargeMemoryClass() {
456         // Really brain dead right now -- just take this from the configured
457         // vm heap size, and assume it is in megabytes and thus ends with "m".
458         String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
459         return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1));
460     }
461 
462     /**
463      * Returns true if this is a low-RAM device.  Exactly whether a device is low-RAM
464      * is ultimately up to the device configuration, but currently it generally means
465      * something in the class of a 512MB device with about a 800x480 or less screen.
466      * This is mostly intended to be used by apps to determine whether they should turn
467      * off certain features that require more RAM.
468      */
isLowRamDevice()469     public boolean isLowRamDevice() {
470         return isLowRamDeviceStatic();
471     }
472 
473     /** @hide */
isLowRamDeviceStatic()474     public static boolean isLowRamDeviceStatic() {
475         return "true".equals(SystemProperties.get("ro.config.low_ram", "false"));
476     }
477 
478     /**
479      * Used by persistent processes to determine if they are running on a
480      * higher-end device so should be okay using hardware drawing acceleration
481      * (which tends to consume a lot more RAM).
482      * @hide
483      */
isHighEndGfx()484     static public boolean isHighEndGfx() {
485         return !isLowRamDeviceStatic() &&
486                 !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
487     }
488 
489     /**
490      * Return the maximum number of recents entries that we will maintain and show.
491      * @hide
492      */
getMaxRecentTasksStatic()493     static public int getMaxRecentTasksStatic() {
494         if (gMaxRecentTasks < 0) {
495             return gMaxRecentTasks = isLowRamDeviceStatic() ? 50 : 100;
496         }
497         return gMaxRecentTasks;
498     }
499 
500     /**
501      * Return the default limit on the number of recents that an app can make.
502      * @hide
503      */
getDefaultAppRecentsLimitStatic()504     static public int getDefaultAppRecentsLimitStatic() {
505         return getMaxRecentTasksStatic() / 6;
506     }
507 
508     /**
509      * Return the maximum limit on the number of recents that an app can make.
510      * @hide
511      */
getMaxAppRecentsLimitStatic()512     static public int getMaxAppRecentsLimitStatic() {
513         return getMaxRecentTasksStatic() / 2;
514     }
515 
516     /**
517      * Information you can set and retrieve about the current activity within the recent task list.
518      */
519     public static class TaskDescription implements Parcelable {
520         /** @hide */
521         public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_";
522         private static final String ATTR_TASKDESCRIPTIONLABEL =
523                 ATTR_TASKDESCRIPTION_PREFIX + "label";
524         private static final String ATTR_TASKDESCRIPTIONCOLOR =
525                 ATTR_TASKDESCRIPTION_PREFIX + "color";
526         private static final String ATTR_TASKDESCRIPTIONICONFILENAME =
527                 ATTR_TASKDESCRIPTION_PREFIX + "icon_filename";
528 
529         private String mLabel;
530         private Bitmap mIcon;
531         private String mIconFilename;
532         private int mColorPrimary;
533 
534         /**
535          * Creates the TaskDescription to the specified values.
536          *
537          * @param label A label and description of the current state of this task.
538          * @param icon An icon that represents the current state of this task.
539          * @param colorPrimary A color to override the theme's primary color.  This color must be opaque.
540          */
TaskDescription(String label, Bitmap icon, int colorPrimary)541         public TaskDescription(String label, Bitmap icon, int colorPrimary) {
542             if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
543                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
544             }
545 
546             mLabel = label;
547             mIcon = icon;
548             mColorPrimary = colorPrimary;
549         }
550 
551         /** @hide */
TaskDescription(String label, int colorPrimary, String iconFilename)552         public TaskDescription(String label, int colorPrimary, String iconFilename) {
553             this(label, null, colorPrimary);
554             mIconFilename = iconFilename;
555         }
556 
557         /**
558          * Creates the TaskDescription to the specified values.
559          *
560          * @param label A label and description of the current state of this activity.
561          * @param icon An icon that represents the current state of this activity.
562          */
TaskDescription(String label, Bitmap icon)563         public TaskDescription(String label, Bitmap icon) {
564             this(label, icon, 0);
565         }
566 
567         /**
568          * Creates the TaskDescription to the specified values.
569          *
570          * @param label A label and description of the current state of this activity.
571          */
TaskDescription(String label)572         public TaskDescription(String label) {
573             this(label, null, 0);
574         }
575 
576         /**
577          * Creates an empty TaskDescription.
578          */
TaskDescription()579         public TaskDescription() {
580             this(null, null, 0);
581         }
582 
583         /**
584          * Creates a copy of another TaskDescription.
585          */
TaskDescription(TaskDescription td)586         public TaskDescription(TaskDescription td) {
587             mLabel = td.mLabel;
588             mIcon = td.mIcon;
589             mColorPrimary = td.mColorPrimary;
590             mIconFilename = td.mIconFilename;
591         }
592 
TaskDescription(Parcel source)593         private TaskDescription(Parcel source) {
594             readFromParcel(source);
595         }
596 
597         /**
598          * Sets the label for this task description.
599          * @hide
600          */
setLabel(String label)601         public void setLabel(String label) {
602             mLabel = label;
603         }
604 
605         /**
606          * Sets the primary color for this task description.
607          * @hide
608          */
setPrimaryColor(int primaryColor)609         public void setPrimaryColor(int primaryColor) {
610             // Ensure that the given color is valid
611             if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) {
612                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
613             }
614             mColorPrimary = primaryColor;
615         }
616 
617         /**
618          * Sets the icon for this task description.
619          * @hide
620          */
setIcon(Bitmap icon)621         public void setIcon(Bitmap icon) {
622             mIcon = icon;
623         }
624 
625         /**
626          * Moves the icon bitmap reference from an actual Bitmap to a file containing the
627          * bitmap.
628          * @hide
629          */
setIconFilename(String iconFilename)630         public void setIconFilename(String iconFilename) {
631             mIconFilename = iconFilename;
632             mIcon = null;
633         }
634 
635         /**
636          * @return The label and description of the current state of this task.
637          */
getLabel()638         public String getLabel() {
639             return mLabel;
640         }
641 
642         /**
643          * @return The icon that represents the current state of this task.
644          */
getIcon()645         public Bitmap getIcon() {
646             if (mIcon != null) {
647                 return mIcon;
648             }
649             return loadTaskDescriptionIcon(mIconFilename);
650         }
651 
652         /** @hide */
getIconFilename()653         public String getIconFilename() {
654             return mIconFilename;
655         }
656 
657         /** @hide */
getInMemoryIcon()658         public Bitmap getInMemoryIcon() {
659             return mIcon;
660         }
661 
662         /** @hide */
loadTaskDescriptionIcon(String iconFilename)663         public static Bitmap loadTaskDescriptionIcon(String iconFilename) {
664             if (iconFilename != null) {
665                 try {
666                     return ActivityManagerNative.getDefault().
667                             getTaskDescriptionIcon(iconFilename);
668                 } catch (RemoteException e) {
669                 }
670             }
671             return null;
672         }
673 
674         /**
675          * @return The color override on the theme's primary color.
676          */
getPrimaryColor()677         public int getPrimaryColor() {
678             return mColorPrimary;
679         }
680 
681         /** @hide */
saveToXml(XmlSerializer out)682         public void saveToXml(XmlSerializer out) throws IOException {
683             if (mLabel != null) {
684                 out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel);
685             }
686             if (mColorPrimary != 0) {
687                 out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR, Integer.toHexString(mColorPrimary));
688             }
689             if (mIconFilename != null) {
690                 out.attribute(null, ATTR_TASKDESCRIPTIONICONFILENAME, mIconFilename);
691             }
692         }
693 
694         /** @hide */
restoreFromXml(String attrName, String attrValue)695         public void restoreFromXml(String attrName, String attrValue) {
696             if (ATTR_TASKDESCRIPTIONLABEL.equals(attrName)) {
697                 setLabel(attrValue);
698             } else if (ATTR_TASKDESCRIPTIONCOLOR.equals(attrName)) {
699                 setPrimaryColor((int) Long.parseLong(attrValue, 16));
700             } else if (ATTR_TASKDESCRIPTIONICONFILENAME.equals(attrName)) {
701                 setIconFilename(attrValue);
702             }
703         }
704 
705         @Override
describeContents()706         public int describeContents() {
707             return 0;
708         }
709 
710         @Override
writeToParcel(Parcel dest, int flags)711         public void writeToParcel(Parcel dest, int flags) {
712             if (mLabel == null) {
713                 dest.writeInt(0);
714             } else {
715                 dest.writeInt(1);
716                 dest.writeString(mLabel);
717             }
718             if (mIcon == null) {
719                 dest.writeInt(0);
720             } else {
721                 dest.writeInt(1);
722                 mIcon.writeToParcel(dest, 0);
723             }
724             dest.writeInt(mColorPrimary);
725             if (mIconFilename == null) {
726                 dest.writeInt(0);
727             } else {
728                 dest.writeInt(1);
729                 dest.writeString(mIconFilename);
730             }
731         }
732 
readFromParcel(Parcel source)733         public void readFromParcel(Parcel source) {
734             mLabel = source.readInt() > 0 ? source.readString() : null;
735             mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null;
736             mColorPrimary = source.readInt();
737             mIconFilename = source.readInt() > 0 ? source.readString() : null;
738         }
739 
740         public static final Creator<TaskDescription> CREATOR
741                 = new Creator<TaskDescription>() {
742             public TaskDescription createFromParcel(Parcel source) {
743                 return new TaskDescription(source);
744             }
745             public TaskDescription[] newArray(int size) {
746                 return new TaskDescription[size];
747             }
748         };
749 
750         @Override
toString()751         public String toString() {
752             return "TaskDescription Label: " + mLabel + " Icon: " + mIcon +
753                     " colorPrimary: " + mColorPrimary;
754         }
755     }
756 
757     /**
758      * Information you can retrieve about tasks that the user has most recently
759      * started or visited.
760      */
761     public static class RecentTaskInfo implements Parcelable {
762         /**
763          * If this task is currently running, this is the identifier for it.
764          * If it is not running, this will be -1.
765          */
766         public int id;
767 
768         /**
769          * The true identifier of this task, valid even if it is not running.
770          */
771         public int persistentId;
772 
773         /**
774          * The original Intent used to launch the task.  You can use this
775          * Intent to re-launch the task (if it is no longer running) or bring
776          * the current task to the front.
777          */
778         public Intent baseIntent;
779 
780         /**
781          * If this task was started from an alias, this is the actual
782          * activity component that was initially started; the component of
783          * the baseIntent in this case is the name of the actual activity
784          * implementation that the alias referred to.  Otherwise, this is null.
785          */
786         public ComponentName origActivity;
787 
788         /**
789          * Description of the task's last state.
790          */
791         public CharSequence description;
792 
793         /**
794          * The id of the ActivityStack this Task was on most recently.
795          * @hide
796          */
797         public int stackId;
798 
799         /**
800          * The id of the user the task was running as.
801          * @hide
802          */
803         public int userId;
804 
805         /**
806          * The first time this task was active.
807          * @hide
808          */
809         public long firstActiveTime;
810 
811         /**
812          * The last time this task was active.
813          * @hide
814          */
815         public long lastActiveTime;
816 
817         /**
818          * The recent activity values for the highest activity in the stack to have set the values.
819          * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
820          */
821         public TaskDescription taskDescription;
822 
823         /**
824          * Task affiliation for grouping with other tasks.
825          */
826         public int affiliatedTaskId;
827 
828         /**
829          * Task affiliation color of the source task with the affiliated task id.
830          *
831          * @hide
832          */
833         public int affiliatedTaskColor;
834 
RecentTaskInfo()835         public RecentTaskInfo() {
836         }
837 
838         @Override
describeContents()839         public int describeContents() {
840             return 0;
841         }
842 
843         @Override
writeToParcel(Parcel dest, int flags)844         public void writeToParcel(Parcel dest, int flags) {
845             dest.writeInt(id);
846             dest.writeInt(persistentId);
847             if (baseIntent != null) {
848                 dest.writeInt(1);
849                 baseIntent.writeToParcel(dest, 0);
850             } else {
851                 dest.writeInt(0);
852             }
853             ComponentName.writeToParcel(origActivity, dest);
854             TextUtils.writeToParcel(description, dest,
855                     Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
856             if (taskDescription != null) {
857                 dest.writeInt(1);
858                 taskDescription.writeToParcel(dest, 0);
859             } else {
860                 dest.writeInt(0);
861             }
862             dest.writeInt(stackId);
863             dest.writeInt(userId);
864             dest.writeLong(firstActiveTime);
865             dest.writeLong(lastActiveTime);
866             dest.writeInt(affiliatedTaskId);
867             dest.writeInt(affiliatedTaskColor);
868         }
869 
readFromParcel(Parcel source)870         public void readFromParcel(Parcel source) {
871             id = source.readInt();
872             persistentId = source.readInt();
873             baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
874             origActivity = ComponentName.readFromParcel(source);
875             description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
876             taskDescription = source.readInt() > 0 ?
877                     TaskDescription.CREATOR.createFromParcel(source) : null;
878             stackId = source.readInt();
879             userId = source.readInt();
880             firstActiveTime = source.readLong();
881             lastActiveTime = source.readLong();
882             affiliatedTaskId = source.readInt();
883             affiliatedTaskColor = source.readInt();
884         }
885 
886         public static final Creator<RecentTaskInfo> CREATOR
887                 = new Creator<RecentTaskInfo>() {
888             public RecentTaskInfo createFromParcel(Parcel source) {
889                 return new RecentTaskInfo(source);
890             }
891             public RecentTaskInfo[] newArray(int size) {
892                 return new RecentTaskInfo[size];
893             }
894         };
895 
RecentTaskInfo(Parcel source)896         private RecentTaskInfo(Parcel source) {
897             readFromParcel(source);
898         }
899     }
900 
901     /**
902      * Flag for use with {@link #getRecentTasks}: return all tasks, even those
903      * that have set their
904      * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
905      */
906     public static final int RECENT_WITH_EXCLUDED = 0x0001;
907 
908     /**
909      * Provides a list that does not contain any
910      * recent tasks that currently are not available to the user.
911      */
912     public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
913 
914     /**
915      * Provides a list that contains recent tasks for all
916      * profiles of a user.
917      * @hide
918      */
919     public static final int RECENT_INCLUDE_PROFILES = 0x0004;
920 
921     /**
922      * Ignores all tasks that are on the home stack.
923      * @hide
924      */
925     public static final int RECENT_IGNORE_HOME_STACK_TASKS = 0x0008;
926 
927     /**
928      * <p></p>Return a list of the tasks that the user has recently launched, with
929      * the most recent being first and older ones after in order.
930      *
931      * <p><b>Note: this method is only intended for debugging and presenting
932      * task management user interfaces</b>.  This should never be used for
933      * core logic in an application, such as deciding between different
934      * behaviors based on the information found here.  Such uses are
935      * <em>not</em> supported, and will likely break in the future.  For
936      * example, if multiple applications can be actively running at the
937      * same time, assumptions made about the meaning of the data here for
938      * purposes of control flow will be incorrect.</p>
939      *
940      * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
941      * no longer available to third party applications: the introduction of
942      * document-centric recents means
943      * it can leak personal information to the caller.  For backwards compatibility,
944      * it will still return a small subset of its data: at least the caller's
945      * own tasks (though see {@link #getAppTasks()} for the correct supported
946      * way to retrieve that information), and possibly some other tasks
947      * such as home that are known to not be sensitive.
948      *
949      * @param maxNum The maximum number of entries to return in the list.  The
950      * actual number returned may be smaller, depending on how many tasks the
951      * user has started and the maximum number the system can remember.
952      * @param flags Information about what to return.  May be any combination
953      * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
954      *
955      * @return Returns a list of RecentTaskInfo records describing each of
956      * the recent tasks.
957      */
958     @Deprecated
getRecentTasks(int maxNum, int flags)959     public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
960             throws SecurityException {
961         try {
962             return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
963                     flags, UserHandle.myUserId());
964         } catch (RemoteException e) {
965             // System dead, we will be dead too soon!
966             return null;
967         }
968     }
969 
970     /**
971      * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
972      * specific user. It requires holding
973      * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
974      * @param maxNum The maximum number of entries to return in the list.  The
975      * actual number returned may be smaller, depending on how many tasks the
976      * user has started and the maximum number the system can remember.
977      * @param flags Information about what to return.  May be any combination
978      * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
979      *
980      * @return Returns a list of RecentTaskInfo records describing each of
981      * the recent tasks.
982      *
983      * @hide
984      */
getRecentTasksForUser(int maxNum, int flags, int userId)985     public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
986             throws SecurityException {
987         try {
988             return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
989                     flags, userId);
990         } catch (RemoteException e) {
991             // System dead, we will be dead too soon!
992             return null;
993         }
994     }
995 
996     /**
997      * Information you can retrieve about a particular task that is currently
998      * "running" in the system.  Note that a running task does not mean the
999      * given task actually has a process it is actively running in; it simply
1000      * means that the user has gone to it and never closed it, but currently
1001      * the system may have killed its process and is only holding on to its
1002      * last state in order to restart it when the user returns.
1003      */
1004     public static class RunningTaskInfo implements Parcelable {
1005         /**
1006          * A unique identifier for this task.
1007          */
1008         public int id;
1009 
1010         /**
1011          * The component launched as the first activity in the task.  This can
1012          * be considered the "application" of this task.
1013          */
1014         public ComponentName baseActivity;
1015 
1016         /**
1017          * The activity component at the top of the history stack of the task.
1018          * This is what the user is currently doing.
1019          */
1020         public ComponentName topActivity;
1021 
1022         /**
1023          * Thumbnail representation of the task's current state.  Currently
1024          * always null.
1025          */
1026         public Bitmap thumbnail;
1027 
1028         /**
1029          * Description of the task's current state.
1030          */
1031         public CharSequence description;
1032 
1033         /**
1034          * Number of activities in this task.
1035          */
1036         public int numActivities;
1037 
1038         /**
1039          * Number of activities that are currently running (not stopped
1040          * and persisted) in this task.
1041          */
1042         public int numRunning;
1043 
1044         /**
1045          * Last time task was run. For sorting.
1046          * @hide
1047          */
1048         public long lastActiveTime;
1049 
RunningTaskInfo()1050         public RunningTaskInfo() {
1051         }
1052 
describeContents()1053         public int describeContents() {
1054             return 0;
1055         }
1056 
writeToParcel(Parcel dest, int flags)1057         public void writeToParcel(Parcel dest, int flags) {
1058             dest.writeInt(id);
1059             ComponentName.writeToParcel(baseActivity, dest);
1060             ComponentName.writeToParcel(topActivity, dest);
1061             if (thumbnail != null) {
1062                 dest.writeInt(1);
1063                 thumbnail.writeToParcel(dest, 0);
1064             } else {
1065                 dest.writeInt(0);
1066             }
1067             TextUtils.writeToParcel(description, dest,
1068                     Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1069             dest.writeInt(numActivities);
1070             dest.writeInt(numRunning);
1071         }
1072 
readFromParcel(Parcel source)1073         public void readFromParcel(Parcel source) {
1074             id = source.readInt();
1075             baseActivity = ComponentName.readFromParcel(source);
1076             topActivity = ComponentName.readFromParcel(source);
1077             if (source.readInt() != 0) {
1078                 thumbnail = Bitmap.CREATOR.createFromParcel(source);
1079             } else {
1080                 thumbnail = null;
1081             }
1082             description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
1083             numActivities = source.readInt();
1084             numRunning = source.readInt();
1085         }
1086 
1087         public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
1088             public RunningTaskInfo createFromParcel(Parcel source) {
1089                 return new RunningTaskInfo(source);
1090             }
1091             public RunningTaskInfo[] newArray(int size) {
1092                 return new RunningTaskInfo[size];
1093             }
1094         };
1095 
RunningTaskInfo(Parcel source)1096         private RunningTaskInfo(Parcel source) {
1097             readFromParcel(source);
1098         }
1099     }
1100 
1101     /**
1102      * Get the list of tasks associated with the calling application.
1103      *
1104      * @return The list of tasks associated with the application making this call.
1105      * @throws SecurityException
1106      */
getAppTasks()1107     public List<ActivityManager.AppTask> getAppTasks() {
1108         ArrayList<AppTask> tasks = new ArrayList<AppTask>();
1109         List<IAppTask> appTasks;
1110         try {
1111             appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName());
1112         } catch (RemoteException e) {
1113             // System dead, we will be dead too soon!
1114             return null;
1115         }
1116         int numAppTasks = appTasks.size();
1117         for (int i = 0; i < numAppTasks; i++) {
1118             tasks.add(new AppTask(appTasks.get(i)));
1119         }
1120         return tasks;
1121     }
1122 
1123     /**
1124      * Return the current design dimensions for {@link AppTask} thumbnails, for use
1125      * with {@link #addAppTask}.
1126      */
getAppTaskThumbnailSize()1127     public Size getAppTaskThumbnailSize() {
1128         synchronized (this) {
1129             ensureAppTaskThumbnailSizeLocked();
1130             return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
1131         }
1132     }
1133 
ensureAppTaskThumbnailSizeLocked()1134     private void ensureAppTaskThumbnailSizeLocked() {
1135         if (mAppTaskThumbnailSize == null) {
1136             try {
1137                 mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize();
1138             } catch (RemoteException e) {
1139                 throw new IllegalStateException("System dead?", e);
1140             }
1141         }
1142     }
1143 
1144     /**
1145      * Add a new {@link AppTask} for the calling application.  This will create a new
1146      * recents entry that is added to the <b>end</b> of all existing recents.
1147      *
1148      * @param activity The activity that is adding the entry.   This is used to help determine
1149      * the context that the new recents entry will be in.
1150      * @param intent The Intent that describes the recents entry.  This is the same Intent that
1151      * you would have used to launch the activity for it.  In generally you will want to set
1152      * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
1153      * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
1154      * entry will exist without an activity, so it doesn't make sense to not retain it when
1155      * its activity disappears.  The given Intent here also must have an explicit ComponentName
1156      * set on it.
1157      * @param description Optional additional description information.
1158      * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
1159      * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
1160      * recreated in your process, probably in a way you don't like, before the recents entry
1161      * is added.
1162      *
1163      * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
1164      * most likely cause of failure is that there is no more room for more tasks for your app.
1165      */
addAppTask(@onNull Activity activity, @NonNull Intent intent, @Nullable TaskDescription description, @NonNull Bitmap thumbnail)1166     public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
1167             @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
1168         Point size;
1169         synchronized (this) {
1170             ensureAppTaskThumbnailSizeLocked();
1171             size = mAppTaskThumbnailSize;
1172         }
1173         final int tw = thumbnail.getWidth();
1174         final int th = thumbnail.getHeight();
1175         if (tw != size.x || th != size.y) {
1176             Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
1177 
1178             // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
1179             float scale;
1180             float dx = 0, dy = 0;
1181             if (tw * size.x > size.y * th) {
1182                 scale = (float) size.x / (float) th;
1183                 dx = (size.y - tw * scale) * 0.5f;
1184             } else {
1185                 scale = (float) size.y / (float) tw;
1186                 dy = (size.x - th * scale) * 0.5f;
1187             }
1188             Matrix matrix = new Matrix();
1189             matrix.setScale(scale, scale);
1190             matrix.postTranslate((int) (dx + 0.5f), 0);
1191 
1192             Canvas canvas = new Canvas(bm);
1193             canvas.drawBitmap(thumbnail, matrix, null);
1194             canvas.setBitmap(null);
1195 
1196             thumbnail = bm;
1197         }
1198         if (description == null) {
1199             description = new TaskDescription();
1200         }
1201         try {
1202             return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(),
1203                     intent, description, thumbnail);
1204         } catch (RemoteException e) {
1205             throw new IllegalStateException("System dead?", e);
1206         }
1207     }
1208 
1209     /**
1210      * Return a list of the tasks that are currently running, with
1211      * the most recent being first and older ones after in order.  Note that
1212      * "running" does not mean any of the task's code is currently loaded or
1213      * activity -- the task may have been frozen by the system, so that it
1214      * can be restarted in its previous state when next brought to the
1215      * foreground.
1216      *
1217      * <p><b>Note: this method is only intended for debugging and presenting
1218      * task management user interfaces</b>.  This should never be used for
1219      * core logic in an application, such as deciding between different
1220      * behaviors based on the information found here.  Such uses are
1221      * <em>not</em> supported, and will likely break in the future.  For
1222      * example, if multiple applications can be actively running at the
1223      * same time, assumptions made about the meaning of the data here for
1224      * purposes of control flow will be incorrect.</p>
1225      *
1226      * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
1227      * is no longer available to third party
1228      * applications: the introduction of document-centric recents means
1229      * it can leak person information to the caller.  For backwards compatibility,
1230      * it will still retu rn a small subset of its data: at least the caller's
1231      * own tasks, and possibly some other tasks
1232      * such as home that are known to not be sensitive.
1233      *
1234      * @param maxNum The maximum number of entries to return in the list.  The
1235      * actual number returned may be smaller, depending on how many tasks the
1236      * user has started.
1237      *
1238      * @return Returns a list of RunningTaskInfo records describing each of
1239      * the running tasks.
1240      */
1241     @Deprecated
getRunningTasks(int maxNum)1242     public List<RunningTaskInfo> getRunningTasks(int maxNum)
1243             throws SecurityException {
1244         try {
1245             return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1246         } catch (RemoteException e) {
1247             // System dead, we will be dead too soon!
1248             return null;
1249         }
1250     }
1251 
1252     /**
1253      * Completely remove the given task.
1254      *
1255      * @param taskId Identifier of the task to be removed.
1256      * @return Returns true if the given task was found and removed.
1257      *
1258      * @hide
1259      */
removeTask(int taskId)1260     public boolean removeTask(int taskId) throws SecurityException {
1261         try {
1262             return ActivityManagerNative.getDefault().removeTask(taskId);
1263         } catch (RemoteException e) {
1264             // System dead, we will be dead too soon!
1265             return false;
1266         }
1267     }
1268 
1269     /** @hide */
1270     public static class TaskThumbnail implements Parcelable {
1271         public Bitmap mainThumbnail;
1272         public ParcelFileDescriptor thumbnailFileDescriptor;
1273 
TaskThumbnail()1274         public TaskThumbnail() {
1275         }
1276 
describeContents()1277         public int describeContents() {
1278             if (thumbnailFileDescriptor != null) {
1279                 return thumbnailFileDescriptor.describeContents();
1280             }
1281             return 0;
1282         }
1283 
writeToParcel(Parcel dest, int flags)1284         public void writeToParcel(Parcel dest, int flags) {
1285             if (mainThumbnail != null) {
1286                 dest.writeInt(1);
1287                 mainThumbnail.writeToParcel(dest, flags);
1288             } else {
1289                 dest.writeInt(0);
1290             }
1291             if (thumbnailFileDescriptor != null) {
1292                 dest.writeInt(1);
1293                 thumbnailFileDescriptor.writeToParcel(dest, flags);
1294             } else {
1295                 dest.writeInt(0);
1296             }
1297         }
1298 
readFromParcel(Parcel source)1299         public void readFromParcel(Parcel source) {
1300             if (source.readInt() != 0) {
1301                 mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1302             } else {
1303                 mainThumbnail = null;
1304             }
1305             if (source.readInt() != 0) {
1306                 thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1307             } else {
1308                 thumbnailFileDescriptor = null;
1309             }
1310         }
1311 
1312         public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1313             public TaskThumbnail createFromParcel(Parcel source) {
1314                 return new TaskThumbnail(source);
1315             }
1316             public TaskThumbnail[] newArray(int size) {
1317                 return new TaskThumbnail[size];
1318             }
1319         };
1320 
TaskThumbnail(Parcel source)1321         private TaskThumbnail(Parcel source) {
1322             readFromParcel(source);
1323         }
1324     }
1325 
1326     /** @hide */
getTaskThumbnail(int id)1327     public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1328         try {
1329             return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1330         } catch (RemoteException e) {
1331             // System dead, we will be dead too soon!
1332             return null;
1333         }
1334     }
1335 
1336     /** @hide */
isInHomeStack(int taskId)1337     public boolean isInHomeStack(int taskId) {
1338         try {
1339             return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1340         } catch (RemoteException e) {
1341             // System dead, we will be dead too soon!
1342             return false;
1343         }
1344     }
1345 
1346     /**
1347      * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1348      * activity along with the task, so it is positioned immediately behind
1349      * the task.
1350      */
1351     public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1352 
1353     /**
1354      * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1355      * user-instigated action, so the current activity will not receive a
1356      * hint that the user is leaving.
1357      */
1358     public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1359 
1360     /**
1361      * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1362      * with a null options argument.
1363      *
1364      * @param taskId The identifier of the task to be moved, as found in
1365      * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1366      * @param flags Additional operational flags, 0 or more of
1367      * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1368      */
moveTaskToFront(int taskId, int flags)1369     public void moveTaskToFront(int taskId, int flags) {
1370         moveTaskToFront(taskId, flags, null);
1371     }
1372 
1373     /**
1374      * Ask that the task associated with a given task ID be moved to the
1375      * front of the stack, so it is now visible to the user.  Requires that
1376      * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1377      * or a SecurityException will be thrown.
1378      *
1379      * @param taskId The identifier of the task to be moved, as found in
1380      * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1381      * @param flags Additional operational flags, 0 or more of
1382      * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1383      * @param options Additional options for the operation, either null or
1384      * as per {@link Context#startActivity(Intent, android.os.Bundle)
1385      * Context.startActivity(Intent, Bundle)}.
1386      */
moveTaskToFront(int taskId, int flags, Bundle options)1387     public void moveTaskToFront(int taskId, int flags, Bundle options) {
1388         try {
1389             ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1390         } catch (RemoteException e) {
1391             // System dead, we will be dead too soon!
1392         }
1393     }
1394 
1395     /**
1396      * Information you can retrieve about a particular Service that is
1397      * currently running in the system.
1398      */
1399     public static class RunningServiceInfo implements Parcelable {
1400         /**
1401          * The service component.
1402          */
1403         public ComponentName service;
1404 
1405         /**
1406          * If non-zero, this is the process the service is running in.
1407          */
1408         public int pid;
1409 
1410         /**
1411          * The UID that owns this service.
1412          */
1413         public int uid;
1414 
1415         /**
1416          * The name of the process this service runs in.
1417          */
1418         public String process;
1419 
1420         /**
1421          * Set to true if the service has asked to run as a foreground process.
1422          */
1423         public boolean foreground;
1424 
1425         /**
1426          * The time when the service was first made active, either by someone
1427          * starting or binding to it.  This
1428          * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1429          */
1430         public long activeSince;
1431 
1432         /**
1433          * Set to true if this service has been explicitly started.
1434          */
1435         public boolean started;
1436 
1437         /**
1438          * Number of clients connected to the service.
1439          */
1440         public int clientCount;
1441 
1442         /**
1443          * Number of times the service's process has crashed while the service
1444          * is running.
1445          */
1446         public int crashCount;
1447 
1448         /**
1449          * The time when there was last activity in the service (either
1450          * explicit requests to start it or clients binding to it).  This
1451          * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1452          */
1453         public long lastActivityTime;
1454 
1455         /**
1456          * If non-zero, this service is not currently running, but scheduled to
1457          * restart at the given time.
1458          */
1459         public long restarting;
1460 
1461         /**
1462          * Bit for {@link #flags}: set if this service has been
1463          * explicitly started.
1464          */
1465         public static final int FLAG_STARTED = 1<<0;
1466 
1467         /**
1468          * Bit for {@link #flags}: set if the service has asked to
1469          * run as a foreground process.
1470          */
1471         public static final int FLAG_FOREGROUND = 1<<1;
1472 
1473         /**
1474          * Bit for {@link #flags): set if the service is running in a
1475          * core system process.
1476          */
1477         public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1478 
1479         /**
1480          * Bit for {@link #flags): set if the service is running in a
1481          * persistent process.
1482          */
1483         public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1484 
1485         /**
1486          * Running flags.
1487          */
1488         public int flags;
1489 
1490         /**
1491          * For special services that are bound to by system code, this is
1492          * the package that holds the binding.
1493          */
1494         public String clientPackage;
1495 
1496         /**
1497          * For special services that are bound to by system code, this is
1498          * a string resource providing a user-visible label for who the
1499          * client is.
1500          */
1501         public int clientLabel;
1502 
RunningServiceInfo()1503         public RunningServiceInfo() {
1504         }
1505 
describeContents()1506         public int describeContents() {
1507             return 0;
1508         }
1509 
writeToParcel(Parcel dest, int flags)1510         public void writeToParcel(Parcel dest, int flags) {
1511             ComponentName.writeToParcel(service, dest);
1512             dest.writeInt(pid);
1513             dest.writeInt(uid);
1514             dest.writeString(process);
1515             dest.writeInt(foreground ? 1 : 0);
1516             dest.writeLong(activeSince);
1517             dest.writeInt(started ? 1 : 0);
1518             dest.writeInt(clientCount);
1519             dest.writeInt(crashCount);
1520             dest.writeLong(lastActivityTime);
1521             dest.writeLong(restarting);
1522             dest.writeInt(this.flags);
1523             dest.writeString(clientPackage);
1524             dest.writeInt(clientLabel);
1525         }
1526 
readFromParcel(Parcel source)1527         public void readFromParcel(Parcel source) {
1528             service = ComponentName.readFromParcel(source);
1529             pid = source.readInt();
1530             uid = source.readInt();
1531             process = source.readString();
1532             foreground = source.readInt() != 0;
1533             activeSince = source.readLong();
1534             started = source.readInt() != 0;
1535             clientCount = source.readInt();
1536             crashCount = source.readInt();
1537             lastActivityTime = source.readLong();
1538             restarting = source.readLong();
1539             flags = source.readInt();
1540             clientPackage = source.readString();
1541             clientLabel = source.readInt();
1542         }
1543 
1544         public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1545             public RunningServiceInfo createFromParcel(Parcel source) {
1546                 return new RunningServiceInfo(source);
1547             }
1548             public RunningServiceInfo[] newArray(int size) {
1549                 return new RunningServiceInfo[size];
1550             }
1551         };
1552 
RunningServiceInfo(Parcel source)1553         private RunningServiceInfo(Parcel source) {
1554             readFromParcel(source);
1555         }
1556     }
1557 
1558     /**
1559      * Return a list of the services that are currently running.
1560      *
1561      * <p><b>Note: this method is only intended for debugging or implementing
1562      * service management type user interfaces.</b></p>
1563      *
1564      * @param maxNum The maximum number of entries to return in the list.  The
1565      * actual number returned may be smaller, depending on how many services
1566      * are running.
1567      *
1568      * @return Returns a list of RunningServiceInfo records describing each of
1569      * the running tasks.
1570      */
getRunningServices(int maxNum)1571     public List<RunningServiceInfo> getRunningServices(int maxNum)
1572             throws SecurityException {
1573         try {
1574             return ActivityManagerNative.getDefault()
1575                     .getServices(maxNum, 0);
1576         } catch (RemoteException e) {
1577             // System dead, we will be dead too soon!
1578             return null;
1579         }
1580     }
1581 
1582     /**
1583      * Returns a PendingIntent you can start to show a control panel for the
1584      * given running service.  If the service does not have a control panel,
1585      * null is returned.
1586      */
getRunningServiceControlPanel(ComponentName service)1587     public PendingIntent getRunningServiceControlPanel(ComponentName service)
1588             throws SecurityException {
1589         try {
1590             return ActivityManagerNative.getDefault()
1591                     .getRunningServiceControlPanel(service);
1592         } catch (RemoteException e) {
1593             // System dead, we will be dead too soon!
1594             return null;
1595         }
1596     }
1597 
1598     /**
1599      * Information you can retrieve about the available memory through
1600      * {@link ActivityManager#getMemoryInfo}.
1601      */
1602     public static class MemoryInfo implements Parcelable {
1603         /**
1604          * The available memory on the system.  This number should not
1605          * be considered absolute: due to the nature of the kernel, a significant
1606          * portion of this memory is actually in use and needed for the overall
1607          * system to run well.
1608          */
1609         public long availMem;
1610 
1611         /**
1612          * The total memory accessible by the kernel.  This is basically the
1613          * RAM size of the device, not including below-kernel fixed allocations
1614          * like DMA buffers, RAM for the baseband CPU, etc.
1615          */
1616         public long totalMem;
1617 
1618         /**
1619          * The threshold of {@link #availMem} at which we consider memory to be
1620          * low and start killing background services and other non-extraneous
1621          * processes.
1622          */
1623         public long threshold;
1624 
1625         /**
1626          * Set to true if the system considers itself to currently be in a low
1627          * memory situation.
1628          */
1629         public boolean lowMemory;
1630 
1631         /** @hide */
1632         public long hiddenAppThreshold;
1633         /** @hide */
1634         public long secondaryServerThreshold;
1635         /** @hide */
1636         public long visibleAppThreshold;
1637         /** @hide */
1638         public long foregroundAppThreshold;
1639 
MemoryInfo()1640         public MemoryInfo() {
1641         }
1642 
describeContents()1643         public int describeContents() {
1644             return 0;
1645         }
1646 
writeToParcel(Parcel dest, int flags)1647         public void writeToParcel(Parcel dest, int flags) {
1648             dest.writeLong(availMem);
1649             dest.writeLong(totalMem);
1650             dest.writeLong(threshold);
1651             dest.writeInt(lowMemory ? 1 : 0);
1652             dest.writeLong(hiddenAppThreshold);
1653             dest.writeLong(secondaryServerThreshold);
1654             dest.writeLong(visibleAppThreshold);
1655             dest.writeLong(foregroundAppThreshold);
1656         }
1657 
readFromParcel(Parcel source)1658         public void readFromParcel(Parcel source) {
1659             availMem = source.readLong();
1660             totalMem = source.readLong();
1661             threshold = source.readLong();
1662             lowMemory = source.readInt() != 0;
1663             hiddenAppThreshold = source.readLong();
1664             secondaryServerThreshold = source.readLong();
1665             visibleAppThreshold = source.readLong();
1666             foregroundAppThreshold = source.readLong();
1667         }
1668 
1669         public static final Creator<MemoryInfo> CREATOR
1670                 = new Creator<MemoryInfo>() {
1671             public MemoryInfo createFromParcel(Parcel source) {
1672                 return new MemoryInfo(source);
1673             }
1674             public MemoryInfo[] newArray(int size) {
1675                 return new MemoryInfo[size];
1676             }
1677         };
1678 
MemoryInfo(Parcel source)1679         private MemoryInfo(Parcel source) {
1680             readFromParcel(source);
1681         }
1682     }
1683 
1684     /**
1685      * Return general information about the memory state of the system.  This
1686      * can be used to help decide how to manage your own memory, though note
1687      * that polling is not recommended and
1688      * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1689      * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1690      * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1691      * level of your process as needed, which gives a better hint for how to
1692      * manage its memory.
1693      */
getMemoryInfo(MemoryInfo outInfo)1694     public void getMemoryInfo(MemoryInfo outInfo) {
1695         try {
1696             ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1697         } catch (RemoteException e) {
1698         }
1699     }
1700 
1701     /**
1702      * Information you can retrieve about an ActivityStack in the system.
1703      * @hide
1704      */
1705     public static class StackInfo implements Parcelable {
1706         public int stackId;
1707         public Rect bounds = new Rect();
1708         public int[] taskIds;
1709         public String[] taskNames;
1710         public int displayId;
1711 
1712         @Override
describeContents()1713         public int describeContents() {
1714             return 0;
1715         }
1716 
1717         @Override
writeToParcel(Parcel dest, int flags)1718         public void writeToParcel(Parcel dest, int flags) {
1719             dest.writeInt(stackId);
1720             dest.writeInt(bounds.left);
1721             dest.writeInt(bounds.top);
1722             dest.writeInt(bounds.right);
1723             dest.writeInt(bounds.bottom);
1724             dest.writeIntArray(taskIds);
1725             dest.writeStringArray(taskNames);
1726             dest.writeInt(displayId);
1727         }
1728 
readFromParcel(Parcel source)1729         public void readFromParcel(Parcel source) {
1730             stackId = source.readInt();
1731             bounds = new Rect(
1732                     source.readInt(), source.readInt(), source.readInt(), source.readInt());
1733             taskIds = source.createIntArray();
1734             taskNames = source.createStringArray();
1735             displayId = source.readInt();
1736         }
1737 
1738         public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1739             @Override
1740             public StackInfo createFromParcel(Parcel source) {
1741                 return new StackInfo(source);
1742             }
1743             @Override
1744             public StackInfo[] newArray(int size) {
1745                 return new StackInfo[size];
1746             }
1747         };
1748 
StackInfo()1749         public StackInfo() {
1750         }
1751 
StackInfo(Parcel source)1752         private StackInfo(Parcel source) {
1753             readFromParcel(source);
1754         }
1755 
toString(String prefix)1756         public String toString(String prefix) {
1757             StringBuilder sb = new StringBuilder(256);
1758             sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1759                     sb.append(" bounds="); sb.append(bounds.toShortString());
1760                     sb.append(" displayId="); sb.append(displayId);
1761                     sb.append("\n");
1762             prefix = prefix + "  ";
1763             for (int i = 0; i < taskIds.length; ++i) {
1764                 sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1765                         sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
1766             }
1767             return sb.toString();
1768         }
1769 
1770         @Override
toString()1771         public String toString() {
1772             return toString("");
1773         }
1774     }
1775 
1776     /**
1777      * @hide
1778      */
clearApplicationUserData(String packageName, IPackageDataObserver observer)1779     public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1780         try {
1781             return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1782                     observer, UserHandle.myUserId());
1783         } catch (RemoteException e) {
1784             return false;
1785         }
1786     }
1787 
1788     /**
1789      * Permits an application to erase its own data from disk.  This is equivalent to
1790      * the user choosing to clear the app's data from within the device settings UI.  It
1791      * erases all dynamic data associated with the app -- its private data and data in its
1792      * private area on external storage -- but does not remove the installed application
1793      * itself, nor any OBB files.
1794      *
1795      * @return {@code true} if the application successfully requested that the application's
1796      *     data be erased; {@code false} otherwise.
1797      */
clearApplicationUserData()1798     public boolean clearApplicationUserData() {
1799         return clearApplicationUserData(mContext.getPackageName(), null);
1800     }
1801 
1802     /**
1803      * Information you can retrieve about any processes that are in an error condition.
1804      */
1805     public static class ProcessErrorStateInfo implements Parcelable {
1806         /**
1807          * Condition codes
1808          */
1809         public static final int NO_ERROR = 0;
1810         public static final int CRASHED = 1;
1811         public static final int NOT_RESPONDING = 2;
1812 
1813         /**
1814          * The condition that the process is in.
1815          */
1816         public int condition;
1817 
1818         /**
1819          * The process name in which the crash or error occurred.
1820          */
1821         public String processName;
1822 
1823         /**
1824          * The pid of this process; 0 if none
1825          */
1826         public int pid;
1827 
1828         /**
1829          * The kernel user-ID that has been assigned to this process;
1830          * currently this is not a unique ID (multiple applications can have
1831          * the same uid).
1832          */
1833         public int uid;
1834 
1835         /**
1836          * The activity name associated with the error, if known.  May be null.
1837          */
1838         public String tag;
1839 
1840         /**
1841          * A short message describing the error condition.
1842          */
1843         public String shortMsg;
1844 
1845         /**
1846          * A long message describing the error condition.
1847          */
1848         public String longMsg;
1849 
1850         /**
1851          * The stack trace where the error originated.  May be null.
1852          */
1853         public String stackTrace;
1854 
1855         /**
1856          * to be deprecated: This value will always be null.
1857          */
1858         public byte[] crashData = null;
1859 
ProcessErrorStateInfo()1860         public ProcessErrorStateInfo() {
1861         }
1862 
1863         @Override
describeContents()1864         public int describeContents() {
1865             return 0;
1866         }
1867 
1868         @Override
writeToParcel(Parcel dest, int flags)1869         public void writeToParcel(Parcel dest, int flags) {
1870             dest.writeInt(condition);
1871             dest.writeString(processName);
1872             dest.writeInt(pid);
1873             dest.writeInt(uid);
1874             dest.writeString(tag);
1875             dest.writeString(shortMsg);
1876             dest.writeString(longMsg);
1877             dest.writeString(stackTrace);
1878         }
1879 
readFromParcel(Parcel source)1880         public void readFromParcel(Parcel source) {
1881             condition = source.readInt();
1882             processName = source.readString();
1883             pid = source.readInt();
1884             uid = source.readInt();
1885             tag = source.readString();
1886             shortMsg = source.readString();
1887             longMsg = source.readString();
1888             stackTrace = source.readString();
1889         }
1890 
1891         public static final Creator<ProcessErrorStateInfo> CREATOR =
1892                 new Creator<ProcessErrorStateInfo>() {
1893             public ProcessErrorStateInfo createFromParcel(Parcel source) {
1894                 return new ProcessErrorStateInfo(source);
1895             }
1896             public ProcessErrorStateInfo[] newArray(int size) {
1897                 return new ProcessErrorStateInfo[size];
1898             }
1899         };
1900 
ProcessErrorStateInfo(Parcel source)1901         private ProcessErrorStateInfo(Parcel source) {
1902             readFromParcel(source);
1903         }
1904     }
1905 
1906     /**
1907      * Returns a list of any processes that are currently in an error condition.  The result
1908      * will be null if all processes are running properly at this time.
1909      *
1910      * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1911      * current error conditions (it will not return an empty list).  This list ordering is not
1912      * specified.
1913      */
getProcessesInErrorState()1914     public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1915         try {
1916             return ActivityManagerNative.getDefault().getProcessesInErrorState();
1917         } catch (RemoteException e) {
1918             return null;
1919         }
1920     }
1921 
1922     /**
1923      * Information you can retrieve about a running process.
1924      */
1925     public static class RunningAppProcessInfo implements Parcelable {
1926         /**
1927          * The name of the process that this object is associated with
1928          */
1929         public String processName;
1930 
1931         /**
1932          * The pid of this process; 0 if none
1933          */
1934         public int pid;
1935 
1936         /**
1937          * The user id of this process.
1938          */
1939         public int uid;
1940 
1941         /**
1942          * All packages that have been loaded into the process.
1943          */
1944         public String pkgList[];
1945 
1946         /**
1947          * Constant for {@link #flags}: this is an app that is unable to
1948          * correctly save its state when going to the background,
1949          * so it can not be killed while in the background.
1950          * @hide
1951          */
1952         public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1953 
1954         /**
1955          * Constant for {@link #flags}: this process is associated with a
1956          * persistent system app.
1957          * @hide
1958          */
1959         public static final int FLAG_PERSISTENT = 1<<1;
1960 
1961         /**
1962          * Constant for {@link #flags}: this process is associated with a
1963          * persistent system app.
1964          * @hide
1965          */
1966         public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1967 
1968         /**
1969          * Flags of information.  May be any of
1970          * {@link #FLAG_CANT_SAVE_STATE}.
1971          * @hide
1972          */
1973         public int flags;
1974 
1975         /**
1976          * Last memory trim level reported to the process: corresponds to
1977          * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1978          * ComponentCallbacks2.onTrimMemory(int)}.
1979          */
1980         public int lastTrimLevel;
1981 
1982         /**
1983          * Constant for {@link #importance}: this process is running the
1984          * foreground UI.
1985          */
1986         public static final int IMPORTANCE_FOREGROUND = 100;
1987 
1988         /**
1989          * Constant for {@link #importance}: this process is running something
1990          * that is actively visible to the user, though not in the immediate
1991          * foreground.
1992          */
1993         public static final int IMPORTANCE_VISIBLE = 200;
1994 
1995         /**
1996          * Constant for {@link #importance}: this process is running something
1997          * that is considered to be actively perceptible to the user.  An
1998          * example would be an application performing background music playback.
1999          */
2000         public static final int IMPORTANCE_PERCEPTIBLE = 130;
2001 
2002         /**
2003          * Constant for {@link #importance}: this process is running an
2004          * application that can not save its state, and thus can't be killed
2005          * while in the background.
2006          * @hide
2007          */
2008         public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
2009 
2010         /**
2011          * Constant for {@link #importance}: this process is contains services
2012          * that should remain running.
2013          */
2014         public static final int IMPORTANCE_SERVICE = 300;
2015 
2016         /**
2017          * Constant for {@link #importance}: this process process contains
2018          * background code that is expendable.
2019          */
2020         public static final int IMPORTANCE_BACKGROUND = 400;
2021 
2022         /**
2023          * Constant for {@link #importance}: this process is empty of any
2024          * actively running code.
2025          */
2026         public static final int IMPORTANCE_EMPTY = 500;
2027 
2028         /**
2029          * Constant for {@link #importance}: this process does not exist.
2030          */
2031         public static final int IMPORTANCE_GONE = 1000;
2032 
2033         /** @hide */
procStateToImportance(int procState)2034         public static int procStateToImportance(int procState) {
2035             if (procState >= ActivityManager.PROCESS_STATE_HOME) {
2036                 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
2037             } else if (procState >= ActivityManager.PROCESS_STATE_SERVICE) {
2038                 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
2039             } else if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
2040                 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
2041             } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
2042                 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
2043             } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
2044                 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
2045             } else {
2046                 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
2047             }
2048         }
2049 
2050         /**
2051          * The relative importance level that the system places on this
2052          * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
2053          * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
2054          * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
2055          * constants are numbered so that "more important" values are always
2056          * smaller than "less important" values.
2057          */
2058         public int importance;
2059 
2060         /**
2061          * An additional ordering within a particular {@link #importance}
2062          * category, providing finer-grained information about the relative
2063          * utility of processes within a category.  This number means nothing
2064          * except that a smaller values are more recently used (and thus
2065          * more important).  Currently an LRU value is only maintained for
2066          * the {@link #IMPORTANCE_BACKGROUND} category, though others may
2067          * be maintained in the future.
2068          */
2069         public int lru;
2070 
2071         /**
2072          * Constant for {@link #importanceReasonCode}: nothing special has
2073          * been specified for the reason for this level.
2074          */
2075         public static final int REASON_UNKNOWN = 0;
2076 
2077         /**
2078          * Constant for {@link #importanceReasonCode}: one of the application's
2079          * content providers is being used by another process.  The pid of
2080          * the client process is in {@link #importanceReasonPid} and the
2081          * target provider in this process is in
2082          * {@link #importanceReasonComponent}.
2083          */
2084         public static final int REASON_PROVIDER_IN_USE = 1;
2085 
2086         /**
2087          * Constant for {@link #importanceReasonCode}: one of the application's
2088          * content providers is being used by another process.  The pid of
2089          * the client process is in {@link #importanceReasonPid} and the
2090          * target provider in this process is in
2091          * {@link #importanceReasonComponent}.
2092          */
2093         public static final int REASON_SERVICE_IN_USE = 2;
2094 
2095         /**
2096          * The reason for {@link #importance}, if any.
2097          */
2098         public int importanceReasonCode;
2099 
2100         /**
2101          * For the specified values of {@link #importanceReasonCode}, this
2102          * is the process ID of the other process that is a client of this
2103          * process.  This will be 0 if no other process is using this one.
2104          */
2105         public int importanceReasonPid;
2106 
2107         /**
2108          * For the specified values of {@link #importanceReasonCode}, this
2109          * is the name of the component that is being used in this process.
2110          */
2111         public ComponentName importanceReasonComponent;
2112 
2113         /**
2114          * When {@link #importanceReasonPid} is non-0, this is the importance
2115          * of the other pid. @hide
2116          */
2117         public int importanceReasonImportance;
2118 
2119         /**
2120          * Current process state, as per PROCESS_STATE_* constants.
2121          * @hide
2122          */
2123         public int processState;
2124 
RunningAppProcessInfo()2125         public RunningAppProcessInfo() {
2126             importance = IMPORTANCE_FOREGROUND;
2127             importanceReasonCode = REASON_UNKNOWN;
2128             processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
2129         }
2130 
RunningAppProcessInfo(String pProcessName, int pPid, String pArr[])2131         public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
2132             processName = pProcessName;
2133             pid = pPid;
2134             pkgList = pArr;
2135         }
2136 
describeContents()2137         public int describeContents() {
2138             return 0;
2139         }
2140 
writeToParcel(Parcel dest, int flags)2141         public void writeToParcel(Parcel dest, int flags) {
2142             dest.writeString(processName);
2143             dest.writeInt(pid);
2144             dest.writeInt(uid);
2145             dest.writeStringArray(pkgList);
2146             dest.writeInt(this.flags);
2147             dest.writeInt(lastTrimLevel);
2148             dest.writeInt(importance);
2149             dest.writeInt(lru);
2150             dest.writeInt(importanceReasonCode);
2151             dest.writeInt(importanceReasonPid);
2152             ComponentName.writeToParcel(importanceReasonComponent, dest);
2153             dest.writeInt(importanceReasonImportance);
2154             dest.writeInt(processState);
2155         }
2156 
readFromParcel(Parcel source)2157         public void readFromParcel(Parcel source) {
2158             processName = source.readString();
2159             pid = source.readInt();
2160             uid = source.readInt();
2161             pkgList = source.readStringArray();
2162             flags = source.readInt();
2163             lastTrimLevel = source.readInt();
2164             importance = source.readInt();
2165             lru = source.readInt();
2166             importanceReasonCode = source.readInt();
2167             importanceReasonPid = source.readInt();
2168             importanceReasonComponent = ComponentName.readFromParcel(source);
2169             importanceReasonImportance = source.readInt();
2170             processState = source.readInt();
2171         }
2172 
2173         public static final Creator<RunningAppProcessInfo> CREATOR =
2174             new Creator<RunningAppProcessInfo>() {
2175             public RunningAppProcessInfo createFromParcel(Parcel source) {
2176                 return new RunningAppProcessInfo(source);
2177             }
2178             public RunningAppProcessInfo[] newArray(int size) {
2179                 return new RunningAppProcessInfo[size];
2180             }
2181         };
2182 
RunningAppProcessInfo(Parcel source)2183         private RunningAppProcessInfo(Parcel source) {
2184             readFromParcel(source);
2185         }
2186     }
2187 
2188     /**
2189      * Returns a list of application processes installed on external media
2190      * that are running on the device.
2191      *
2192      * <p><b>Note: this method is only intended for debugging or building
2193      * a user-facing process management UI.</b></p>
2194      *
2195      * @return Returns a list of ApplicationInfo records, or null if none
2196      * This list ordering is not specified.
2197      * @hide
2198      */
getRunningExternalApplications()2199     public List<ApplicationInfo> getRunningExternalApplications() {
2200         try {
2201             return ActivityManagerNative.getDefault().getRunningExternalApplications();
2202         } catch (RemoteException e) {
2203             return null;
2204         }
2205     }
2206 
2207     /**
2208      * Returns a list of application processes that are running on the device.
2209      *
2210      * <p><b>Note: this method is only intended for debugging or building
2211      * a user-facing process management UI.</b></p>
2212      *
2213      * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2214      * running processes (it will not return an empty list).  This list ordering is not
2215      * specified.
2216      */
getRunningAppProcesses()2217     public List<RunningAppProcessInfo> getRunningAppProcesses() {
2218         try {
2219             return ActivityManagerNative.getDefault().getRunningAppProcesses();
2220         } catch (RemoteException e) {
2221             return null;
2222         }
2223     }
2224 
2225     /**
2226      * Return global memory state information for the calling process.  This
2227      * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
2228      * only fields that will be filled in are
2229      * {@link RunningAppProcessInfo#pid},
2230      * {@link RunningAppProcessInfo#uid},
2231      * {@link RunningAppProcessInfo#lastTrimLevel},
2232      * {@link RunningAppProcessInfo#importance},
2233      * {@link RunningAppProcessInfo#lru}, and
2234      * {@link RunningAppProcessInfo#importanceReasonCode}.
2235      */
getMyMemoryState(RunningAppProcessInfo outState)2236     static public void getMyMemoryState(RunningAppProcessInfo outState) {
2237         try {
2238             ActivityManagerNative.getDefault().getMyMemoryState(outState);
2239         } catch (RemoteException e) {
2240         }
2241     }
2242 
2243     /**
2244      * Return information about the memory usage of one or more processes.
2245      *
2246      * <p><b>Note: this method is only intended for debugging or building
2247      * a user-facing process management UI.</b></p>
2248      *
2249      * @param pids The pids of the processes whose memory usage is to be
2250      * retrieved.
2251      * @return Returns an array of memory information, one for each
2252      * requested pid.
2253      */
getProcessMemoryInfo(int[] pids)2254     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2255         try {
2256             return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2257         } catch (RemoteException e) {
2258             return null;
2259         }
2260     }
2261 
2262     /**
2263      * @deprecated This is now just a wrapper for
2264      * {@link #killBackgroundProcesses(String)}; the previous behavior here
2265      * is no longer available to applications because it allows them to
2266      * break other applications by removing their alarms, stopping their
2267      * services, etc.
2268      */
2269     @Deprecated
restartPackage(String packageName)2270     public void restartPackage(String packageName) {
2271         killBackgroundProcesses(packageName);
2272     }
2273 
2274     /**
2275      * Have the system immediately kill all background processes associated
2276      * with the given package.  This is the same as the kernel killing those
2277      * processes to reclaim memory; the system will take care of restarting
2278      * these processes in the future as needed.
2279      *
2280      * <p>You must hold the permission
2281      * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2282      * call this method.
2283      *
2284      * @param packageName The name of the package whose processes are to
2285      * be killed.
2286      */
killBackgroundProcesses(String packageName)2287     public void killBackgroundProcesses(String packageName) {
2288         try {
2289             ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2290                     UserHandle.myUserId());
2291         } catch (RemoteException e) {
2292         }
2293     }
2294 
2295     /**
2296      * Have the system perform a force stop of everything associated with
2297      * the given application package.  All processes that share its uid
2298      * will be killed, all services it has running stopped, all activities
2299      * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2300      * broadcast will be sent, so that any of its registered alarms can
2301      * be stopped, notifications removed, etc.
2302      *
2303      * <p>You must hold the permission
2304      * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2305      * call this method.
2306      *
2307      * @param packageName The name of the package to be stopped.
2308      * @param userId The user for which the running package is to be stopped.
2309      *
2310      * @hide This is not available to third party applications due to
2311      * it allowing them to break other applications by stopping their
2312      * services, removing their alarms, etc.
2313      */
forceStopPackageAsUser(String packageName, int userId)2314     public void forceStopPackageAsUser(String packageName, int userId) {
2315         try {
2316             ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
2317         } catch (RemoteException e) {
2318         }
2319     }
2320 
2321     /**
2322      * @see #forceStopPackageAsUser(String, int)
2323      * @hide
2324      */
forceStopPackage(String packageName)2325     public void forceStopPackage(String packageName) {
2326         forceStopPackageAsUser(packageName, UserHandle.myUserId());
2327     }
2328 
2329     /**
2330      * Get the device configuration attributes.
2331      */
getDeviceConfigurationInfo()2332     public ConfigurationInfo getDeviceConfigurationInfo() {
2333         try {
2334             return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2335         } catch (RemoteException e) {
2336         }
2337         return null;
2338     }
2339 
2340     /**
2341      * Get the preferred density of icons for the launcher. This is used when
2342      * custom drawables are created (e.g., for shortcuts).
2343      *
2344      * @return density in terms of DPI
2345      */
getLauncherLargeIconDensity()2346     public int getLauncherLargeIconDensity() {
2347         final Resources res = mContext.getResources();
2348         final int density = res.getDisplayMetrics().densityDpi;
2349         final int sw = res.getConfiguration().smallestScreenWidthDp;
2350 
2351         if (sw < 600) {
2352             // Smaller than approx 7" tablets, use the regular icon size.
2353             return density;
2354         }
2355 
2356         switch (density) {
2357             case DisplayMetrics.DENSITY_LOW:
2358                 return DisplayMetrics.DENSITY_MEDIUM;
2359             case DisplayMetrics.DENSITY_MEDIUM:
2360                 return DisplayMetrics.DENSITY_HIGH;
2361             case DisplayMetrics.DENSITY_TV:
2362                 return DisplayMetrics.DENSITY_XHIGH;
2363             case DisplayMetrics.DENSITY_HIGH:
2364                 return DisplayMetrics.DENSITY_XHIGH;
2365             case DisplayMetrics.DENSITY_XHIGH:
2366                 return DisplayMetrics.DENSITY_XXHIGH;
2367             case DisplayMetrics.DENSITY_XXHIGH:
2368                 return DisplayMetrics.DENSITY_XHIGH * 2;
2369             default:
2370                 // The density is some abnormal value.  Return some other
2371                 // abnormal value that is a reasonable scaling of it.
2372                 return (int)((density*1.5f)+.5f);
2373         }
2374     }
2375 
2376     /**
2377      * Get the preferred launcher icon size. This is used when custom drawables
2378      * are created (e.g., for shortcuts).
2379      *
2380      * @return dimensions of square icons in terms of pixels
2381      */
getLauncherLargeIconSize()2382     public int getLauncherLargeIconSize() {
2383         return getLauncherLargeIconSizeInner(mContext);
2384     }
2385 
getLauncherLargeIconSizeInner(Context context)2386     static int getLauncherLargeIconSizeInner(Context context) {
2387         final Resources res = context.getResources();
2388         final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2389         final int sw = res.getConfiguration().smallestScreenWidthDp;
2390 
2391         if (sw < 600) {
2392             // Smaller than approx 7" tablets, use the regular icon size.
2393             return size;
2394         }
2395 
2396         final int density = res.getDisplayMetrics().densityDpi;
2397 
2398         switch (density) {
2399             case DisplayMetrics.DENSITY_LOW:
2400                 return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2401             case DisplayMetrics.DENSITY_MEDIUM:
2402                 return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2403             case DisplayMetrics.DENSITY_TV:
2404                 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2405             case DisplayMetrics.DENSITY_HIGH:
2406                 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2407             case DisplayMetrics.DENSITY_XHIGH:
2408                 return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2409             case DisplayMetrics.DENSITY_XXHIGH:
2410                 return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2411             default:
2412                 // The density is some abnormal value.  Return some other
2413                 // abnormal value that is a reasonable scaling of it.
2414                 return (int)((size*1.5f) + .5f);
2415         }
2416     }
2417 
2418     /**
2419      * Returns "true" if the user interface is currently being messed with
2420      * by a monkey.
2421      */
isUserAMonkey()2422     public static boolean isUserAMonkey() {
2423         try {
2424             return ActivityManagerNative.getDefault().isUserAMonkey();
2425         } catch (RemoteException e) {
2426         }
2427         return false;
2428     }
2429 
2430     /**
2431      * Returns "true" if device is running in a test harness.
2432      */
isRunningInTestHarness()2433     public static boolean isRunningInTestHarness() {
2434         return SystemProperties.getBoolean("ro.test_harness", false);
2435     }
2436 
2437     /**
2438      * Returns the launch count of each installed package.
2439      *
2440      * @hide
2441      */
2442     /*public Map<String, Integer> getAllPackageLaunchCounts() {
2443         try {
2444             IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2445                     ServiceManager.getService("usagestats"));
2446             if (usageStatsService == null) {
2447                 return new HashMap<String, Integer>();
2448             }
2449 
2450             UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2451                     ActivityThread.currentPackageName());
2452             if (allPkgUsageStats == null) {
2453                 return new HashMap<String, Integer>();
2454             }
2455 
2456             Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2457             for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2458                 launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2459             }
2460 
2461             return launchCounts;
2462         } catch (RemoteException e) {
2463             Log.w(TAG, "Could not query launch counts", e);
2464             return new HashMap<String, Integer>();
2465         }
2466     }*/
2467 
2468     /** @hide */
checkComponentPermission(String permission, int uid, int owningUid, boolean exported)2469     public static int checkComponentPermission(String permission, int uid,
2470             int owningUid, boolean exported) {
2471         // Root, system server get to do everything.
2472         if (uid == 0 || uid == Process.SYSTEM_UID) {
2473             return PackageManager.PERMISSION_GRANTED;
2474         }
2475         // Isolated processes don't get any permissions.
2476         if (UserHandle.isIsolated(uid)) {
2477             return PackageManager.PERMISSION_DENIED;
2478         }
2479         // If there is a uid that owns whatever is being accessed, it has
2480         // blanket access to it regardless of the permissions it requires.
2481         if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2482             return PackageManager.PERMISSION_GRANTED;
2483         }
2484         // If the target is not exported, then nobody else can get to it.
2485         if (!exported) {
2486             /*
2487             RuntimeException here = new RuntimeException("here");
2488             here.fillInStackTrace();
2489             Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2490                     here);
2491             */
2492             return PackageManager.PERMISSION_DENIED;
2493         }
2494         if (permission == null) {
2495             return PackageManager.PERMISSION_GRANTED;
2496         }
2497         try {
2498             return AppGlobals.getPackageManager()
2499                     .checkUidPermission(permission, uid);
2500         } catch (RemoteException e) {
2501             // Should never happen, but if it does... deny!
2502             Slog.e(TAG, "PackageManager is dead?!?", e);
2503         }
2504         return PackageManager.PERMISSION_DENIED;
2505     }
2506 
2507     /** @hide */
checkUidPermission(String permission, int uid)2508     public static int checkUidPermission(String permission, int uid) {
2509         try {
2510             return AppGlobals.getPackageManager()
2511                     .checkUidPermission(permission, uid);
2512         } catch (RemoteException e) {
2513             // Should never happen, but if it does... deny!
2514             Slog.e(TAG, "PackageManager is dead?!?", e);
2515         }
2516         return PackageManager.PERMISSION_DENIED;
2517     }
2518 
2519     /**
2520      * @hide
2521      * Helper for dealing with incoming user arguments to system service calls.
2522      * Takes care of checking permissions and converting USER_CURRENT to the
2523      * actual current user.
2524      *
2525      * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2526      * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2527      * @param userId The user id argument supplied by the caller -- this is the user
2528      * they want to run as.
2529      * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2530      * to get a USER_ALL returned and deal with it correctly.  If false,
2531      * an exception will be thrown if USER_ALL is supplied.
2532      * @param requireFull If true, the caller must hold
2533      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2534      * different user than their current process; otherwise they must hold
2535      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2536      * @param name Optional textual name of the incoming call; only for generating error messages.
2537      * @param callerPackage Optional package name of caller; only for error messages.
2538      *
2539      * @return Returns the user ID that the call should run as.  Will always be a concrete
2540      * user number, unless <var>allowAll</var> is true in which case it could also be
2541      * USER_ALL.
2542      */
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)2543     public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2544             boolean allowAll, boolean requireFull, String name, String callerPackage) {
2545         if (UserHandle.getUserId(callingUid) == userId) {
2546             return userId;
2547         }
2548         try {
2549             return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2550                     callingUid, userId, allowAll, requireFull, name, callerPackage);
2551         } catch (RemoteException e) {
2552             throw new SecurityException("Failed calling activity manager", e);
2553         }
2554     }
2555 
2556     /**
2557      * Gets the userId of the current foreground user. Requires system permissions.
2558      * @hide
2559      */
2560     @SystemApi
getCurrentUser()2561     public static int getCurrentUser() {
2562         UserInfo ui;
2563         try {
2564             ui = ActivityManagerNative.getDefault().getCurrentUser();
2565             return ui != null ? ui.id : 0;
2566         } catch (RemoteException e) {
2567             return 0;
2568         }
2569     }
2570 
2571     /**
2572      * @param userid the user's id. Zero indicates the default user
2573      * @hide
2574      */
switchUser(int userid)2575     public boolean switchUser(int userid) {
2576         try {
2577             return ActivityManagerNative.getDefault().switchUser(userid);
2578         } catch (RemoteException e) {
2579             return false;
2580         }
2581     }
2582 
2583     /**
2584      * Return whether the given user is actively running.  This means that
2585      * the user is in the "started" state, not "stopped" -- it is currently
2586      * allowed to run code through scheduled alarms, receiving broadcasts,
2587      * etc.  A started user may be either the current foreground user or a
2588      * background user; the result here does not distinguish between the two.
2589      * @param userid the user's id. Zero indicates the default user.
2590      * @hide
2591      */
isUserRunning(int userid)2592     public boolean isUserRunning(int userid) {
2593         try {
2594             return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2595         } catch (RemoteException e) {
2596             return false;
2597         }
2598     }
2599 
2600     /**
2601      * Perform a system dump of various state associated with the given application
2602      * package name.  This call blocks while the dump is being performed, so should
2603      * not be done on a UI thread.  The data will be written to the given file
2604      * descriptor as text.  An application must hold the
2605      * {@link android.Manifest.permission#DUMP} permission to make this call.
2606      * @param fd The file descriptor that the dump should be written to.  The file
2607      * descriptor is <em>not</em> closed by this function; the caller continues to
2608      * own it.
2609      * @param packageName The name of the package that is to be dumped.
2610      */
dumpPackageState(FileDescriptor fd, String packageName)2611     public void dumpPackageState(FileDescriptor fd, String packageName) {
2612         dumpPackageStateStatic(fd, packageName);
2613     }
2614 
2615     /**
2616      * @hide
2617      */
dumpPackageStateStatic(FileDescriptor fd, String packageName)2618     public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2619         FileOutputStream fout = new FileOutputStream(fd);
2620         PrintWriter pw = new FastPrintWriter(fout);
2621         dumpService(pw, fd, "package", new String[] { packageName });
2622         pw.println();
2623         dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2624                 "-a", "package", packageName });
2625         pw.println();
2626         dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
2627         pw.println();
2628         dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
2629         pw.println();
2630         dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2631         pw.println();
2632         dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2633         pw.flush();
2634     }
2635 
dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args)2636     private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2637         pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2638         IBinder service = ServiceManager.checkService(name);
2639         if (service == null) {
2640             pw.println("  (Service not found)");
2641             return;
2642         }
2643         TransferPipe tp = null;
2644         try {
2645             pw.flush();
2646             tp = new TransferPipe();
2647             tp.setBufferPrefix("  ");
2648             service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
2649             tp.go(fd, 10000);
2650         } catch (Throwable e) {
2651             if (tp != null) {
2652                 tp.kill();
2653             }
2654             pw.println("Failure dumping service:");
2655             e.printStackTrace(pw);
2656         }
2657     }
2658 
2659     /**
2660      * @hide
2661      */
startLockTaskMode(int taskId)2662     public void startLockTaskMode(int taskId) {
2663         try {
2664             ActivityManagerNative.getDefault().startLockTaskMode(taskId);
2665         } catch (RemoteException e) {
2666         }
2667     }
2668 
2669     /**
2670      * @hide
2671      */
stopLockTaskMode()2672     public void stopLockTaskMode() {
2673         try {
2674             ActivityManagerNative.getDefault().stopLockTaskMode();
2675         } catch (RemoteException e) {
2676         }
2677     }
2678 
2679     /**
2680      * Return whether currently in lock task mode.  When in this mode
2681      * no new tasks can be created or switched to.
2682      *
2683      * @see Activity#startLockTask()
2684      */
isInLockTaskMode()2685     public boolean isInLockTaskMode() {
2686         try {
2687             return ActivityManagerNative.getDefault().isInLockTaskMode();
2688         } catch (RemoteException e) {
2689             return false;
2690         }
2691     }
2692 
2693     /**
2694      * The AppTask allows you to manage your own application's tasks.
2695      * See {@link android.app.ActivityManager#getAppTasks()}
2696      */
2697     public static class AppTask {
2698         private IAppTask mAppTaskImpl;
2699 
2700         /** @hide */
AppTask(IAppTask task)2701         public AppTask(IAppTask task) {
2702             mAppTaskImpl = task;
2703         }
2704 
2705         /**
2706          * Finishes all activities in this task and removes it from the recent tasks list.
2707          */
finishAndRemoveTask()2708         public void finishAndRemoveTask() {
2709             try {
2710                 mAppTaskImpl.finishAndRemoveTask();
2711             } catch (RemoteException e) {
2712                 Slog.e(TAG, "Invalid AppTask", e);
2713             }
2714         }
2715 
2716         /**
2717          * Get the RecentTaskInfo associated with this task.
2718          *
2719          * @return The RecentTaskInfo for this task, or null if the task no longer exists.
2720          */
getTaskInfo()2721         public RecentTaskInfo getTaskInfo() {
2722             try {
2723                 return mAppTaskImpl.getTaskInfo();
2724             } catch (RemoteException e) {
2725                 Slog.e(TAG, "Invalid AppTask", e);
2726                 return null;
2727             }
2728         }
2729 
2730         /**
2731          * Bring this task to the foreground.  If it contains activities, they will be
2732          * brought to the foreground with it and their instances re-created if needed.
2733          * If it doesn't contain activities, the root activity of the task will be
2734          * re-launched.
2735          */
moveToFront()2736         public void moveToFront() {
2737             try {
2738                 mAppTaskImpl.moveToFront();
2739             } catch (RemoteException e) {
2740                 Slog.e(TAG, "Invalid AppTask", e);
2741             }
2742         }
2743 
2744         /**
2745          * Start an activity in this task.  Brings the task to the foreground.  If this task
2746          * is not currently active (that is, its id < 0), then a new activity for the given
2747          * Intent will be launched as the root of the task and the task brought to the
2748          * foreground.  Otherwise, if this task is currently active and the Intent does not specify
2749          * an activity to launch in a new task, then a new activity for the given Intent will
2750          * be launched on top of the task and the task brought to the foreground.  If this
2751          * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
2752          * or would otherwise be launched in to a new task, then the activity not launched but
2753          * this task be brought to the foreground and a new intent delivered to the top
2754          * activity if appropriate.
2755          *
2756          * <p>In other words, you generally want to use an Intent here that does not specify
2757          * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
2758          * and let the system do the right thing.</p>
2759          *
2760          * @param intent The Intent describing the new activity to be launched on the task.
2761          * @param options Optional launch options.
2762          *
2763          * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
2764          */
startActivity(Context context, Intent intent, Bundle options)2765         public void startActivity(Context context, Intent intent, Bundle options) {
2766             ActivityThread thread = ActivityThread.currentActivityThread();
2767             thread.getInstrumentation().execStartActivityFromAppTask(context,
2768                     thread.getApplicationThread(), mAppTaskImpl, intent, options);
2769         }
2770 
2771         /**
2772          * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
2773          * Intent of this AppTask.
2774          *
2775          * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
2776          * be set; otherwise, it will be cleared.
2777          */
setExcludeFromRecents(boolean exclude)2778         public void setExcludeFromRecents(boolean exclude) {
2779             try {
2780                 mAppTaskImpl.setExcludeFromRecents(exclude);
2781             } catch (RemoteException e) {
2782                 Slog.e(TAG, "Invalid AppTask", e);
2783             }
2784         }
2785     }
2786 }
2787