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