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