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