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