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