ActivityManager.java revision c0ffce5ddd6446f1d46a49cdfaeda4a2ce408e1d
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 last time this task was active.
681         * @hide
682         */
683        public long lastActiveTime;
684
685        /**
686         * The recent activity values for the highest activity in the stack to have set the values.
687         * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
688         *
689         * @hide
690         */
691        public TaskDescription taskDescription;
692
693        public RecentTaskInfo() {
694        }
695
696        @Override
697        public int describeContents() {
698            return 0;
699        }
700
701        @Override
702        public void writeToParcel(Parcel dest, int flags) {
703            dest.writeInt(id);
704            dest.writeInt(persistentId);
705            if (baseIntent != null) {
706                dest.writeInt(1);
707                baseIntent.writeToParcel(dest, 0);
708            } else {
709                dest.writeInt(0);
710            }
711            ComponentName.writeToParcel(origActivity, dest);
712            TextUtils.writeToParcel(description, dest,
713                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
714            if (taskDescription != null) {
715                dest.writeInt(1);
716                taskDescription.writeToParcel(dest, 0);
717            } else {
718                dest.writeInt(0);
719            }
720            dest.writeInt(stackId);
721            dest.writeInt(userId);
722            dest.writeLong(lastActiveTime);
723        }
724
725        public void readFromParcel(Parcel source) {
726            id = source.readInt();
727            persistentId = source.readInt();
728            baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
729            origActivity = ComponentName.readFromParcel(source);
730            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
731            taskDescription = source.readInt() > 0 ?
732                    TaskDescription.CREATOR.createFromParcel(source) : null;
733            stackId = source.readInt();
734            userId = source.readInt();
735            lastActiveTime = source.readLong();
736        }
737
738        public static final Creator<RecentTaskInfo> CREATOR
739                = new Creator<RecentTaskInfo>() {
740            public RecentTaskInfo createFromParcel(Parcel source) {
741                return new RecentTaskInfo(source);
742            }
743            public RecentTaskInfo[] newArray(int size) {
744                return new RecentTaskInfo[size];
745            }
746        };
747
748        private RecentTaskInfo(Parcel source) {
749            readFromParcel(source);
750        }
751    }
752
753    /**
754     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
755     * that have set their
756     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
757     */
758    public static final int RECENT_WITH_EXCLUDED = 0x0001;
759
760    /**
761     * Provides a list that does not contain any
762     * recent tasks that currently are not available to the user.
763     */
764    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
765
766    /**
767     * Provides a list that contains recent tasks for all
768     * profiles of a user.
769     * @hide
770     */
771    public static final int RECENT_INCLUDE_PROFILES = 0x0004;
772
773    /**
774     * <p></p>Return a list of the tasks that the user has recently launched, with
775     * the most recent being first and older ones after in order.
776     *
777     * <p><b>Note: this method is only intended for debugging and presenting
778     * task management user interfaces</b>.  This should never be used for
779     * core logic in an application, such as deciding between different
780     * behaviors based on the information found here.  Such uses are
781     * <em>not</em> supported, and will likely break in the future.  For
782     * example, if multiple applications can be actively running at the
783     * same time, assumptions made about the meaning of the data here for
784     * purposes of control flow will be incorrect.</p>
785     *
786     * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method is
787     * no longer available to third party applications: as the introduction of
788     * document-centric recents means
789     * it can leak personal information to the caller.  For backwards compatibility,
790     * it will still return a small subset of its data: at least the caller's
791     * own tasks (though see {@link #getAppTasks()} for the correct supported
792     * way to retrieve that information), and possibly some other tasks
793     * such as home that are known to not be sensitive.
794     *
795     * @param maxNum The maximum number of entries to return in the list.  The
796     * actual number returned may be smaller, depending on how many tasks the
797     * user has started and the maximum number the system can remember.
798     * @param flags Information about what to return.  May be any combination
799     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
800     *
801     * @return Returns a list of RecentTaskInfo records describing each of
802     * the recent tasks.
803     *
804     * @throws SecurityException Throws SecurityException if the caller does
805     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
806     */
807    @Deprecated
808    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
809            throws SecurityException {
810        try {
811            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
812                    flags, UserHandle.myUserId());
813        } catch (RemoteException e) {
814            // System dead, we will be dead too soon!
815            return null;
816        }
817    }
818
819    /**
820     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
821     * specific user. It requires holding
822     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
823     * @param maxNum The maximum number of entries to return in the list.  The
824     * actual number returned may be smaller, depending on how many tasks the
825     * user has started and the maximum number the system can remember.
826     * @param flags Information about what to return.  May be any combination
827     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
828     *
829     * @return Returns a list of RecentTaskInfo records describing each of
830     * the recent tasks.
831     *
832     * @throws SecurityException Throws SecurityException if the caller does
833     * not hold the {@link android.Manifest.permission#GET_TASKS} or the
834     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
835     * @hide
836     */
837    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
838            throws SecurityException {
839        try {
840            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
841                    flags, userId);
842        } catch (RemoteException e) {
843            // System dead, we will be dead too soon!
844            return null;
845        }
846    }
847
848    /**
849     * Information you can retrieve about a particular task that is currently
850     * "running" in the system.  Note that a running task does not mean the
851     * given task actually has a process it is actively running in; it simply
852     * means that the user has gone to it and never closed it, but currently
853     * the system may have killed its process and is only holding on to its
854     * last state in order to restart it when the user returns.
855     */
856    public static class RunningTaskInfo implements Parcelable {
857        /**
858         * A unique identifier for this task.
859         */
860        public int id;
861
862        /**
863         * The component launched as the first activity in the task.  This can
864         * be considered the "application" of this task.
865         */
866        public ComponentName baseActivity;
867
868        /**
869         * The activity component at the top of the history stack of the task.
870         * This is what the user is currently doing.
871         */
872        public ComponentName topActivity;
873
874        /**
875         * Thumbnail representation of the task's current state.  Currently
876         * always null.
877         */
878        public Bitmap thumbnail;
879
880        /**
881         * Description of the task's current state.
882         */
883        public CharSequence description;
884
885        /**
886         * Number of activities in this task.
887         */
888        public int numActivities;
889
890        /**
891         * Number of activities that are currently running (not stopped
892         * and persisted) in this task.
893         */
894        public int numRunning;
895
896        /**
897         * Last time task was run. For sorting.
898         * @hide
899         */
900        public long lastActiveTime;
901
902        public RunningTaskInfo() {
903        }
904
905        public int describeContents() {
906            return 0;
907        }
908
909        public void writeToParcel(Parcel dest, int flags) {
910            dest.writeInt(id);
911            ComponentName.writeToParcel(baseActivity, dest);
912            ComponentName.writeToParcel(topActivity, dest);
913            if (thumbnail != null) {
914                dest.writeInt(1);
915                thumbnail.writeToParcel(dest, 0);
916            } else {
917                dest.writeInt(0);
918            }
919            TextUtils.writeToParcel(description, dest,
920                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
921            dest.writeInt(numActivities);
922            dest.writeInt(numRunning);
923        }
924
925        public void readFromParcel(Parcel source) {
926            id = source.readInt();
927            baseActivity = ComponentName.readFromParcel(source);
928            topActivity = ComponentName.readFromParcel(source);
929            if (source.readInt() != 0) {
930                thumbnail = Bitmap.CREATOR.createFromParcel(source);
931            } else {
932                thumbnail = null;
933            }
934            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
935            numActivities = source.readInt();
936            numRunning = source.readInt();
937        }
938
939        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
940            public RunningTaskInfo createFromParcel(Parcel source) {
941                return new RunningTaskInfo(source);
942            }
943            public RunningTaskInfo[] newArray(int size) {
944                return new RunningTaskInfo[size];
945            }
946        };
947
948        private RunningTaskInfo(Parcel source) {
949            readFromParcel(source);
950        }
951    }
952
953    /**
954     * Get the list of tasks associated with the calling application.
955     *
956     * @return The list of tasks associated with the application making this call.
957     * @throws SecurityException
958     */
959    public List<ActivityManager.AppTask> getAppTasks() {
960        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
961        List<IAppTask> appTasks;
962        try {
963            appTasks = ActivityManagerNative.getDefault().getAppTasks();
964        } catch (RemoteException e) {
965            // System dead, we will be dead too soon!
966            return null;
967        }
968        int numAppTasks = appTasks.size();
969        for (int i = 0; i < numAppTasks; i++) {
970            tasks.add(new AppTask(appTasks.get(i)));
971        }
972        return tasks;
973    }
974
975    /**
976     * Return a list of the tasks that are currently running, with
977     * the most recent being first and older ones after in order.  Note that
978     * "running" does not mean any of the task's code is currently loaded or
979     * activity -- the task may have been frozen by the system, so that it
980     * can be restarted in its previous state when next brought to the
981     * foreground.
982     *
983     * <p><b>Note: this method is only intended for debugging and presenting
984     * task management user interfaces</b>.  This should never be used for
985     * core logic in an application, such as deciding between different
986     * behaviors based on the information found here.  Such uses are
987     * <em>not</em> supported, and will likely break in the future.  For
988     * example, if multiple applications can be actively running at the
989     * same time, assumptions made about the meaning of the data here for
990     * purposes of control flow will be incorrect.</p>
991     *
992     * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method
993     * is no longer available to third party
994     * applications: the introduction of document-centric recents means
995     * it can leak person information to the caller.  For backwards compatibility,
996     * it will still retu rn a small subset of its data: at least the caller's
997     * own tasks, and possibly some other tasks
998     * such as home that are known to not be sensitive.
999     *
1000     * @param maxNum The maximum number of entries to return in the list.  The
1001     * actual number returned may be smaller, depending on how many tasks the
1002     * user has started.
1003     *
1004     * @return Returns a list of RunningTaskInfo records describing each of
1005     * the running tasks.
1006     *
1007     * @throws SecurityException Throws SecurityException if the caller does
1008     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
1009     */
1010    @Deprecated
1011    public List<RunningTaskInfo> getRunningTasks(int maxNum)
1012            throws SecurityException {
1013        try {
1014            return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1015        } catch (RemoteException e) {
1016            // System dead, we will be dead too soon!
1017            return null;
1018        }
1019    }
1020
1021    /**
1022     * If set, the process of the root activity of the task will be killed
1023     * as part of removing the task.
1024     * @hide
1025     */
1026    public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
1027
1028    /**
1029     * Completely remove the given task.
1030     *
1031     * @param taskId Identifier of the task to be removed.
1032     * @param flags Additional operational flags.  May be 0 or
1033     * {@link #REMOVE_TASK_KILL_PROCESS}.
1034     * @return Returns true if the given task was found and removed.
1035     *
1036     * @hide
1037     */
1038    public boolean removeTask(int taskId, int flags)
1039            throws SecurityException {
1040        try {
1041            return ActivityManagerNative.getDefault().removeTask(taskId, flags);
1042        } catch (RemoteException e) {
1043            // System dead, we will be dead too soon!
1044            return false;
1045        }
1046    }
1047
1048    /** @hide */
1049    public static class TaskThumbnail implements Parcelable {
1050        public Bitmap mainThumbnail;
1051        public ParcelFileDescriptor thumbnailFileDescriptor;
1052
1053        public TaskThumbnail() {
1054        }
1055
1056        public int describeContents() {
1057            if (thumbnailFileDescriptor != null) {
1058                return thumbnailFileDescriptor.describeContents();
1059            }
1060            return 0;
1061        }
1062
1063        public void writeToParcel(Parcel dest, int flags) {
1064            if (mainThumbnail != null) {
1065                dest.writeInt(1);
1066                mainThumbnail.writeToParcel(dest, 0);
1067            } else {
1068                dest.writeInt(0);
1069            }
1070            if (thumbnailFileDescriptor != null) {
1071                dest.writeInt(1);
1072                thumbnailFileDescriptor.writeToParcel(dest, 0);
1073            } else {
1074                dest.writeInt(0);
1075            }
1076        }
1077
1078        public void readFromParcel(Parcel source) {
1079            if (source.readInt() != 0) {
1080                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1081            } else {
1082                mainThumbnail = null;
1083            }
1084            if (source.readInt() != 0) {
1085                thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1086            } else {
1087                thumbnailFileDescriptor = null;
1088            }
1089        }
1090
1091        public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1092            public TaskThumbnail createFromParcel(Parcel source) {
1093                return new TaskThumbnail(source);
1094            }
1095            public TaskThumbnail[] newArray(int size) {
1096                return new TaskThumbnail[size];
1097            }
1098        };
1099
1100        private TaskThumbnail(Parcel source) {
1101            readFromParcel(source);
1102        }
1103    }
1104
1105    /** @hide */
1106    public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1107        try {
1108            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1109        } catch (RemoteException e) {
1110            // System dead, we will be dead too soon!
1111            return null;
1112        }
1113    }
1114
1115    /** @hide */
1116    public boolean isInHomeStack(int taskId) {
1117        try {
1118            return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1119        } catch (RemoteException e) {
1120            // System dead, we will be dead too soon!
1121            return false;
1122        }
1123    }
1124
1125    /**
1126     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1127     * activity along with the task, so it is positioned immediately behind
1128     * the task.
1129     */
1130    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1131
1132    /**
1133     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1134     * user-instigated action, so the current activity will not receive a
1135     * hint that the user is leaving.
1136     */
1137    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1138
1139    /**
1140     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1141     * with a null options argument.
1142     *
1143     * @param taskId The identifier of the task to be moved, as found in
1144     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1145     * @param flags Additional operational flags, 0 or more of
1146     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1147     */
1148    public void moveTaskToFront(int taskId, int flags) {
1149        moveTaskToFront(taskId, flags, null);
1150    }
1151
1152    /**
1153     * Ask that the task associated with a given task ID be moved to the
1154     * front of the stack, so it is now visible to the user.  Requires that
1155     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1156     * or a SecurityException will be thrown.
1157     *
1158     * @param taskId The identifier of the task to be moved, as found in
1159     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1160     * @param flags Additional operational flags, 0 or more of
1161     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1162     * @param options Additional options for the operation, either null or
1163     * as per {@link Context#startActivity(Intent, android.os.Bundle)
1164     * Context.startActivity(Intent, Bundle)}.
1165     */
1166    public void moveTaskToFront(int taskId, int flags, Bundle options) {
1167        try {
1168            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1169        } catch (RemoteException e) {
1170            // System dead, we will be dead too soon!
1171        }
1172    }
1173
1174    /**
1175     * Information you can retrieve about a particular Service that is
1176     * currently running in the system.
1177     */
1178    public static class RunningServiceInfo implements Parcelable {
1179        /**
1180         * The service component.
1181         */
1182        public ComponentName service;
1183
1184        /**
1185         * If non-zero, this is the process the service is running in.
1186         */
1187        public int pid;
1188
1189        /**
1190         * The UID that owns this service.
1191         */
1192        public int uid;
1193
1194        /**
1195         * The name of the process this service runs in.
1196         */
1197        public String process;
1198
1199        /**
1200         * Set to true if the service has asked to run as a foreground process.
1201         */
1202        public boolean foreground;
1203
1204        /**
1205         * The time when the service was first made active, either by someone
1206         * starting or binding to it.  This
1207         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1208         */
1209        public long activeSince;
1210
1211        /**
1212         * Set to true if this service has been explicitly started.
1213         */
1214        public boolean started;
1215
1216        /**
1217         * Number of clients connected to the service.
1218         */
1219        public int clientCount;
1220
1221        /**
1222         * Number of times the service's process has crashed while the service
1223         * is running.
1224         */
1225        public int crashCount;
1226
1227        /**
1228         * The time when there was last activity in the service (either
1229         * explicit requests to start it or clients binding to it).  This
1230         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1231         */
1232        public long lastActivityTime;
1233
1234        /**
1235         * If non-zero, this service is not currently running, but scheduled to
1236         * restart at the given time.
1237         */
1238        public long restarting;
1239
1240        /**
1241         * Bit for {@link #flags}: set if this service has been
1242         * explicitly started.
1243         */
1244        public static final int FLAG_STARTED = 1<<0;
1245
1246        /**
1247         * Bit for {@link #flags}: set if the service has asked to
1248         * run as a foreground process.
1249         */
1250        public static final int FLAG_FOREGROUND = 1<<1;
1251
1252        /**
1253         * Bit for {@link #flags): set if the service is running in a
1254         * core system process.
1255         */
1256        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1257
1258        /**
1259         * Bit for {@link #flags): set if the service is running in a
1260         * persistent process.
1261         */
1262        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1263
1264        /**
1265         * Running flags.
1266         */
1267        public int flags;
1268
1269        /**
1270         * For special services that are bound to by system code, this is
1271         * the package that holds the binding.
1272         */
1273        public String clientPackage;
1274
1275        /**
1276         * For special services that are bound to by system code, this is
1277         * a string resource providing a user-visible label for who the
1278         * client is.
1279         */
1280        public int clientLabel;
1281
1282        public RunningServiceInfo() {
1283        }
1284
1285        public int describeContents() {
1286            return 0;
1287        }
1288
1289        public void writeToParcel(Parcel dest, int flags) {
1290            ComponentName.writeToParcel(service, dest);
1291            dest.writeInt(pid);
1292            dest.writeInt(uid);
1293            dest.writeString(process);
1294            dest.writeInt(foreground ? 1 : 0);
1295            dest.writeLong(activeSince);
1296            dest.writeInt(started ? 1 : 0);
1297            dest.writeInt(clientCount);
1298            dest.writeInt(crashCount);
1299            dest.writeLong(lastActivityTime);
1300            dest.writeLong(restarting);
1301            dest.writeInt(this.flags);
1302            dest.writeString(clientPackage);
1303            dest.writeInt(clientLabel);
1304        }
1305
1306        public void readFromParcel(Parcel source) {
1307            service = ComponentName.readFromParcel(source);
1308            pid = source.readInt();
1309            uid = source.readInt();
1310            process = source.readString();
1311            foreground = source.readInt() != 0;
1312            activeSince = source.readLong();
1313            started = source.readInt() != 0;
1314            clientCount = source.readInt();
1315            crashCount = source.readInt();
1316            lastActivityTime = source.readLong();
1317            restarting = source.readLong();
1318            flags = source.readInt();
1319            clientPackage = source.readString();
1320            clientLabel = source.readInt();
1321        }
1322
1323        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1324            public RunningServiceInfo createFromParcel(Parcel source) {
1325                return new RunningServiceInfo(source);
1326            }
1327            public RunningServiceInfo[] newArray(int size) {
1328                return new RunningServiceInfo[size];
1329            }
1330        };
1331
1332        private RunningServiceInfo(Parcel source) {
1333            readFromParcel(source);
1334        }
1335    }
1336
1337    /**
1338     * Return a list of the services that are currently running.
1339     *
1340     * <p><b>Note: this method is only intended for debugging or implementing
1341     * service management type user interfaces.</b></p>
1342     *
1343     * @param maxNum The maximum number of entries to return in the list.  The
1344     * actual number returned may be smaller, depending on how many services
1345     * are running.
1346     *
1347     * @return Returns a list of RunningServiceInfo records describing each of
1348     * the running tasks.
1349     */
1350    public List<RunningServiceInfo> getRunningServices(int maxNum)
1351            throws SecurityException {
1352        try {
1353            return ActivityManagerNative.getDefault()
1354                    .getServices(maxNum, 0);
1355        } catch (RemoteException e) {
1356            // System dead, we will be dead too soon!
1357            return null;
1358        }
1359    }
1360
1361    /**
1362     * Returns a PendingIntent you can start to show a control panel for the
1363     * given running service.  If the service does not have a control panel,
1364     * null is returned.
1365     */
1366    public PendingIntent getRunningServiceControlPanel(ComponentName service)
1367            throws SecurityException {
1368        try {
1369            return ActivityManagerNative.getDefault()
1370                    .getRunningServiceControlPanel(service);
1371        } catch (RemoteException e) {
1372            // System dead, we will be dead too soon!
1373            return null;
1374        }
1375    }
1376
1377    /**
1378     * Information you can retrieve about the available memory through
1379     * {@link ActivityManager#getMemoryInfo}.
1380     */
1381    public static class MemoryInfo implements Parcelable {
1382        /**
1383         * The available memory on the system.  This number should not
1384         * be considered absolute: due to the nature of the kernel, a significant
1385         * portion of this memory is actually in use and needed for the overall
1386         * system to run well.
1387         */
1388        public long availMem;
1389
1390        /**
1391         * The total memory accessible by the kernel.  This is basically the
1392         * RAM size of the device, not including below-kernel fixed allocations
1393         * like DMA buffers, RAM for the baseband CPU, etc.
1394         */
1395        public long totalMem;
1396
1397        /**
1398         * The threshold of {@link #availMem} at which we consider memory to be
1399         * low and start killing background services and other non-extraneous
1400         * processes.
1401         */
1402        public long threshold;
1403
1404        /**
1405         * Set to true if the system considers itself to currently be in a low
1406         * memory situation.
1407         */
1408        public boolean lowMemory;
1409
1410        /** @hide */
1411        public long hiddenAppThreshold;
1412        /** @hide */
1413        public long secondaryServerThreshold;
1414        /** @hide */
1415        public long visibleAppThreshold;
1416        /** @hide */
1417        public long foregroundAppThreshold;
1418
1419        public MemoryInfo() {
1420        }
1421
1422        public int describeContents() {
1423            return 0;
1424        }
1425
1426        public void writeToParcel(Parcel dest, int flags) {
1427            dest.writeLong(availMem);
1428            dest.writeLong(totalMem);
1429            dest.writeLong(threshold);
1430            dest.writeInt(lowMemory ? 1 : 0);
1431            dest.writeLong(hiddenAppThreshold);
1432            dest.writeLong(secondaryServerThreshold);
1433            dest.writeLong(visibleAppThreshold);
1434            dest.writeLong(foregroundAppThreshold);
1435        }
1436
1437        public void readFromParcel(Parcel source) {
1438            availMem = source.readLong();
1439            totalMem = source.readLong();
1440            threshold = source.readLong();
1441            lowMemory = source.readInt() != 0;
1442            hiddenAppThreshold = source.readLong();
1443            secondaryServerThreshold = source.readLong();
1444            visibleAppThreshold = source.readLong();
1445            foregroundAppThreshold = source.readLong();
1446        }
1447
1448        public static final Creator<MemoryInfo> CREATOR
1449                = new Creator<MemoryInfo>() {
1450            public MemoryInfo createFromParcel(Parcel source) {
1451                return new MemoryInfo(source);
1452            }
1453            public MemoryInfo[] newArray(int size) {
1454                return new MemoryInfo[size];
1455            }
1456        };
1457
1458        private MemoryInfo(Parcel source) {
1459            readFromParcel(source);
1460        }
1461    }
1462
1463    /**
1464     * Return general information about the memory state of the system.  This
1465     * can be used to help decide how to manage your own memory, though note
1466     * that polling is not recommended and
1467     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1468     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1469     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1470     * level of your process as needed, which gives a better hint for how to
1471     * manage its memory.
1472     */
1473    public void getMemoryInfo(MemoryInfo outInfo) {
1474        try {
1475            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1476        } catch (RemoteException e) {
1477        }
1478    }
1479
1480    /**
1481     * Information you can retrieve about an ActivityStack in the system.
1482     * @hide
1483     */
1484    public static class StackInfo implements Parcelable {
1485        public int stackId;
1486        public Rect bounds = new Rect();
1487        public int[] taskIds;
1488        public String[] taskNames;
1489        public int displayId;
1490
1491        @Override
1492        public int describeContents() {
1493            return 0;
1494        }
1495
1496        @Override
1497        public void writeToParcel(Parcel dest, int flags) {
1498            dest.writeInt(stackId);
1499            dest.writeInt(bounds.left);
1500            dest.writeInt(bounds.top);
1501            dest.writeInt(bounds.right);
1502            dest.writeInt(bounds.bottom);
1503            dest.writeIntArray(taskIds);
1504            dest.writeStringArray(taskNames);
1505            dest.writeInt(displayId);
1506        }
1507
1508        public void readFromParcel(Parcel source) {
1509            stackId = source.readInt();
1510            bounds = new Rect(
1511                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
1512            taskIds = source.createIntArray();
1513            taskNames = source.createStringArray();
1514            displayId = source.readInt();
1515        }
1516
1517        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1518            @Override
1519            public StackInfo createFromParcel(Parcel source) {
1520                return new StackInfo(source);
1521            }
1522            @Override
1523            public StackInfo[] newArray(int size) {
1524                return new StackInfo[size];
1525            }
1526        };
1527
1528        public StackInfo() {
1529        }
1530
1531        private StackInfo(Parcel source) {
1532            readFromParcel(source);
1533        }
1534
1535        public String toString(String prefix) {
1536            StringBuilder sb = new StringBuilder(256);
1537            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1538                    sb.append(" bounds="); sb.append(bounds.toShortString());
1539                    sb.append(" displayId="); sb.append(displayId);
1540                    sb.append("\n");
1541            prefix = prefix + "  ";
1542            for (int i = 0; i < taskIds.length; ++i) {
1543                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1544                        sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
1545            }
1546            return sb.toString();
1547        }
1548
1549        @Override
1550        public String toString() {
1551            return toString("");
1552        }
1553    }
1554
1555    /**
1556     * @hide
1557     */
1558    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1559        try {
1560            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1561                    observer, UserHandle.myUserId());
1562        } catch (RemoteException e) {
1563            return false;
1564        }
1565    }
1566
1567    /**
1568     * Permits an application to erase its own data from disk.  This is equivalent to
1569     * the user choosing to clear the app's data from within the device settings UI.  It
1570     * erases all dynamic data associated with the app -- its private data and data in its
1571     * private area on external storage -- but does not remove the installed application
1572     * itself, nor any OBB files.
1573     *
1574     * @return {@code true} if the application successfully requested that the application's
1575     *     data be erased; {@code false} otherwise.
1576     */
1577    public boolean clearApplicationUserData() {
1578        return clearApplicationUserData(mContext.getPackageName(), null);
1579    }
1580
1581    /**
1582     * Information you can retrieve about any processes that are in an error condition.
1583     */
1584    public static class ProcessErrorStateInfo implements Parcelable {
1585        /**
1586         * Condition codes
1587         */
1588        public static final int NO_ERROR = 0;
1589        public static final int CRASHED = 1;
1590        public static final int NOT_RESPONDING = 2;
1591
1592        /**
1593         * The condition that the process is in.
1594         */
1595        public int condition;
1596
1597        /**
1598         * The process name in which the crash or error occurred.
1599         */
1600        public String processName;
1601
1602        /**
1603         * The pid of this process; 0 if none
1604         */
1605        public int pid;
1606
1607        /**
1608         * The kernel user-ID that has been assigned to this process;
1609         * currently this is not a unique ID (multiple applications can have
1610         * the same uid).
1611         */
1612        public int uid;
1613
1614        /**
1615         * The activity name associated with the error, if known.  May be null.
1616         */
1617        public String tag;
1618
1619        /**
1620         * A short message describing the error condition.
1621         */
1622        public String shortMsg;
1623
1624        /**
1625         * A long message describing the error condition.
1626         */
1627        public String longMsg;
1628
1629        /**
1630         * The stack trace where the error originated.  May be null.
1631         */
1632        public String stackTrace;
1633
1634        /**
1635         * to be deprecated: This value will always be null.
1636         */
1637        public byte[] crashData = null;
1638
1639        public ProcessErrorStateInfo() {
1640        }
1641
1642        @Override
1643        public int describeContents() {
1644            return 0;
1645        }
1646
1647        @Override
1648        public void writeToParcel(Parcel dest, int flags) {
1649            dest.writeInt(condition);
1650            dest.writeString(processName);
1651            dest.writeInt(pid);
1652            dest.writeInt(uid);
1653            dest.writeString(tag);
1654            dest.writeString(shortMsg);
1655            dest.writeString(longMsg);
1656            dest.writeString(stackTrace);
1657        }
1658
1659        public void readFromParcel(Parcel source) {
1660            condition = source.readInt();
1661            processName = source.readString();
1662            pid = source.readInt();
1663            uid = source.readInt();
1664            tag = source.readString();
1665            shortMsg = source.readString();
1666            longMsg = source.readString();
1667            stackTrace = source.readString();
1668        }
1669
1670        public static final Creator<ProcessErrorStateInfo> CREATOR =
1671                new Creator<ProcessErrorStateInfo>() {
1672            public ProcessErrorStateInfo createFromParcel(Parcel source) {
1673                return new ProcessErrorStateInfo(source);
1674            }
1675            public ProcessErrorStateInfo[] newArray(int size) {
1676                return new ProcessErrorStateInfo[size];
1677            }
1678        };
1679
1680        private ProcessErrorStateInfo(Parcel source) {
1681            readFromParcel(source);
1682        }
1683    }
1684
1685    /**
1686     * Returns a list of any processes that are currently in an error condition.  The result
1687     * will be null if all processes are running properly at this time.
1688     *
1689     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1690     * current error conditions (it will not return an empty list).  This list ordering is not
1691     * specified.
1692     */
1693    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1694        try {
1695            return ActivityManagerNative.getDefault().getProcessesInErrorState();
1696        } catch (RemoteException e) {
1697            return null;
1698        }
1699    }
1700
1701    /**
1702     * Information you can retrieve about a running process.
1703     */
1704    public static class RunningAppProcessInfo implements Parcelable {
1705        /**
1706         * The name of the process that this object is associated with
1707         */
1708        public String processName;
1709
1710        /**
1711         * The pid of this process; 0 if none
1712         */
1713        public int pid;
1714
1715        /**
1716         * The user id of this process.
1717         */
1718        public int uid;
1719
1720        /**
1721         * All packages that have been loaded into the process.
1722         */
1723        public String pkgList[];
1724
1725        /**
1726         * Constant for {@link #flags}: this is an app that is unable to
1727         * correctly save its state when going to the background,
1728         * so it can not be killed while in the background.
1729         * @hide
1730         */
1731        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1732
1733        /**
1734         * Constant for {@link #flags}: this process is associated with a
1735         * persistent system app.
1736         * @hide
1737         */
1738        public static final int FLAG_PERSISTENT = 1<<1;
1739
1740        /**
1741         * Constant for {@link #flags}: this process is associated with a
1742         * persistent system app.
1743         * @hide
1744         */
1745        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1746
1747        /**
1748         * Flags of information.  May be any of
1749         * {@link #FLAG_CANT_SAVE_STATE}.
1750         * @hide
1751         */
1752        public int flags;
1753
1754        /**
1755         * Last memory trim level reported to the process: corresponds to
1756         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1757         * ComponentCallbacks2.onTrimMemory(int)}.
1758         */
1759        public int lastTrimLevel;
1760
1761        /**
1762         * Constant for {@link #importance}: this process is running the
1763         * foreground UI.
1764         */
1765        public static final int IMPORTANCE_FOREGROUND = 100;
1766
1767        /**
1768         * Constant for {@link #importance}: this process is running something
1769         * that is actively visible to the user, though not in the immediate
1770         * foreground.
1771         */
1772        public static final int IMPORTANCE_VISIBLE = 200;
1773
1774        /**
1775         * Constant for {@link #importance}: this process is running something
1776         * that is considered to be actively perceptible to the user.  An
1777         * example would be an application performing background music playback.
1778         */
1779        public static final int IMPORTANCE_PERCEPTIBLE = 130;
1780
1781        /**
1782         * Constant for {@link #importance}: this process is running an
1783         * application that can not save its state, and thus can't be killed
1784         * while in the background.
1785         * @hide
1786         */
1787        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1788
1789        /**
1790         * Constant for {@link #importance}: this process is contains services
1791         * that should remain running.
1792         */
1793        public static final int IMPORTANCE_SERVICE = 300;
1794
1795        /**
1796         * Constant for {@link #importance}: this process process contains
1797         * background code that is expendable.
1798         */
1799        public static final int IMPORTANCE_BACKGROUND = 400;
1800
1801        /**
1802         * Constant for {@link #importance}: this process is empty of any
1803         * actively running code.
1804         */
1805        public static final int IMPORTANCE_EMPTY = 500;
1806
1807        /**
1808         * The relative importance level that the system places on this
1809         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
1810         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1811         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
1812         * constants are numbered so that "more important" values are always
1813         * smaller than "less important" values.
1814         */
1815        public int importance;
1816
1817        /**
1818         * An additional ordering within a particular {@link #importance}
1819         * category, providing finer-grained information about the relative
1820         * utility of processes within a category.  This number means nothing
1821         * except that a smaller values are more recently used (and thus
1822         * more important).  Currently an LRU value is only maintained for
1823         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1824         * be maintained in the future.
1825         */
1826        public int lru;
1827
1828        /**
1829         * Constant for {@link #importanceReasonCode}: nothing special has
1830         * been specified for the reason for this level.
1831         */
1832        public static final int REASON_UNKNOWN = 0;
1833
1834        /**
1835         * Constant for {@link #importanceReasonCode}: one of the application's
1836         * content providers is being used by another process.  The pid of
1837         * the client process is in {@link #importanceReasonPid} and the
1838         * target provider in this process is in
1839         * {@link #importanceReasonComponent}.
1840         */
1841        public static final int REASON_PROVIDER_IN_USE = 1;
1842
1843        /**
1844         * Constant for {@link #importanceReasonCode}: one of the application's
1845         * content providers is being used by another process.  The pid of
1846         * the client process is in {@link #importanceReasonPid} and the
1847         * target provider in this process is in
1848         * {@link #importanceReasonComponent}.
1849         */
1850        public static final int REASON_SERVICE_IN_USE = 2;
1851
1852        /**
1853         * The reason for {@link #importance}, if any.
1854         */
1855        public int importanceReasonCode;
1856
1857        /**
1858         * For the specified values of {@link #importanceReasonCode}, this
1859         * is the process ID of the other process that is a client of this
1860         * process.  This will be 0 if no other process is using this one.
1861         */
1862        public int importanceReasonPid;
1863
1864        /**
1865         * For the specified values of {@link #importanceReasonCode}, this
1866         * is the name of the component that is being used in this process.
1867         */
1868        public ComponentName importanceReasonComponent;
1869
1870        /**
1871         * When {@link #importanceReasonPid} is non-0, this is the importance
1872         * of the other pid. @hide
1873         */
1874        public int importanceReasonImportance;
1875
1876        /**
1877         * Current process state, as per PROCESS_STATE_* constants.
1878         * @hide
1879         */
1880        public int processState;
1881
1882        public RunningAppProcessInfo() {
1883            importance = IMPORTANCE_FOREGROUND;
1884            importanceReasonCode = REASON_UNKNOWN;
1885            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
1886        }
1887
1888        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1889            processName = pProcessName;
1890            pid = pPid;
1891            pkgList = pArr;
1892        }
1893
1894        public int describeContents() {
1895            return 0;
1896        }
1897
1898        public void writeToParcel(Parcel dest, int flags) {
1899            dest.writeString(processName);
1900            dest.writeInt(pid);
1901            dest.writeInt(uid);
1902            dest.writeStringArray(pkgList);
1903            dest.writeInt(this.flags);
1904            dest.writeInt(lastTrimLevel);
1905            dest.writeInt(importance);
1906            dest.writeInt(lru);
1907            dest.writeInt(importanceReasonCode);
1908            dest.writeInt(importanceReasonPid);
1909            ComponentName.writeToParcel(importanceReasonComponent, dest);
1910            dest.writeInt(importanceReasonImportance);
1911            dest.writeInt(processState);
1912        }
1913
1914        public void readFromParcel(Parcel source) {
1915            processName = source.readString();
1916            pid = source.readInt();
1917            uid = source.readInt();
1918            pkgList = source.readStringArray();
1919            flags = source.readInt();
1920            lastTrimLevel = source.readInt();
1921            importance = source.readInt();
1922            lru = source.readInt();
1923            importanceReasonCode = source.readInt();
1924            importanceReasonPid = source.readInt();
1925            importanceReasonComponent = ComponentName.readFromParcel(source);
1926            importanceReasonImportance = source.readInt();
1927            processState = source.readInt();
1928        }
1929
1930        public static final Creator<RunningAppProcessInfo> CREATOR =
1931            new Creator<RunningAppProcessInfo>() {
1932            public RunningAppProcessInfo createFromParcel(Parcel source) {
1933                return new RunningAppProcessInfo(source);
1934            }
1935            public RunningAppProcessInfo[] newArray(int size) {
1936                return new RunningAppProcessInfo[size];
1937            }
1938        };
1939
1940        private RunningAppProcessInfo(Parcel source) {
1941            readFromParcel(source);
1942        }
1943    }
1944
1945    /**
1946     * Returns a list of application processes installed on external media
1947     * that are running on the device.
1948     *
1949     * <p><b>Note: this method is only intended for debugging or building
1950     * a user-facing process management UI.</b></p>
1951     *
1952     * @return Returns a list of ApplicationInfo records, or null if none
1953     * This list ordering is not specified.
1954     * @hide
1955     */
1956    public List<ApplicationInfo> getRunningExternalApplications() {
1957        try {
1958            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1959        } catch (RemoteException e) {
1960            return null;
1961        }
1962    }
1963
1964    /**
1965     * Returns a list of application processes that are running on the device.
1966     *
1967     * <p><b>Note: this method is only intended for debugging or building
1968     * a user-facing process management UI.</b></p>
1969     *
1970     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
1971     * running processes (it will not return an empty list).  This list ordering is not
1972     * specified.
1973     */
1974    public List<RunningAppProcessInfo> getRunningAppProcesses() {
1975        try {
1976            return ActivityManagerNative.getDefault().getRunningAppProcesses();
1977        } catch (RemoteException e) {
1978            return null;
1979        }
1980    }
1981
1982    /**
1983     * Return global memory state information for the calling process.  This
1984     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
1985     * only fields that will be filled in are
1986     * {@link RunningAppProcessInfo#pid},
1987     * {@link RunningAppProcessInfo#uid},
1988     * {@link RunningAppProcessInfo#lastTrimLevel},
1989     * {@link RunningAppProcessInfo#importance},
1990     * {@link RunningAppProcessInfo#lru}, and
1991     * {@link RunningAppProcessInfo#importanceReasonCode}.
1992     */
1993    static public void getMyMemoryState(RunningAppProcessInfo outState) {
1994        try {
1995            ActivityManagerNative.getDefault().getMyMemoryState(outState);
1996        } catch (RemoteException e) {
1997        }
1998    }
1999
2000    /**
2001     * Return information about the memory usage of one or more processes.
2002     *
2003     * <p><b>Note: this method is only intended for debugging or building
2004     * a user-facing process management UI.</b></p>
2005     *
2006     * @param pids The pids of the processes whose memory usage is to be
2007     * retrieved.
2008     * @return Returns an array of memory information, one for each
2009     * requested pid.
2010     */
2011    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2012        try {
2013            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2014        } catch (RemoteException e) {
2015            return null;
2016        }
2017    }
2018
2019    /**
2020     * @deprecated This is now just a wrapper for
2021     * {@link #killBackgroundProcesses(String)}; the previous behavior here
2022     * is no longer available to applications because it allows them to
2023     * break other applications by removing their alarms, stopping their
2024     * services, etc.
2025     */
2026    @Deprecated
2027    public void restartPackage(String packageName) {
2028        killBackgroundProcesses(packageName);
2029    }
2030
2031    /**
2032     * Have the system immediately kill all background processes associated
2033     * with the given package.  This is the same as the kernel killing those
2034     * processes to reclaim memory; the system will take care of restarting
2035     * these processes in the future as needed.
2036     *
2037     * <p>You must hold the permission
2038     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2039     * call this method.
2040     *
2041     * @param packageName The name of the package whose processes are to
2042     * be killed.
2043     */
2044    public void killBackgroundProcesses(String packageName) {
2045        try {
2046            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2047                    UserHandle.myUserId());
2048        } catch (RemoteException e) {
2049        }
2050    }
2051
2052    /**
2053     * Have the system perform a force stop of everything associated with
2054     * the given application package.  All processes that share its uid
2055     * will be killed, all services it has running stopped, all activities
2056     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2057     * broadcast will be sent, so that any of its registered alarms can
2058     * be stopped, notifications removed, etc.
2059     *
2060     * <p>You must hold the permission
2061     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2062     * call this method.
2063     *
2064     * @param packageName The name of the package to be stopped.
2065     *
2066     * @hide This is not available to third party applications due to
2067     * it allowing them to break other applications by stopping their
2068     * services, removing their alarms, etc.
2069     */
2070    public void forceStopPackage(String packageName) {
2071        try {
2072            ActivityManagerNative.getDefault().forceStopPackage(packageName,
2073                    UserHandle.myUserId());
2074        } catch (RemoteException e) {
2075        }
2076    }
2077
2078    /**
2079     * Get the device configuration attributes.
2080     */
2081    public ConfigurationInfo getDeviceConfigurationInfo() {
2082        try {
2083            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2084        } catch (RemoteException e) {
2085        }
2086        return null;
2087    }
2088
2089    /**
2090     * Get the preferred density of icons for the launcher. This is used when
2091     * custom drawables are created (e.g., for shortcuts).
2092     *
2093     * @return density in terms of DPI
2094     */
2095    public int getLauncherLargeIconDensity() {
2096        final Resources res = mContext.getResources();
2097        final int density = res.getDisplayMetrics().densityDpi;
2098        final int sw = res.getConfiguration().smallestScreenWidthDp;
2099
2100        if (sw < 600) {
2101            // Smaller than approx 7" tablets, use the regular icon size.
2102            return density;
2103        }
2104
2105        switch (density) {
2106            case DisplayMetrics.DENSITY_LOW:
2107                return DisplayMetrics.DENSITY_MEDIUM;
2108            case DisplayMetrics.DENSITY_MEDIUM:
2109                return DisplayMetrics.DENSITY_HIGH;
2110            case DisplayMetrics.DENSITY_TV:
2111                return DisplayMetrics.DENSITY_XHIGH;
2112            case DisplayMetrics.DENSITY_HIGH:
2113                return DisplayMetrics.DENSITY_XHIGH;
2114            case DisplayMetrics.DENSITY_XHIGH:
2115                return DisplayMetrics.DENSITY_XXHIGH;
2116            case DisplayMetrics.DENSITY_XXHIGH:
2117                return DisplayMetrics.DENSITY_XHIGH * 2;
2118            default:
2119                // The density is some abnormal value.  Return some other
2120                // abnormal value that is a reasonable scaling of it.
2121                return (int)((density*1.5f)+.5f);
2122        }
2123    }
2124
2125    /**
2126     * Get the preferred launcher icon size. This is used when custom drawables
2127     * are created (e.g., for shortcuts).
2128     *
2129     * @return dimensions of square icons in terms of pixels
2130     */
2131    public int getLauncherLargeIconSize() {
2132        return getLauncherLargeIconSizeInner(mContext);
2133    }
2134
2135    static int getLauncherLargeIconSizeInner(Context context) {
2136        final Resources res = context.getResources();
2137        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2138        final int sw = res.getConfiguration().smallestScreenWidthDp;
2139
2140        if (sw < 600) {
2141            // Smaller than approx 7" tablets, use the regular icon size.
2142            return size;
2143        }
2144
2145        final int density = res.getDisplayMetrics().densityDpi;
2146
2147        switch (density) {
2148            case DisplayMetrics.DENSITY_LOW:
2149                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2150            case DisplayMetrics.DENSITY_MEDIUM:
2151                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2152            case DisplayMetrics.DENSITY_TV:
2153                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2154            case DisplayMetrics.DENSITY_HIGH:
2155                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2156            case DisplayMetrics.DENSITY_XHIGH:
2157                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2158            case DisplayMetrics.DENSITY_XXHIGH:
2159                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2160            default:
2161                // The density is some abnormal value.  Return some other
2162                // abnormal value that is a reasonable scaling of it.
2163                return (int)((size*1.5f) + .5f);
2164        }
2165    }
2166
2167    /**
2168     * Returns "true" if the user interface is currently being messed with
2169     * by a monkey.
2170     */
2171    public static boolean isUserAMonkey() {
2172        try {
2173            return ActivityManagerNative.getDefault().isUserAMonkey();
2174        } catch (RemoteException e) {
2175        }
2176        return false;
2177    }
2178
2179    /**
2180     * Returns "true" if device is running in a test harness.
2181     */
2182    public static boolean isRunningInTestHarness() {
2183        return SystemProperties.getBoolean("ro.test_harness", false);
2184    }
2185
2186    /**
2187     * Returns the launch count of each installed package.
2188     *
2189     * @hide
2190     */
2191    public Map<String, Integer> getAllPackageLaunchCounts() {
2192        try {
2193            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2194                    ServiceManager.getService("usagestats"));
2195            if (usageStatsService == null) {
2196                return new HashMap<String, Integer>();
2197            }
2198
2199            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2200                    ActivityThread.currentPackageName());
2201            if (allPkgUsageStats == null) {
2202                return new HashMap<String, Integer>();
2203            }
2204
2205            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2206            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2207                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2208            }
2209
2210            return launchCounts;
2211        } catch (RemoteException e) {
2212            Log.w(TAG, "Could not query launch counts", e);
2213            return new HashMap<String, Integer>();
2214        }
2215    }
2216
2217    /** @hide */
2218    public static int checkComponentPermission(String permission, int uid,
2219            int owningUid, boolean exported) {
2220        // Root, system server get to do everything.
2221        if (uid == 0 || uid == Process.SYSTEM_UID) {
2222            return PackageManager.PERMISSION_GRANTED;
2223        }
2224        // Isolated processes don't get any permissions.
2225        if (UserHandle.isIsolated(uid)) {
2226            return PackageManager.PERMISSION_DENIED;
2227        }
2228        // If there is a uid that owns whatever is being accessed, it has
2229        // blanket access to it regardless of the permissions it requires.
2230        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2231            return PackageManager.PERMISSION_GRANTED;
2232        }
2233        // If the target is not exported, then nobody else can get to it.
2234        if (!exported) {
2235            /*
2236            RuntimeException here = new RuntimeException("here");
2237            here.fillInStackTrace();
2238            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2239                    here);
2240            */
2241            return PackageManager.PERMISSION_DENIED;
2242        }
2243        if (permission == null) {
2244            return PackageManager.PERMISSION_GRANTED;
2245        }
2246        try {
2247            return AppGlobals.getPackageManager()
2248                    .checkUidPermission(permission, uid);
2249        } catch (RemoteException e) {
2250            // Should never happen, but if it does... deny!
2251            Slog.e(TAG, "PackageManager is dead?!?", e);
2252        }
2253        return PackageManager.PERMISSION_DENIED;
2254    }
2255
2256    /** @hide */
2257    public static int checkUidPermission(String permission, int uid) {
2258        try {
2259            return AppGlobals.getPackageManager()
2260                    .checkUidPermission(permission, uid);
2261        } catch (RemoteException e) {
2262            // Should never happen, but if it does... deny!
2263            Slog.e(TAG, "PackageManager is dead?!?", e);
2264        }
2265        return PackageManager.PERMISSION_DENIED;
2266    }
2267
2268    /**
2269     * @hide
2270     * Helper for dealing with incoming user arguments to system service calls.
2271     * Takes care of checking permissions and converting USER_CURRENT to the
2272     * actual current user.
2273     *
2274     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2275     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2276     * @param userId The user id argument supplied by the caller -- this is the user
2277     * they want to run as.
2278     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2279     * to get a USER_ALL returned and deal with it correctly.  If false,
2280     * an exception will be thrown if USER_ALL is supplied.
2281     * @param requireFull If true, the caller must hold
2282     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2283     * different user than their current process; otherwise they must hold
2284     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2285     * @param name Optional textual name of the incoming call; only for generating error messages.
2286     * @param callerPackage Optional package name of caller; only for error messages.
2287     *
2288     * @return Returns the user ID that the call should run as.  Will always be a concrete
2289     * user number, unless <var>allowAll</var> is true in which case it could also be
2290     * USER_ALL.
2291     */
2292    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2293            boolean allowAll, boolean requireFull, String name, String callerPackage) {
2294        if (UserHandle.getUserId(callingUid) == userId) {
2295            return userId;
2296        }
2297        try {
2298            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2299                    callingUid, userId, allowAll, requireFull, name, callerPackage);
2300        } catch (RemoteException e) {
2301            throw new SecurityException("Failed calling activity manager", e);
2302        }
2303    }
2304
2305    /** @hide */
2306    public static int getCurrentUser() {
2307        UserInfo ui;
2308        try {
2309            ui = ActivityManagerNative.getDefault().getCurrentUser();
2310            return ui != null ? ui.id : 0;
2311        } catch (RemoteException e) {
2312            return 0;
2313        }
2314    }
2315
2316    /**
2317     * Returns the usage statistics of each installed package.
2318     *
2319     * @hide
2320     */
2321    public UsageStats.PackageStats[] getAllPackageUsageStats() {
2322        try {
2323            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2324                    ServiceManager.getService("usagestats"));
2325            if (usageStatsService != null) {
2326                return usageStatsService.getAllPkgUsageStats(ActivityThread.currentPackageName());
2327            }
2328        } catch (RemoteException e) {
2329            Log.w(TAG, "Could not query usage stats", e);
2330        }
2331        return new UsageStats.PackageStats[0];
2332    }
2333
2334    /**
2335     * @param userid the user's id. Zero indicates the default user
2336     * @hide
2337     */
2338    public boolean switchUser(int userid) {
2339        try {
2340            return ActivityManagerNative.getDefault().switchUser(userid);
2341        } catch (RemoteException e) {
2342            return false;
2343        }
2344    }
2345
2346    /**
2347     * Return whether the given user is actively running.  This means that
2348     * the user is in the "started" state, not "stopped" -- it is currently
2349     * allowed to run code through scheduled alarms, receiving broadcasts,
2350     * etc.  A started user may be either the current foreground user or a
2351     * background user; the result here does not distinguish between the two.
2352     * @param userid the user's id. Zero indicates the default user.
2353     * @hide
2354     */
2355    public boolean isUserRunning(int userid) {
2356        try {
2357            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2358        } catch (RemoteException e) {
2359            return false;
2360        }
2361    }
2362
2363    /**
2364     * Perform a system dump of various state associated with the given application
2365     * package name.  This call blocks while the dump is being performed, so should
2366     * not be done on a UI thread.  The data will be written to the given file
2367     * descriptor as text.  An application must hold the
2368     * {@link android.Manifest.permission#DUMP} permission to make this call.
2369     * @param fd The file descriptor that the dump should be written to.  The file
2370     * descriptor is <em>not</em> closed by this function; the caller continues to
2371     * own it.
2372     * @param packageName The name of the package that is to be dumped.
2373     */
2374    public void dumpPackageState(FileDescriptor fd, String packageName) {
2375        dumpPackageStateStatic(fd, packageName);
2376    }
2377
2378    /**
2379     * @hide
2380     */
2381    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2382        FileOutputStream fout = new FileOutputStream(fd);
2383        PrintWriter pw = new FastPrintWriter(fout);
2384        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2385                "-a", "package", packageName });
2386        pw.println();
2387        dumpService(pw, fd, "meminfo", new String[] { "--local", packageName });
2388        pw.println();
2389        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { "-a", packageName });
2390        pw.println();
2391        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2392        pw.println();
2393        dumpService(pw, fd, "package", new String[] { packageName });
2394        pw.println();
2395        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2396        pw.flush();
2397    }
2398
2399    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2400        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2401        IBinder service = ServiceManager.checkService(name);
2402        if (service == null) {
2403            pw.println("  (Service not found)");
2404            return;
2405        }
2406        TransferPipe tp = null;
2407        try {
2408            pw.flush();
2409            tp = new TransferPipe();
2410            tp.setBufferPrefix("  ");
2411            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
2412            tp.go(fd);
2413        } catch (Throwable e) {
2414            if (tp != null) {
2415                tp.kill();
2416            }
2417            pw.println("Failure dumping service:");
2418            e.printStackTrace(pw);
2419        }
2420    }
2421
2422    /**
2423     * @hide
2424     */
2425    public void startLockTaskMode(int taskId) {
2426        try {
2427            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
2428        } catch (RemoteException e) {
2429        }
2430    }
2431
2432    /**
2433     * @hide
2434     */
2435    public void stopLockTaskMode() {
2436        try {
2437            ActivityManagerNative.getDefault().stopLockTaskMode();
2438        } catch (RemoteException e) {
2439        }
2440    }
2441
2442    /**
2443     * @hide
2444     */
2445    public boolean isInLockTaskMode() {
2446        try {
2447            return ActivityManagerNative.getDefault().isInLockTaskMode();
2448        } catch (RemoteException e) {
2449            return false;
2450        }
2451    }
2452
2453    /**
2454     * The AppTask allows you to manage your own application's tasks.
2455     * See {@link android.app.ActivityManager#getAppTasks()}
2456     */
2457    public static class AppTask {
2458        private IAppTask mAppTaskImpl;
2459
2460        /** @hide */
2461        public AppTask(IAppTask task) {
2462            mAppTaskImpl = task;
2463        }
2464
2465        /**
2466         * Finishes all activities in this task and removes it from the recent tasks list.
2467         */
2468        public void finishAndRemoveTask() {
2469            try {
2470                mAppTaskImpl.finishAndRemoveTask();
2471            } catch (RemoteException e) {
2472                Slog.e(TAG, "Invalid AppTask", e);
2473            }
2474        }
2475
2476        /**
2477         * Get the RecentTaskInfo associated with this task.
2478         *
2479         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
2480         */
2481        public RecentTaskInfo getTaskInfo() {
2482            try {
2483                return mAppTaskImpl.getTaskInfo();
2484            } catch (RemoteException e) {
2485                Slog.e(TAG, "Invalid AppTask", e);
2486                return null;
2487            }
2488        }
2489    }
2490}
2491