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