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