ActivityManager.java revision e4a0c5722b1d8db95dfc842d716452dbbf02c86d
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 Rect[] taskBounds;
1793        public int displayId;
1794
1795        @Override
1796        public int describeContents() {
1797            return 0;
1798        }
1799
1800        @Override
1801        public void writeToParcel(Parcel dest, int flags) {
1802            dest.writeInt(stackId);
1803            dest.writeInt(bounds.left);
1804            dest.writeInt(bounds.top);
1805            dest.writeInt(bounds.right);
1806            dest.writeInt(bounds.bottom);
1807            dest.writeIntArray(taskIds);
1808            dest.writeStringArray(taskNames);
1809            final int boundsCount = taskBounds == null ? 0 : taskBounds.length;
1810            dest.writeInt(boundsCount);
1811            for (int i = 0; i < boundsCount; i++) {
1812                dest.writeInt(taskBounds[i].left);
1813                dest.writeInt(taskBounds[i].top);
1814                dest.writeInt(taskBounds[i].right);
1815                dest.writeInt(taskBounds[i].bottom);
1816            }
1817            dest.writeInt(displayId);
1818        }
1819
1820        public void readFromParcel(Parcel source) {
1821            stackId = source.readInt();
1822            bounds = new Rect(
1823                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
1824            taskIds = source.createIntArray();
1825            taskNames = source.createStringArray();
1826            final int boundsCount = source.readInt();
1827            if (boundsCount > 0) {
1828                taskBounds = new Rect[boundsCount];
1829                for (int i = 0; i < boundsCount; i++) {
1830                    taskBounds[i] = new Rect();
1831                    taskBounds[i].set(
1832                            source.readInt(), source.readInt(), source.readInt(), source.readInt());
1833                }
1834            } else {
1835                taskBounds = null;
1836            }
1837            displayId = source.readInt();
1838        }
1839
1840        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1841            @Override
1842            public StackInfo createFromParcel(Parcel source) {
1843                return new StackInfo(source);
1844            }
1845            @Override
1846            public StackInfo[] newArray(int size) {
1847                return new StackInfo[size];
1848            }
1849        };
1850
1851        public StackInfo() {
1852        }
1853
1854        private StackInfo(Parcel source) {
1855            readFromParcel(source);
1856        }
1857
1858        public String toString(String prefix) {
1859            StringBuilder sb = new StringBuilder(256);
1860            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1861                    sb.append(" bounds="); sb.append(bounds.toShortString());
1862                    sb.append(" displayId="); sb.append(displayId);
1863                    sb.append("\n");
1864            prefix = prefix + "  ";
1865            for (int i = 0; i < taskIds.length; ++i) {
1866                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1867                        sb.append(": "); sb.append(taskNames[i]);
1868                        if (taskBounds != null) {
1869                            sb.append(" bounds="); sb.append(taskBounds[i].toShortString());
1870                        }
1871                        sb.append("\n");
1872            }
1873            return sb.toString();
1874        }
1875
1876        @Override
1877        public String toString() {
1878            return toString("");
1879        }
1880    }
1881
1882    /**
1883     * @hide
1884     */
1885    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1886        try {
1887            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1888                    observer, UserHandle.myUserId());
1889        } catch (RemoteException e) {
1890            return false;
1891        }
1892    }
1893
1894    /**
1895     * Permits an application to erase its own data from disk.  This is equivalent to
1896     * the user choosing to clear the app's data from within the device settings UI.  It
1897     * erases all dynamic data associated with the app -- its private data and data in its
1898     * private area on external storage -- but does not remove the installed application
1899     * itself, nor any OBB files.
1900     *
1901     * @return {@code true} if the application successfully requested that the application's
1902     *     data be erased; {@code false} otherwise.
1903     */
1904    public boolean clearApplicationUserData() {
1905        return clearApplicationUserData(mContext.getPackageName(), null);
1906    }
1907
1908    /**
1909     * Information you can retrieve about any processes that are in an error condition.
1910     */
1911    public static class ProcessErrorStateInfo implements Parcelable {
1912        /**
1913         * Condition codes
1914         */
1915        public static final int NO_ERROR = 0;
1916        public static final int CRASHED = 1;
1917        public static final int NOT_RESPONDING = 2;
1918
1919        /**
1920         * The condition that the process is in.
1921         */
1922        public int condition;
1923
1924        /**
1925         * The process name in which the crash or error occurred.
1926         */
1927        public String processName;
1928
1929        /**
1930         * The pid of this process; 0 if none
1931         */
1932        public int pid;
1933
1934        /**
1935         * The kernel user-ID that has been assigned to this process;
1936         * currently this is not a unique ID (multiple applications can have
1937         * the same uid).
1938         */
1939        public int uid;
1940
1941        /**
1942         * The activity name associated with the error, if known.  May be null.
1943         */
1944        public String tag;
1945
1946        /**
1947         * A short message describing the error condition.
1948         */
1949        public String shortMsg;
1950
1951        /**
1952         * A long message describing the error condition.
1953         */
1954        public String longMsg;
1955
1956        /**
1957         * The stack trace where the error originated.  May be null.
1958         */
1959        public String stackTrace;
1960
1961        /**
1962         * to be deprecated: This value will always be null.
1963         */
1964        public byte[] crashData = null;
1965
1966        public ProcessErrorStateInfo() {
1967        }
1968
1969        @Override
1970        public int describeContents() {
1971            return 0;
1972        }
1973
1974        @Override
1975        public void writeToParcel(Parcel dest, int flags) {
1976            dest.writeInt(condition);
1977            dest.writeString(processName);
1978            dest.writeInt(pid);
1979            dest.writeInt(uid);
1980            dest.writeString(tag);
1981            dest.writeString(shortMsg);
1982            dest.writeString(longMsg);
1983            dest.writeString(stackTrace);
1984        }
1985
1986        public void readFromParcel(Parcel source) {
1987            condition = source.readInt();
1988            processName = source.readString();
1989            pid = source.readInt();
1990            uid = source.readInt();
1991            tag = source.readString();
1992            shortMsg = source.readString();
1993            longMsg = source.readString();
1994            stackTrace = source.readString();
1995        }
1996
1997        public static final Creator<ProcessErrorStateInfo> CREATOR =
1998                new Creator<ProcessErrorStateInfo>() {
1999            public ProcessErrorStateInfo createFromParcel(Parcel source) {
2000                return new ProcessErrorStateInfo(source);
2001            }
2002            public ProcessErrorStateInfo[] newArray(int size) {
2003                return new ProcessErrorStateInfo[size];
2004            }
2005        };
2006
2007        private ProcessErrorStateInfo(Parcel source) {
2008            readFromParcel(source);
2009        }
2010    }
2011
2012    /**
2013     * Returns a list of any processes that are currently in an error condition.  The result
2014     * will be null if all processes are running properly at this time.
2015     *
2016     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
2017     * current error conditions (it will not return an empty list).  This list ordering is not
2018     * specified.
2019     */
2020    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
2021        try {
2022            return ActivityManagerNative.getDefault().getProcessesInErrorState();
2023        } catch (RemoteException e) {
2024            return null;
2025        }
2026    }
2027
2028    /**
2029     * Information you can retrieve about a running process.
2030     */
2031    public static class RunningAppProcessInfo implements Parcelable {
2032        /**
2033         * The name of the process that this object is associated with
2034         */
2035        public String processName;
2036
2037        /**
2038         * The pid of this process; 0 if none
2039         */
2040        public int pid;
2041
2042        /**
2043         * The user id of this process.
2044         */
2045        public int uid;
2046
2047        /**
2048         * All packages that have been loaded into the process.
2049         */
2050        public String pkgList[];
2051
2052        /**
2053         * Constant for {@link #flags}: this is an app that is unable to
2054         * correctly save its state when going to the background,
2055         * so it can not be killed while in the background.
2056         * @hide
2057         */
2058        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
2059
2060        /**
2061         * Constant for {@link #flags}: this process is associated with a
2062         * persistent system app.
2063         * @hide
2064         */
2065        public static final int FLAG_PERSISTENT = 1<<1;
2066
2067        /**
2068         * Constant for {@link #flags}: this process is associated with a
2069         * persistent system app.
2070         * @hide
2071         */
2072        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
2073
2074        /**
2075         * Flags of information.  May be any of
2076         * {@link #FLAG_CANT_SAVE_STATE}.
2077         * @hide
2078         */
2079        public int flags;
2080
2081        /**
2082         * Last memory trim level reported to the process: corresponds to
2083         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2084         * ComponentCallbacks2.onTrimMemory(int)}.
2085         */
2086        public int lastTrimLevel;
2087
2088        /**
2089         * Constant for {@link #importance}: This process is running the
2090         * foreground UI; that is, it is the thing currently at the top of the screen
2091         * that the user is interacting with.
2092         */
2093        public static final int IMPORTANCE_FOREGROUND = 100;
2094
2095        /**
2096         * Constant for {@link #importance}: This process is running a foreground
2097         * service, for example to perform music playback even while the user is
2098         * not immediately in the app.  This generally indicates that the process
2099         * is doing something the user actively cares about.
2100         */
2101        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
2102
2103        /**
2104         * Constant for {@link #importance}: This process is running the foreground
2105         * UI, but the device is asleep so it is not visible to the user.  This means
2106         * the user is not really aware of the process, because they can not see or
2107         * interact with it, but it is quite important because it what they expect to
2108         * return to once unlocking the device.
2109         */
2110        public static final int IMPORTANCE_TOP_SLEEPING = 150;
2111
2112        /**
2113         * Constant for {@link #importance}: This process is running something
2114         * that is actively visible to the user, though not in the immediate
2115         * foreground.  This may be running a window that is behind the current
2116         * foreground (so paused and with its state saved, not interacting with
2117         * the user, but visible to them to some degree); it may also be running
2118         * other services under the system's control that it inconsiders important.
2119         */
2120        public static final int IMPORTANCE_VISIBLE = 200;
2121
2122        /**
2123         * Constant for {@link #importance}: This process is not something the user
2124         * is directly aware of, but is otherwise perceptable to them to some degree.
2125         */
2126        public static final int IMPORTANCE_PERCEPTIBLE = 130;
2127
2128        /**
2129         * Constant for {@link #importance}: This process is running an
2130         * application that can not save its state, and thus can't be killed
2131         * while in the background.
2132         * @hide
2133         */
2134        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
2135
2136        /**
2137         * Constant for {@link #importance}: This process is contains services
2138         * that should remain running.  These are background services apps have
2139         * started, not something the user is aware of, so they may be killed by
2140         * the system relatively freely (though it is generally desired that they
2141         * stay running as long as they want to).
2142         */
2143        public static final int IMPORTANCE_SERVICE = 300;
2144
2145        /**
2146         * Constant for {@link #importance}: This process process contains
2147         * background code that is expendable.
2148         */
2149        public static final int IMPORTANCE_BACKGROUND = 400;
2150
2151        /**
2152         * Constant for {@link #importance}: This process is empty of any
2153         * actively running code.
2154         */
2155        public static final int IMPORTANCE_EMPTY = 500;
2156
2157        /**
2158         * Constant for {@link #importance}: This process does not exist.
2159         */
2160        public static final int IMPORTANCE_GONE = 1000;
2161
2162        /** @hide */
2163        public static int procStateToImportance(int procState) {
2164            if (procState == PROCESS_STATE_NONEXISTENT) {
2165                return IMPORTANCE_GONE;
2166            } else if (procState >= PROCESS_STATE_HOME) {
2167                return IMPORTANCE_BACKGROUND;
2168            } else if (procState >= PROCESS_STATE_SERVICE) {
2169                return IMPORTANCE_SERVICE;
2170            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
2171                return IMPORTANCE_CANT_SAVE_STATE;
2172            } else if (procState >= PROCESS_STATE_IMPORTANT_BACKGROUND) {
2173                return IMPORTANCE_PERCEPTIBLE;
2174            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
2175                return IMPORTANCE_VISIBLE;
2176            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
2177                return IMPORTANCE_TOP_SLEEPING;
2178            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
2179                return IMPORTANCE_FOREGROUND_SERVICE;
2180            } else {
2181                return IMPORTANCE_FOREGROUND;
2182            }
2183        }
2184
2185        /**
2186         * The relative importance level that the system places on this
2187         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
2188         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
2189         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
2190         * constants are numbered so that "more important" values are always
2191         * smaller than "less important" values.
2192         */
2193        public int importance;
2194
2195        /**
2196         * An additional ordering within a particular {@link #importance}
2197         * category, providing finer-grained information about the relative
2198         * utility of processes within a category.  This number means nothing
2199         * except that a smaller values are more recently used (and thus
2200         * more important).  Currently an LRU value is only maintained for
2201         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
2202         * be maintained in the future.
2203         */
2204        public int lru;
2205
2206        /**
2207         * Constant for {@link #importanceReasonCode}: nothing special has
2208         * been specified for the reason for this level.
2209         */
2210        public static final int REASON_UNKNOWN = 0;
2211
2212        /**
2213         * Constant for {@link #importanceReasonCode}: one of the application's
2214         * content providers is being used by another process.  The pid of
2215         * the client process is in {@link #importanceReasonPid} and the
2216         * target provider in this process is in
2217         * {@link #importanceReasonComponent}.
2218         */
2219        public static final int REASON_PROVIDER_IN_USE = 1;
2220
2221        /**
2222         * Constant for {@link #importanceReasonCode}: one of the application's
2223         * content providers is being used by another process.  The pid of
2224         * the client process is in {@link #importanceReasonPid} and the
2225         * target provider in this process is in
2226         * {@link #importanceReasonComponent}.
2227         */
2228        public static final int REASON_SERVICE_IN_USE = 2;
2229
2230        /**
2231         * The reason for {@link #importance}, if any.
2232         */
2233        public int importanceReasonCode;
2234
2235        /**
2236         * For the specified values of {@link #importanceReasonCode}, this
2237         * is the process ID of the other process that is a client of this
2238         * process.  This will be 0 if no other process is using this one.
2239         */
2240        public int importanceReasonPid;
2241
2242        /**
2243         * For the specified values of {@link #importanceReasonCode}, this
2244         * is the name of the component that is being used in this process.
2245         */
2246        public ComponentName importanceReasonComponent;
2247
2248        /**
2249         * When {@link #importanceReasonPid} is non-0, this is the importance
2250         * of the other pid. @hide
2251         */
2252        public int importanceReasonImportance;
2253
2254        /**
2255         * Current process state, as per PROCESS_STATE_* constants.
2256         * @hide
2257         */
2258        public int processState;
2259
2260        public RunningAppProcessInfo() {
2261            importance = IMPORTANCE_FOREGROUND;
2262            importanceReasonCode = REASON_UNKNOWN;
2263            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
2264        }
2265
2266        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
2267            processName = pProcessName;
2268            pid = pPid;
2269            pkgList = pArr;
2270        }
2271
2272        public int describeContents() {
2273            return 0;
2274        }
2275
2276        public void writeToParcel(Parcel dest, int flags) {
2277            dest.writeString(processName);
2278            dest.writeInt(pid);
2279            dest.writeInt(uid);
2280            dest.writeStringArray(pkgList);
2281            dest.writeInt(this.flags);
2282            dest.writeInt(lastTrimLevel);
2283            dest.writeInt(importance);
2284            dest.writeInt(lru);
2285            dest.writeInt(importanceReasonCode);
2286            dest.writeInt(importanceReasonPid);
2287            ComponentName.writeToParcel(importanceReasonComponent, dest);
2288            dest.writeInt(importanceReasonImportance);
2289            dest.writeInt(processState);
2290        }
2291
2292        public void readFromParcel(Parcel source) {
2293            processName = source.readString();
2294            pid = source.readInt();
2295            uid = source.readInt();
2296            pkgList = source.readStringArray();
2297            flags = source.readInt();
2298            lastTrimLevel = source.readInt();
2299            importance = source.readInt();
2300            lru = source.readInt();
2301            importanceReasonCode = source.readInt();
2302            importanceReasonPid = source.readInt();
2303            importanceReasonComponent = ComponentName.readFromParcel(source);
2304            importanceReasonImportance = source.readInt();
2305            processState = source.readInt();
2306        }
2307
2308        public static final Creator<RunningAppProcessInfo> CREATOR =
2309            new Creator<RunningAppProcessInfo>() {
2310            public RunningAppProcessInfo createFromParcel(Parcel source) {
2311                return new RunningAppProcessInfo(source);
2312            }
2313            public RunningAppProcessInfo[] newArray(int size) {
2314                return new RunningAppProcessInfo[size];
2315            }
2316        };
2317
2318        private RunningAppProcessInfo(Parcel source) {
2319            readFromParcel(source);
2320        }
2321    }
2322
2323    /**
2324     * Returns a list of application processes installed on external media
2325     * that are running on the device.
2326     *
2327     * <p><b>Note: this method is only intended for debugging or building
2328     * a user-facing process management UI.</b></p>
2329     *
2330     * @return Returns a list of ApplicationInfo records, or null if none
2331     * This list ordering is not specified.
2332     * @hide
2333     */
2334    public List<ApplicationInfo> getRunningExternalApplications() {
2335        try {
2336            return ActivityManagerNative.getDefault().getRunningExternalApplications();
2337        } catch (RemoteException e) {
2338            return null;
2339        }
2340    }
2341
2342    /**
2343     * Sets the memory trim mode for a process and schedules a memory trim operation.
2344     *
2345     * <p><b>Note: this method is only intended for testing framework.</b></p>
2346     *
2347     * @return Returns true if successful.
2348     * @hide
2349     */
2350    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
2351        try {
2352            return ActivityManagerNative.getDefault().setProcessMemoryTrimLevel(process, userId,
2353                    level);
2354        } catch (RemoteException e) {
2355            return false;
2356        }
2357    }
2358
2359    /**
2360     * Returns a list of application processes that are running on the device.
2361     *
2362     * <p><b>Note: this method is only intended for debugging or building
2363     * a user-facing process management UI.</b></p>
2364     *
2365     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2366     * running processes (it will not return an empty list).  This list ordering is not
2367     * specified.
2368     */
2369    public List<RunningAppProcessInfo> getRunningAppProcesses() {
2370        try {
2371            return ActivityManagerNative.getDefault().getRunningAppProcesses();
2372        } catch (RemoteException e) {
2373            return null;
2374        }
2375    }
2376
2377    /**
2378     * Return the importance of a given package name, based on the processes that are
2379     * currently running.  The return value is one of the importance constants defined
2380     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
2381     * processes that this package has code running inside of.  If there are no processes
2382     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
2383     * @hide
2384     */
2385    @SystemApi
2386    public int getPackageImportance(String packageName) {
2387        try {
2388            int procState = ActivityManagerNative.getDefault().getPackageProcessState(packageName,
2389                    mContext.getOpPackageName());
2390            return RunningAppProcessInfo.procStateToImportance(procState);
2391        } catch (RemoteException e) {
2392            return RunningAppProcessInfo.IMPORTANCE_GONE;
2393        }
2394    }
2395
2396    /**
2397     * Return global memory state information for the calling process.  This
2398     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
2399     * only fields that will be filled in are
2400     * {@link RunningAppProcessInfo#pid},
2401     * {@link RunningAppProcessInfo#uid},
2402     * {@link RunningAppProcessInfo#lastTrimLevel},
2403     * {@link RunningAppProcessInfo#importance},
2404     * {@link RunningAppProcessInfo#lru}, and
2405     * {@link RunningAppProcessInfo#importanceReasonCode}.
2406     */
2407    static public void getMyMemoryState(RunningAppProcessInfo outState) {
2408        try {
2409            ActivityManagerNative.getDefault().getMyMemoryState(outState);
2410        } catch (RemoteException e) {
2411        }
2412    }
2413
2414    /**
2415     * Return information about the memory usage of one or more processes.
2416     *
2417     * <p><b>Note: this method is only intended for debugging or building
2418     * a user-facing process management UI.</b></p>
2419     *
2420     * @param pids The pids of the processes whose memory usage is to be
2421     * retrieved.
2422     * @return Returns an array of memory information, one for each
2423     * requested pid.
2424     */
2425    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2426        try {
2427            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2428        } catch (RemoteException e) {
2429            return null;
2430        }
2431    }
2432
2433    /**
2434     * @deprecated This is now just a wrapper for
2435     * {@link #killBackgroundProcesses(String)}; the previous behavior here
2436     * is no longer available to applications because it allows them to
2437     * break other applications by removing their alarms, stopping their
2438     * services, etc.
2439     */
2440    @Deprecated
2441    public void restartPackage(String packageName) {
2442        killBackgroundProcesses(packageName);
2443    }
2444
2445    /**
2446     * Have the system immediately kill all background processes associated
2447     * with the given package.  This is the same as the kernel killing those
2448     * processes to reclaim memory; the system will take care of restarting
2449     * these processes in the future as needed.
2450     *
2451     * <p>You must hold the permission
2452     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2453     * call this method.
2454     *
2455     * @param packageName The name of the package whose processes are to
2456     * be killed.
2457     */
2458    public void killBackgroundProcesses(String packageName) {
2459        try {
2460            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2461                    UserHandle.myUserId());
2462        } catch (RemoteException e) {
2463        }
2464    }
2465
2466    /**
2467     * Kills the specified UID.
2468     * @param uid The UID to kill.
2469     * @param reason The reason for the kill.
2470     *
2471     * @hide
2472     */
2473    @SystemApi
2474    @RequiresPermission(Manifest.permission.KILL_UID)
2475    public void killUid(int uid, String reason) {
2476        try {
2477            ActivityManagerNative.getDefault().killUid(uid, reason);
2478        } catch (RemoteException e) {
2479            Log.e(TAG, "Couldn't kill uid:" + uid, e);
2480        }
2481    }
2482
2483    /**
2484     * Have the system perform a force stop of everything associated with
2485     * the given application package.  All processes that share its uid
2486     * will be killed, all services it has running stopped, all activities
2487     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2488     * broadcast will be sent, so that any of its registered alarms can
2489     * be stopped, notifications removed, etc.
2490     *
2491     * <p>You must hold the permission
2492     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2493     * call this method.
2494     *
2495     * @param packageName The name of the package to be stopped.
2496     * @param userId The user for which the running package is to be stopped.
2497     *
2498     * @hide This is not available to third party applications due to
2499     * it allowing them to break other applications by stopping their
2500     * services, removing their alarms, etc.
2501     */
2502    public void forceStopPackageAsUser(String packageName, int userId) {
2503        try {
2504            ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
2505        } catch (RemoteException e) {
2506        }
2507    }
2508
2509    /**
2510     * @see #forceStopPackageAsUser(String, int)
2511     * @hide
2512     */
2513    public void forceStopPackage(String packageName) {
2514        forceStopPackageAsUser(packageName, UserHandle.myUserId());
2515    }
2516
2517    /**
2518     * Get the device configuration attributes.
2519     */
2520    public ConfigurationInfo getDeviceConfigurationInfo() {
2521        try {
2522            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2523        } catch (RemoteException e) {
2524        }
2525        return null;
2526    }
2527
2528    /**
2529     * Get the preferred density of icons for the launcher. This is used when
2530     * custom drawables are created (e.g., for shortcuts).
2531     *
2532     * @return density in terms of DPI
2533     */
2534    public int getLauncherLargeIconDensity() {
2535        final Resources res = mContext.getResources();
2536        final int density = res.getDisplayMetrics().densityDpi;
2537        final int sw = res.getConfiguration().smallestScreenWidthDp;
2538
2539        if (sw < 600) {
2540            // Smaller than approx 7" tablets, use the regular icon size.
2541            return density;
2542        }
2543
2544        switch (density) {
2545            case DisplayMetrics.DENSITY_LOW:
2546                return DisplayMetrics.DENSITY_MEDIUM;
2547            case DisplayMetrics.DENSITY_MEDIUM:
2548                return DisplayMetrics.DENSITY_HIGH;
2549            case DisplayMetrics.DENSITY_TV:
2550                return DisplayMetrics.DENSITY_XHIGH;
2551            case DisplayMetrics.DENSITY_HIGH:
2552                return DisplayMetrics.DENSITY_XHIGH;
2553            case DisplayMetrics.DENSITY_XHIGH:
2554                return DisplayMetrics.DENSITY_XXHIGH;
2555            case DisplayMetrics.DENSITY_XXHIGH:
2556                return DisplayMetrics.DENSITY_XHIGH * 2;
2557            default:
2558                // The density is some abnormal value.  Return some other
2559                // abnormal value that is a reasonable scaling of it.
2560                return (int)((density*1.5f)+.5f);
2561        }
2562    }
2563
2564    /**
2565     * Get the preferred launcher icon size. This is used when custom drawables
2566     * are created (e.g., for shortcuts).
2567     *
2568     * @return dimensions of square icons in terms of pixels
2569     */
2570    public int getLauncherLargeIconSize() {
2571        return getLauncherLargeIconSizeInner(mContext);
2572    }
2573
2574    static int getLauncherLargeIconSizeInner(Context context) {
2575        final Resources res = context.getResources();
2576        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2577        final int sw = res.getConfiguration().smallestScreenWidthDp;
2578
2579        if (sw < 600) {
2580            // Smaller than approx 7" tablets, use the regular icon size.
2581            return size;
2582        }
2583
2584        final int density = res.getDisplayMetrics().densityDpi;
2585
2586        switch (density) {
2587            case DisplayMetrics.DENSITY_LOW:
2588                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2589            case DisplayMetrics.DENSITY_MEDIUM:
2590                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2591            case DisplayMetrics.DENSITY_TV:
2592                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2593            case DisplayMetrics.DENSITY_HIGH:
2594                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2595            case DisplayMetrics.DENSITY_XHIGH:
2596                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2597            case DisplayMetrics.DENSITY_XXHIGH:
2598                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2599            default:
2600                // The density is some abnormal value.  Return some other
2601                // abnormal value that is a reasonable scaling of it.
2602                return (int)((size*1.5f) + .5f);
2603        }
2604    }
2605
2606    /**
2607     * Returns "true" if the user interface is currently being messed with
2608     * by a monkey.
2609     */
2610    public static boolean isUserAMonkey() {
2611        try {
2612            return ActivityManagerNative.getDefault().isUserAMonkey();
2613        } catch (RemoteException e) {
2614        }
2615        return false;
2616    }
2617
2618    /**
2619     * Returns "true" if device is running in a test harness.
2620     */
2621    public static boolean isRunningInTestHarness() {
2622        return SystemProperties.getBoolean("ro.test_harness", false);
2623    }
2624
2625    /**
2626     * Returns the launch count of each installed package.
2627     *
2628     * @hide
2629     */
2630    /*public Map<String, Integer> getAllPackageLaunchCounts() {
2631        try {
2632            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2633                    ServiceManager.getService("usagestats"));
2634            if (usageStatsService == null) {
2635                return new HashMap<String, Integer>();
2636            }
2637
2638            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2639                    ActivityThread.currentPackageName());
2640            if (allPkgUsageStats == null) {
2641                return new HashMap<String, Integer>();
2642            }
2643
2644            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2645            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2646                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2647            }
2648
2649            return launchCounts;
2650        } catch (RemoteException e) {
2651            Log.w(TAG, "Could not query launch counts", e);
2652            return new HashMap<String, Integer>();
2653        }
2654    }*/
2655
2656    /** @hide */
2657    public static int checkComponentPermission(String permission, int uid,
2658            int owningUid, boolean exported) {
2659        // Root, system server get to do everything.
2660        final int appId = UserHandle.getAppId(uid);
2661        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
2662            return PackageManager.PERMISSION_GRANTED;
2663        }
2664        // Isolated processes don't get any permissions.
2665        if (UserHandle.isIsolated(uid)) {
2666            return PackageManager.PERMISSION_DENIED;
2667        }
2668        // If there is a uid that owns whatever is being accessed, it has
2669        // blanket access to it regardless of the permissions it requires.
2670        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2671            return PackageManager.PERMISSION_GRANTED;
2672        }
2673        // If the target is not exported, then nobody else can get to it.
2674        if (!exported) {
2675            /*
2676            RuntimeException here = new RuntimeException("here");
2677            here.fillInStackTrace();
2678            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2679                    here);
2680            */
2681            return PackageManager.PERMISSION_DENIED;
2682        }
2683        if (permission == null) {
2684            return PackageManager.PERMISSION_GRANTED;
2685        }
2686        try {
2687            return AppGlobals.getPackageManager()
2688                    .checkUidPermission(permission, uid);
2689        } catch (RemoteException e) {
2690            // Should never happen, but if it does... deny!
2691            Slog.e(TAG, "PackageManager is dead?!?", e);
2692        }
2693        return PackageManager.PERMISSION_DENIED;
2694    }
2695
2696    /** @hide */
2697    public static int checkUidPermission(String permission, int uid) {
2698        try {
2699            return AppGlobals.getPackageManager()
2700                    .checkUidPermission(permission, uid);
2701        } catch (RemoteException e) {
2702            // Should never happen, but if it does... deny!
2703            Slog.e(TAG, "PackageManager is dead?!?", e);
2704        }
2705        return PackageManager.PERMISSION_DENIED;
2706    }
2707
2708    /**
2709     * @hide
2710     * Helper for dealing with incoming user arguments to system service calls.
2711     * Takes care of checking permissions and converting USER_CURRENT to the
2712     * actual current user.
2713     *
2714     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2715     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2716     * @param userId The user id argument supplied by the caller -- this is the user
2717     * they want to run as.
2718     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2719     * to get a USER_ALL returned and deal with it correctly.  If false,
2720     * an exception will be thrown if USER_ALL is supplied.
2721     * @param requireFull If true, the caller must hold
2722     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2723     * different user than their current process; otherwise they must hold
2724     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2725     * @param name Optional textual name of the incoming call; only for generating error messages.
2726     * @param callerPackage Optional package name of caller; only for error messages.
2727     *
2728     * @return Returns the user ID that the call should run as.  Will always be a concrete
2729     * user number, unless <var>allowAll</var> is true in which case it could also be
2730     * USER_ALL.
2731     */
2732    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2733            boolean allowAll, boolean requireFull, String name, String callerPackage) {
2734        if (UserHandle.getUserId(callingUid) == userId) {
2735            return userId;
2736        }
2737        try {
2738            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2739                    callingUid, userId, allowAll, requireFull, name, callerPackage);
2740        } catch (RemoteException e) {
2741            throw new SecurityException("Failed calling activity manager", e);
2742        }
2743    }
2744
2745    /**
2746     * Gets the userId of the current foreground user. Requires system permissions.
2747     * @hide
2748     */
2749    @SystemApi
2750    public static int getCurrentUser() {
2751        UserInfo ui;
2752        try {
2753            ui = ActivityManagerNative.getDefault().getCurrentUser();
2754            return ui != null ? ui.id : 0;
2755        } catch (RemoteException e) {
2756            return 0;
2757        }
2758    }
2759
2760    /**
2761     * @param userid the user's id. Zero indicates the default user.
2762     * @hide
2763     */
2764    public boolean switchUser(int userid) {
2765        try {
2766            return ActivityManagerNative.getDefault().switchUser(userid);
2767        } catch (RemoteException e) {
2768            return false;
2769        }
2770    }
2771
2772    /**
2773     * Return whether the given user is actively running.  This means that
2774     * the user is in the "started" state, not "stopped" -- it is currently
2775     * allowed to run code through scheduled alarms, receiving broadcasts,
2776     * etc.  A started user may be either the current foreground user or a
2777     * background user; the result here does not distinguish between the two.
2778     * @param userid the user's id. Zero indicates the default user.
2779     * @hide
2780     */
2781    public boolean isUserRunning(int userid) {
2782        try {
2783            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2784        } catch (RemoteException e) {
2785            return false;
2786        }
2787    }
2788
2789    /**
2790     * Perform a system dump of various state associated with the given application
2791     * package name.  This call blocks while the dump is being performed, so should
2792     * not be done on a UI thread.  The data will be written to the given file
2793     * descriptor as text.  An application must hold the
2794     * {@link android.Manifest.permission#DUMP} permission to make this call.
2795     * @param fd The file descriptor that the dump should be written to.  The file
2796     * descriptor is <em>not</em> closed by this function; the caller continues to
2797     * own it.
2798     * @param packageName The name of the package that is to be dumped.
2799     */
2800    public void dumpPackageState(FileDescriptor fd, String packageName) {
2801        dumpPackageStateStatic(fd, packageName);
2802    }
2803
2804    /**
2805     * @hide
2806     */
2807    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2808        FileOutputStream fout = new FileOutputStream(fd);
2809        PrintWriter pw = new FastPrintWriter(fout);
2810        dumpService(pw, fd, "package", new String[] { packageName });
2811        pw.println();
2812        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2813                "-a", "package", packageName });
2814        pw.println();
2815        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
2816        pw.println();
2817        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
2818        pw.println();
2819        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2820        pw.println();
2821        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2822        pw.flush();
2823    }
2824
2825    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2826        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2827        IBinder service = ServiceManager.checkService(name);
2828        if (service == null) {
2829            pw.println("  (Service not found)");
2830            return;
2831        }
2832        TransferPipe tp = null;
2833        try {
2834            pw.flush();
2835            tp = new TransferPipe();
2836            tp.setBufferPrefix("  ");
2837            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
2838            tp.go(fd, 10000);
2839        } catch (Throwable e) {
2840            if (tp != null) {
2841                tp.kill();
2842            }
2843            pw.println("Failure dumping service:");
2844            e.printStackTrace(pw);
2845        }
2846    }
2847
2848    /**
2849     * Request that the system start watching for the calling process to exceed a pss
2850     * size as given here.  Once called, the system will look for any occasions where it
2851     * sees the associated process with a larger pss size and, when this happens, automatically
2852     * pull a heap dump from it and allow the user to share the data.  Note that this request
2853     * continues running even if the process is killed and restarted.  To remove the watch,
2854     * use {@link #clearWatchHeapLimit()}.
2855     *
2856     * <p>This API only work if the calling process has been marked as
2857     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
2858     * (userdebug or eng) build.</p>
2859     *
2860     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
2861     * handle heap limit reports themselves.</p>
2862     *
2863     * @param pssSize The size in bytes to set the limit at.
2864     */
2865    public void setWatchHeapLimit(long pssSize) {
2866        try {
2867            ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, pssSize,
2868                    mContext.getPackageName());
2869        } catch (RemoteException e) {
2870        }
2871    }
2872
2873    /**
2874     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
2875     * If your package has an activity handling this action, it will be launched with the
2876     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
2877     * match the activty must support this action and a MIME type of "*&#47;*".
2878     */
2879    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
2880
2881    /**
2882     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
2883     */
2884    public void clearWatchHeapLimit() {
2885        try {
2886            ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, 0, null);
2887        } catch (RemoteException e) {
2888        }
2889    }
2890
2891    /**
2892     * @hide
2893     */
2894    public void startLockTaskMode(int taskId) {
2895        try {
2896            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
2897        } catch (RemoteException e) {
2898        }
2899    }
2900
2901    /**
2902     * @hide
2903     */
2904    public void stopLockTaskMode() {
2905        try {
2906            ActivityManagerNative.getDefault().stopLockTaskMode();
2907        } catch (RemoteException e) {
2908        }
2909    }
2910
2911    /**
2912     * Return whether currently in lock task mode.  When in this mode
2913     * no new tasks can be created or switched to.
2914     *
2915     * @see Activity#startLockTask()
2916     *
2917     * @deprecated Use {@link #getLockTaskModeState} instead.
2918     */
2919    public boolean isInLockTaskMode() {
2920        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2921    }
2922
2923    /**
2924     * Return the current state of task locking. The three possible outcomes
2925     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
2926     * and {@link #LOCK_TASK_MODE_PINNED}.
2927     *
2928     * @see Activity#startLockTask()
2929     */
2930    public int getLockTaskModeState() {
2931        try {
2932            return ActivityManagerNative.getDefault().getLockTaskModeState();
2933        } catch (RemoteException e) {
2934            return ActivityManager.LOCK_TASK_MODE_NONE;
2935        }
2936    }
2937
2938    /**
2939     * The AppTask allows you to manage your own application's tasks.
2940     * See {@link android.app.ActivityManager#getAppTasks()}
2941     */
2942    public static class AppTask {
2943        private IAppTask mAppTaskImpl;
2944
2945        /** @hide */
2946        public AppTask(IAppTask task) {
2947            mAppTaskImpl = task;
2948        }
2949
2950        /**
2951         * Finishes all activities in this task and removes it from the recent tasks list.
2952         */
2953        public void finishAndRemoveTask() {
2954            try {
2955                mAppTaskImpl.finishAndRemoveTask();
2956            } catch (RemoteException e) {
2957                Slog.e(TAG, "Invalid AppTask", e);
2958            }
2959        }
2960
2961        /**
2962         * Get the RecentTaskInfo associated with this task.
2963         *
2964         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
2965         */
2966        public RecentTaskInfo getTaskInfo() {
2967            try {
2968                return mAppTaskImpl.getTaskInfo();
2969            } catch (RemoteException e) {
2970                Slog.e(TAG, "Invalid AppTask", e);
2971                return null;
2972            }
2973        }
2974
2975        /**
2976         * Bring this task to the foreground.  If it contains activities, they will be
2977         * brought to the foreground with it and their instances re-created if needed.
2978         * If it doesn't contain activities, the root activity of the task will be
2979         * re-launched.
2980         */
2981        public void moveToFront() {
2982            try {
2983                mAppTaskImpl.moveToFront();
2984            } catch (RemoteException e) {
2985                Slog.e(TAG, "Invalid AppTask", e);
2986            }
2987        }
2988
2989        /**
2990         * Start an activity in this task.  Brings the task to the foreground.  If this task
2991         * is not currently active (that is, its id < 0), then a new activity for the given
2992         * Intent will be launched as the root of the task and the task brought to the
2993         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
2994         * an activity to launch in a new task, then a new activity for the given Intent will
2995         * be launched on top of the task and the task brought to the foreground.  If this
2996         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
2997         * or would otherwise be launched in to a new task, then the activity not launched but
2998         * this task be brought to the foreground and a new intent delivered to the top
2999         * activity if appropriate.
3000         *
3001         * <p>In other words, you generally want to use an Intent here that does not specify
3002         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
3003         * and let the system do the right thing.</p>
3004         *
3005         * @param intent The Intent describing the new activity to be launched on the task.
3006         * @param options Optional launch options.
3007         *
3008         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
3009         */
3010        public void startActivity(Context context, Intent intent, Bundle options) {
3011            ActivityThread thread = ActivityThread.currentActivityThread();
3012            thread.getInstrumentation().execStartActivityFromAppTask(context,
3013                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
3014        }
3015
3016        /**
3017         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
3018         * Intent of this AppTask.
3019         *
3020         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
3021         * be set; otherwise, it will be cleared.
3022         */
3023        public void setExcludeFromRecents(boolean exclude) {
3024            try {
3025                mAppTaskImpl.setExcludeFromRecents(exclude);
3026            } catch (RemoteException e) {
3027                Slog.e(TAG, "Invalid AppTask", e);
3028            }
3029        }
3030    }
3031}
3032