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