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