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