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