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