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