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