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