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