ActivityManager.java revision d94df45b3d1ab4004ef517acfc56a9310330f8d8
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.content.ComponentName;
20import android.content.Context;
21import android.content.Intent;
22import android.content.pm.ApplicationInfo;
23import android.content.pm.ConfigurationInfo;
24import android.content.pm.IPackageDataObserver;
25import android.content.res.Configuration;
26import android.content.res.Resources;
27import android.graphics.Bitmap;
28import android.os.Debug;
29import android.os.RemoteException;
30import android.os.Handler;
31import android.os.Parcel;
32import android.os.Parcelable;
33import android.os.SystemProperties;
34import android.text.TextUtils;
35import android.util.DisplayMetrics;
36
37import java.util.List;
38
39/**
40 * Interact with the overall activities running in the system.
41 */
42public class ActivityManager {
43    private static String TAG = "ActivityManager";
44    private static boolean DEBUG = false;
45    private static boolean localLOGV = DEBUG || android.util.Config.LOGV;
46
47    private final Context mContext;
48    private final Handler mHandler;
49
50    /*package*/ ActivityManager(Context context, Handler handler) {
51        mContext = context;
52        mHandler = handler;
53    }
54
55    /**
56     * Return the approximate per-application memory class of the current
57     * device.  This gives you an idea of how hard a memory limit you should
58     * impose on your application to let the overall system work best.  The
59     * returned value is in megabytes; the baseline Android memory class is
60     * 16 (which happens to be the Java heap limit of those devices); some
61     * device with more memory may return 24 or even higher numbers.
62     */
63    public int getMemoryClass() {
64        return staticGetMemoryClass();
65    }
66
67    /** @hide */
68    static public int staticGetMemoryClass() {
69        // Really brain dead right now -- just take this from the configured
70        // vm heap size, and assume it is in megabytes and thus ends with "m".
71        String vmHeapSize = SystemProperties.get("dalvik.vm.growthlimit", "");
72        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
73            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
74        }
75        return staticGetLargeMemoryClass();
76    }
77
78    /**
79     * Return the approximate per-application memory class of the current
80     * device when an application is running with a large heap.  This is the
81     * space available for memory-intensive applications; most applications
82     * should not need this amount of memory, and should instead stay with the
83     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
84     * This may be the same size as {@link #getMemoryClass()} on memory
85     * constrained devices, or it may be significantly larger on devices with
86     * a large amount of available RAM.
87     *
88     * <p>The is the size of the application's Dalvik heap if it has
89     * specified <code>android:largeHeap="true"</code> in its manifest.
90     */
91    public int getLargeMemoryClass() {
92        return staticGetLargeMemoryClass();
93    }
94
95    /** @hide */
96    static public int staticGetLargeMemoryClass() {
97        // Really brain dead right now -- just take this from the configured
98        // vm heap size, and assume it is in megabytes and thus ends with "m".
99        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
100        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
101    }
102
103    /**
104     * Information you can retrieve about tasks that the user has most recently
105     * started or visited.
106     */
107    public static class RecentTaskInfo implements Parcelable {
108        /**
109         * If this task is currently running, this is the identifier for it.
110         * If it is not running, this will be -1.
111         */
112        public int id;
113
114        /**
115         * The true identifier of this task, valid even if it is not running.
116         */
117        public int persistentId;
118
119        /**
120         * The original Intent used to launch the task.  You can use this
121         * Intent to re-launch the task (if it is no longer running) or bring
122         * the current task to the front.
123         */
124        public Intent baseIntent;
125
126        /**
127         * If this task was started from an alias, this is the actual
128         * activity component that was initially started; the component of
129         * the baseIntent in this case is the name of the actual activity
130         * implementation that the alias referred to.  Otherwise, this is null.
131         */
132        public ComponentName origActivity;
133
134        /**
135         * Description of the task's last state.
136         */
137        public CharSequence description;
138
139        public RecentTaskInfo() {
140        }
141
142        public int describeContents() {
143            return 0;
144        }
145
146        public void writeToParcel(Parcel dest, int flags) {
147            dest.writeInt(id);
148            dest.writeInt(persistentId);
149            if (baseIntent != null) {
150                dest.writeInt(1);
151                baseIntent.writeToParcel(dest, 0);
152            } else {
153                dest.writeInt(0);
154            }
155            ComponentName.writeToParcel(origActivity, dest);
156            TextUtils.writeToParcel(description, dest,
157                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
158        }
159
160        public void readFromParcel(Parcel source) {
161            id = source.readInt();
162            persistentId = source.readInt();
163            if (source.readInt() != 0) {
164                baseIntent = Intent.CREATOR.createFromParcel(source);
165            } else {
166                baseIntent = null;
167            }
168            origActivity = ComponentName.readFromParcel(source);
169            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
170        }
171
172        public static final Creator<RecentTaskInfo> CREATOR
173                = new Creator<RecentTaskInfo>() {
174            public RecentTaskInfo createFromParcel(Parcel source) {
175                return new RecentTaskInfo(source);
176            }
177            public RecentTaskInfo[] newArray(int size) {
178                return new RecentTaskInfo[size];
179            }
180        };
181
182        private RecentTaskInfo(Parcel source) {
183            readFromParcel(source);
184        }
185    }
186
187    /**
188     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
189     * that have set their
190     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
191     */
192    public static final int RECENT_WITH_EXCLUDED = 0x0001;
193
194    /**
195     * Provides a list that does not contain any
196     * recent tasks that currently are not available to the user.
197     */
198    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
199
200    /**
201     * Flag for use with {@link #getRecentTasks}: also return the thumbnail
202     * bitmap (if available) for each recent task.
203     * @hide
204     */
205    public static final int TASKS_GET_THUMBNAILS = 0x0001000;
206
207    /**
208     * Return a list of the tasks that the user has recently launched, with
209     * the most recent being first and older ones after in order.
210     *
211     * @param maxNum The maximum number of entries to return in the list.  The
212     * actual number returned may be smaller, depending on how many tasks the
213     * user has started and the maximum number the system can remember.
214     * @param flags Information about what to return.  May be any combination
215     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
216     *
217     * @return Returns a list of RecentTaskInfo records describing each of
218     * the recent tasks.
219     *
220     * @throws SecurityException Throws SecurityException if the caller does
221     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
222     */
223    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
224            throws SecurityException {
225        try {
226            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
227                    flags);
228        } catch (RemoteException e) {
229            // System dead, we will be dead too soon!
230            return null;
231        }
232    }
233
234    /**
235     * Information you can retrieve about a particular task that is currently
236     * "running" in the system.  Note that a running task does not mean the
237     * given task actual has a process it is actively running in; it simply
238     * means that the user has gone to it and never closed it, but currently
239     * the system may have killed its process and is only holding on to its
240     * last state in order to restart it when the user returns.
241     */
242    public static class RunningTaskInfo implements Parcelable {
243        /**
244         * A unique identifier for this task.
245         */
246        public int id;
247
248        /**
249         * The component launched as the first activity in the task.  This can
250         * be considered the "application" of this task.
251         */
252        public ComponentName baseActivity;
253
254        /**
255         * The activity component at the top of the history stack of the task.
256         * This is what the user is currently doing.
257         */
258        public ComponentName topActivity;
259
260        /**
261         * Thumbnail representation of the task's current state.  Currently
262         * always null.
263         */
264        public Bitmap thumbnail;
265
266        /**
267         * Description of the task's current state.
268         */
269        public CharSequence description;
270
271        /**
272         * Number of activities in this task.
273         */
274        public int numActivities;
275
276        /**
277         * Number of activities that are currently running (not stopped
278         * and persisted) in this task.
279         */
280        public int numRunning;
281
282        public RunningTaskInfo() {
283        }
284
285        public int describeContents() {
286            return 0;
287        }
288
289        public void writeToParcel(Parcel dest, int flags) {
290            dest.writeInt(id);
291            ComponentName.writeToParcel(baseActivity, dest);
292            ComponentName.writeToParcel(topActivity, dest);
293            if (thumbnail != null) {
294                dest.writeInt(1);
295                thumbnail.writeToParcel(dest, 0);
296            } else {
297                dest.writeInt(0);
298            }
299            TextUtils.writeToParcel(description, dest,
300                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
301            dest.writeInt(numActivities);
302            dest.writeInt(numRunning);
303        }
304
305        public void readFromParcel(Parcel source) {
306            id = source.readInt();
307            baseActivity = ComponentName.readFromParcel(source);
308            topActivity = ComponentName.readFromParcel(source);
309            if (source.readInt() != 0) {
310                thumbnail = Bitmap.CREATOR.createFromParcel(source);
311            } else {
312                thumbnail = null;
313            }
314            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
315            numActivities = source.readInt();
316            numRunning = source.readInt();
317        }
318
319        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
320            public RunningTaskInfo createFromParcel(Parcel source) {
321                return new RunningTaskInfo(source);
322            }
323            public RunningTaskInfo[] newArray(int size) {
324                return new RunningTaskInfo[size];
325            }
326        };
327
328        private RunningTaskInfo(Parcel source) {
329            readFromParcel(source);
330        }
331    }
332
333    /**
334     * Return a list of the tasks that are currently running, with
335     * the most recent being first and older ones after in order.  Note that
336     * "running" does not mean any of the task's code is currently loaded or
337     * activity -- the task may have been frozen by the system, so that it
338     * can be restarted in its previous state when next brought to the
339     * foreground.
340     *
341     * @param maxNum The maximum number of entries to return in the list.  The
342     * actual number returned may be smaller, depending on how many tasks the
343     * user has started.
344     *
345     * @param flags Optional flags
346     * @param receiver Optional receiver for delayed thumbnails
347     *
348     * @return Returns a list of RunningTaskInfo records describing each of
349     * the running tasks.
350     *
351     * Some thumbnails may not be available at the time of this call. The optional
352     * receiver may be used to receive those thumbnails.
353     *
354     * @throws SecurityException Throws SecurityException if the caller does
355     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
356     *
357     * @hide
358     */
359    public List<RunningTaskInfo> getRunningTasks(int maxNum, int flags, IThumbnailReceiver receiver)
360            throws SecurityException {
361        try {
362            return ActivityManagerNative.getDefault().getTasks(maxNum, flags, receiver);
363        } catch (RemoteException e) {
364            // System dead, we will be dead too soon!
365            return null;
366        }
367    }
368
369    /**
370     * Return a list of the tasks that are currently running, with
371     * the most recent being first and older ones after in order.  Note that
372     * "running" does not mean any of the task's code is currently loaded or
373     * activity -- the task may have been frozen by the system, so that it
374     * can be restarted in its previous state when next brought to the
375     * foreground.
376     *
377     * @param maxNum The maximum number of entries to return in the list.  The
378     * actual number returned may be smaller, depending on how many tasks the
379     * user has started.
380     *
381     * @return Returns a list of RunningTaskInfo records describing each of
382     * the running tasks.
383     *
384     * @throws SecurityException Throws SecurityException if the caller does
385     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
386     */
387    public List<RunningTaskInfo> getRunningTasks(int maxNum)
388            throws SecurityException {
389        return getRunningTasks(maxNum, 0, null);
390    }
391
392    /** @hide */
393    public Bitmap getTaskThumbnail(int id) throws SecurityException {
394        try {
395            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
396        } catch (RemoteException e) {
397            // System dead, we will be dead too soon!
398            return null;
399        }
400    }
401
402    /**
403     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
404     * activity along with the task, so it is positioned immediately behind
405     * the task.
406     */
407    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
408
409    /**
410     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
411     * user-instigated action, so the current activity will not receive a
412     * hint that the user is leaving.
413     */
414    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
415
416    /**
417     * Ask that the task associated with a given task ID be moved to the
418     * front of the stack, so it is now visible to the user.  Requires that
419     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
420     * or a SecurityException will be thrown.
421     *
422     * @param taskId The identifier of the task to be moved, as found in
423     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
424     * @param flags Additional operational flags, 0 or more of
425     * {@link #MOVE_TASK_WITH_HOME}.
426     */
427    public void moveTaskToFront(int taskId, int flags) {
428        try {
429            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags);
430        } catch (RemoteException e) {
431            // System dead, we will be dead too soon!
432        }
433    }
434
435    /**
436     * Information you can retrieve about a particular Service that is
437     * currently running in the system.
438     */
439    public static class RunningServiceInfo implements Parcelable {
440        /**
441         * The service component.
442         */
443        public ComponentName service;
444
445        /**
446         * If non-zero, this is the process the service is running in.
447         */
448        public int pid;
449
450        /**
451         * The UID that owns this service.
452         */
453        public int uid;
454
455        /**
456         * The name of the process this service runs in.
457         */
458        public String process;
459
460        /**
461         * Set to true if the service has asked to run as a foreground process.
462         */
463        public boolean foreground;
464
465        /**
466         * The time when the service was first made active, either by someone
467         * starting or binding to it.  This
468         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
469         */
470        public long activeSince;
471
472        /**
473         * Set to true if this service has been explicitly started.
474         */
475        public boolean started;
476
477        /**
478         * Number of clients connected to the service.
479         */
480        public int clientCount;
481
482        /**
483         * Number of times the service's process has crashed while the service
484         * is running.
485         */
486        public int crashCount;
487
488        /**
489         * The time when there was last activity in the service (either
490         * explicit requests to start it or clients binding to it).  This
491         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
492         */
493        public long lastActivityTime;
494
495        /**
496         * If non-zero, this service is not currently running, but scheduled to
497         * restart at the given time.
498         */
499        public long restarting;
500
501        /**
502         * Bit for {@link #flags}: set if this service has been
503         * explicitly started.
504         */
505        public static final int FLAG_STARTED = 1<<0;
506
507        /**
508         * Bit for {@link #flags}: set if the service has asked to
509         * run as a foreground process.
510         */
511        public static final int FLAG_FOREGROUND = 1<<1;
512
513        /**
514         * Bit for {@link #flags): set if the service is running in a
515         * core system process.
516         */
517        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
518
519        /**
520         * Bit for {@link #flags): set if the service is running in a
521         * persistent process.
522         */
523        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
524
525        /**
526         * Running flags.
527         */
528        public int flags;
529
530        /**
531         * For special services that are bound to by system code, this is
532         * the package that holds the binding.
533         */
534        public String clientPackage;
535
536        /**
537         * For special services that are bound to by system code, this is
538         * a string resource providing a user-visible label for who the
539         * client is.
540         */
541        public int clientLabel;
542
543        public RunningServiceInfo() {
544        }
545
546        public int describeContents() {
547            return 0;
548        }
549
550        public void writeToParcel(Parcel dest, int flags) {
551            ComponentName.writeToParcel(service, dest);
552            dest.writeInt(pid);
553            dest.writeInt(uid);
554            dest.writeString(process);
555            dest.writeInt(foreground ? 1 : 0);
556            dest.writeLong(activeSince);
557            dest.writeInt(started ? 1 : 0);
558            dest.writeInt(clientCount);
559            dest.writeInt(crashCount);
560            dest.writeLong(lastActivityTime);
561            dest.writeLong(restarting);
562            dest.writeInt(this.flags);
563            dest.writeString(clientPackage);
564            dest.writeInt(clientLabel);
565        }
566
567        public void readFromParcel(Parcel source) {
568            service = ComponentName.readFromParcel(source);
569            pid = source.readInt();
570            uid = source.readInt();
571            process = source.readString();
572            foreground = source.readInt() != 0;
573            activeSince = source.readLong();
574            started = source.readInt() != 0;
575            clientCount = source.readInt();
576            crashCount = source.readInt();
577            lastActivityTime = source.readLong();
578            restarting = source.readLong();
579            flags = source.readInt();
580            clientPackage = source.readString();
581            clientLabel = source.readInt();
582        }
583
584        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
585            public RunningServiceInfo createFromParcel(Parcel source) {
586                return new RunningServiceInfo(source);
587            }
588            public RunningServiceInfo[] newArray(int size) {
589                return new RunningServiceInfo[size];
590            }
591        };
592
593        private RunningServiceInfo(Parcel source) {
594            readFromParcel(source);
595        }
596    }
597
598    /**
599     * Return a list of the services that are currently running.
600     *
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 services
603     * are running.
604     *
605     * @return Returns a list of RunningServiceInfo records describing each of
606     * the running tasks.
607     */
608    public List<RunningServiceInfo> getRunningServices(int maxNum)
609            throws SecurityException {
610        try {
611            return (List<RunningServiceInfo>)ActivityManagerNative.getDefault()
612                    .getServices(maxNum, 0);
613        } catch (RemoteException e) {
614            // System dead, we will be dead too soon!
615            return null;
616        }
617    }
618
619    /**
620     * Returns a PendingIntent you can start to show a control panel for the
621     * given running service.  If the service does not have a control panel,
622     * null is returned.
623     */
624    public PendingIntent getRunningServiceControlPanel(ComponentName service)
625            throws SecurityException {
626        try {
627            return ActivityManagerNative.getDefault()
628                    .getRunningServiceControlPanel(service);
629        } catch (RemoteException e) {
630            // System dead, we will be dead too soon!
631            return null;
632        }
633    }
634
635    /**
636     * Information you can retrieve about the available memory through
637     * {@link ActivityManager#getMemoryInfo}.
638     */
639    public static class MemoryInfo implements Parcelable {
640        /**
641         * The total available memory on the system.  This number should not
642         * be considered absolute: due to the nature of the kernel, a significant
643         * portion of this memory is actually in use and needed for the overall
644         * system to run well.
645         */
646        public long availMem;
647
648        /**
649         * The threshold of {@link #availMem} at which we consider memory to be
650         * low and start killing background services and other non-extraneous
651         * processes.
652         */
653        public long threshold;
654
655        /**
656         * Set to true if the system considers itself to currently be in a low
657         * memory situation.
658         */
659        public boolean lowMemory;
660
661        public MemoryInfo() {
662        }
663
664        public int describeContents() {
665            return 0;
666        }
667
668        public void writeToParcel(Parcel dest, int flags) {
669            dest.writeLong(availMem);
670            dest.writeLong(threshold);
671            dest.writeInt(lowMemory ? 1 : 0);
672        }
673
674        public void readFromParcel(Parcel source) {
675            availMem = source.readLong();
676            threshold = source.readLong();
677            lowMemory = source.readInt() != 0;
678        }
679
680        public static final Creator<MemoryInfo> CREATOR
681                = new Creator<MemoryInfo>() {
682            public MemoryInfo createFromParcel(Parcel source) {
683                return new MemoryInfo(source);
684            }
685            public MemoryInfo[] newArray(int size) {
686                return new MemoryInfo[size];
687            }
688        };
689
690        private MemoryInfo(Parcel source) {
691            readFromParcel(source);
692        }
693    }
694
695    public void getMemoryInfo(MemoryInfo outInfo) {
696        try {
697            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
698        } catch (RemoteException e) {
699        }
700    }
701
702    /**
703     * @hide
704     */
705    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
706        try {
707            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
708                    observer);
709        } catch (RemoteException e) {
710            return false;
711        }
712    }
713
714    /**
715     * Information you can retrieve about any processes that are in an error condition.
716     */
717    public static class ProcessErrorStateInfo implements Parcelable {
718        /**
719         * Condition codes
720         */
721        public static final int NO_ERROR = 0;
722        public static final int CRASHED = 1;
723        public static final int NOT_RESPONDING = 2;
724
725        /**
726         * The condition that the process is in.
727         */
728        public int condition;
729
730        /**
731         * The process name in which the crash or error occurred.
732         */
733        public String processName;
734
735        /**
736         * The pid of this process; 0 if none
737         */
738        public int pid;
739
740        /**
741         * The kernel user-ID that has been assigned to this process;
742         * currently this is not a unique ID (multiple applications can have
743         * the same uid).
744         */
745        public int uid;
746
747        /**
748         * The activity name associated with the error, if known.  May be null.
749         */
750        public String tag;
751
752        /**
753         * A short message describing the error condition.
754         */
755        public String shortMsg;
756
757        /**
758         * A long message describing the error condition.
759         */
760        public String longMsg;
761
762        /**
763         * The stack trace where the error originated.  May be null.
764         */
765        public String stackTrace;
766
767        /**
768         * to be deprecated: This value will always be null.
769         */
770        public byte[] crashData = null;
771
772        public ProcessErrorStateInfo() {
773        }
774
775        public int describeContents() {
776            return 0;
777        }
778
779        public void writeToParcel(Parcel dest, int flags) {
780            dest.writeInt(condition);
781            dest.writeString(processName);
782            dest.writeInt(pid);
783            dest.writeInt(uid);
784            dest.writeString(tag);
785            dest.writeString(shortMsg);
786            dest.writeString(longMsg);
787            dest.writeString(stackTrace);
788        }
789
790        public void readFromParcel(Parcel source) {
791            condition = source.readInt();
792            processName = source.readString();
793            pid = source.readInt();
794            uid = source.readInt();
795            tag = source.readString();
796            shortMsg = source.readString();
797            longMsg = source.readString();
798            stackTrace = source.readString();
799        }
800
801        public static final Creator<ProcessErrorStateInfo> CREATOR =
802                new Creator<ProcessErrorStateInfo>() {
803            public ProcessErrorStateInfo createFromParcel(Parcel source) {
804                return new ProcessErrorStateInfo(source);
805            }
806            public ProcessErrorStateInfo[] newArray(int size) {
807                return new ProcessErrorStateInfo[size];
808            }
809        };
810
811        private ProcessErrorStateInfo(Parcel source) {
812            readFromParcel(source);
813        }
814    }
815
816    /**
817     * Returns a list of any processes that are currently in an error condition.  The result
818     * will be null if all processes are running properly at this time.
819     *
820     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
821     * current error conditions (it will not return an empty list).  This list ordering is not
822     * specified.
823     */
824    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
825        try {
826            return ActivityManagerNative.getDefault().getProcessesInErrorState();
827        } catch (RemoteException e) {
828            return null;
829        }
830    }
831
832    /**
833     * Information you can retrieve about a running process.
834     */
835    public static class RunningAppProcessInfo implements Parcelable {
836        /**
837         * The name of the process that this object is associated with
838         */
839        public String processName;
840
841        /**
842         * The pid of this process; 0 if none
843         */
844        public int pid;
845
846        /**
847         * The user id of this process.
848         */
849        public int uid;
850
851        /**
852         * All packages that have been loaded into the process.
853         */
854        public String pkgList[];
855
856        /**
857         * Constant for {@link #flags}: this is an app that is unable to
858         * correctly save its state when going to the background,
859         * so it can not be killed while in the background.
860         * @hide
861         */
862        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
863
864        /**
865         * Constant for {@link #flags}: this process is associated with a
866         * persistent system app.
867         * @hide
868         */
869        public static final int FLAG_PERSISTENT = 1<<1;
870
871        /**
872         * Flags of information.  May be any of
873         * {@link #FLAG_CANT_SAVE_STATE}.
874         * @hide
875         */
876        public int flags;
877
878        /**
879         * Constant for {@link #importance}: this process is running the
880         * foreground UI.
881         */
882        public static final int IMPORTANCE_FOREGROUND = 100;
883
884        /**
885         * Constant for {@link #importance}: this process is running something
886         * that is actively visible to the user, though not in the immediate
887         * foreground.
888         */
889        public static final int IMPORTANCE_VISIBLE = 200;
890
891        /**
892         * Constant for {@link #importance}: this process is running something
893         * that is considered to be actively perceptible to the user.  An
894         * example would be an application performing background music playback.
895         */
896        public static final int IMPORTANCE_PERCEPTIBLE = 130;
897
898        /**
899         * Constant for {@link #importance}: this process is running an
900         * application that can not save its state, and thus can't be killed
901         * while in the background.
902         * @hide
903         */
904        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
905
906        /**
907         * Constant for {@link #importance}: this process is contains services
908         * that should remain running.
909         */
910        public static final int IMPORTANCE_SERVICE = 300;
911
912        /**
913         * Constant for {@link #importance}: this process process contains
914         * background code that is expendable.
915         */
916        public static final int IMPORTANCE_BACKGROUND = 400;
917
918        /**
919         * Constant for {@link #importance}: this process is empty of any
920         * actively running code.
921         */
922        public static final int IMPORTANCE_EMPTY = 500;
923
924        /**
925         * The relative importance level that the system places on this
926         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
927         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
928         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
929         * constants are numbered so that "more important" values are always
930         * smaller than "less important" values.
931         */
932        public int importance;
933
934        /**
935         * An additional ordering within a particular {@link #importance}
936         * category, providing finer-grained information about the relative
937         * utility of processes within a category.  This number means nothing
938         * except that a smaller values are more recently used (and thus
939         * more important).  Currently an LRU value is only maintained for
940         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
941         * be maintained in the future.
942         */
943        public int lru;
944
945        /**
946         * Constant for {@link #importanceReasonCode}: nothing special has
947         * been specified for the reason for this level.
948         */
949        public static final int REASON_UNKNOWN = 0;
950
951        /**
952         * Constant for {@link #importanceReasonCode}: one of the application's
953         * content providers is being used by another process.  The pid of
954         * the client process is in {@link #importanceReasonPid} and the
955         * target provider in this process is in
956         * {@link #importanceReasonComponent}.
957         */
958        public static final int REASON_PROVIDER_IN_USE = 1;
959
960        /**
961         * Constant for {@link #importanceReasonCode}: one of the application's
962         * content providers is being used by another process.  The pid of
963         * the client process is in {@link #importanceReasonPid} and the
964         * target provider in this process is in
965         * {@link #importanceReasonComponent}.
966         */
967        public static final int REASON_SERVICE_IN_USE = 2;
968
969        /**
970         * The reason for {@link #importance}, if any.
971         */
972        public int importanceReasonCode;
973
974        /**
975         * For the specified values of {@link #importanceReasonCode}, this
976         * is the process ID of the other process that is a client of this
977         * process.  This will be 0 if no other process is using this one.
978         */
979        public int importanceReasonPid;
980
981        /**
982         * For the specified values of {@link #importanceReasonCode}, this
983         * is the name of the component that is being used in this process.
984         */
985        public ComponentName importanceReasonComponent;
986
987        public RunningAppProcessInfo() {
988            importance = IMPORTANCE_FOREGROUND;
989            importanceReasonCode = REASON_UNKNOWN;
990        }
991
992        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
993            processName = pProcessName;
994            pid = pPid;
995            pkgList = pArr;
996        }
997
998        public int describeContents() {
999            return 0;
1000        }
1001
1002        public void writeToParcel(Parcel dest, int flags) {
1003            dest.writeString(processName);
1004            dest.writeInt(pid);
1005            dest.writeInt(uid);
1006            dest.writeStringArray(pkgList);
1007            dest.writeInt(this.flags);
1008            dest.writeInt(importance);
1009            dest.writeInt(lru);
1010            dest.writeInt(importanceReasonCode);
1011            dest.writeInt(importanceReasonPid);
1012            ComponentName.writeToParcel(importanceReasonComponent, dest);
1013        }
1014
1015        public void readFromParcel(Parcel source) {
1016            processName = source.readString();
1017            pid = source.readInt();
1018            uid = source.readInt();
1019            pkgList = source.readStringArray();
1020            flags = source.readInt();
1021            importance = source.readInt();
1022            lru = source.readInt();
1023            importanceReasonCode = source.readInt();
1024            importanceReasonPid = source.readInt();
1025            importanceReasonComponent = ComponentName.readFromParcel(source);
1026        }
1027
1028        public static final Creator<RunningAppProcessInfo> CREATOR =
1029            new Creator<RunningAppProcessInfo>() {
1030            public RunningAppProcessInfo createFromParcel(Parcel source) {
1031                return new RunningAppProcessInfo(source);
1032            }
1033            public RunningAppProcessInfo[] newArray(int size) {
1034                return new RunningAppProcessInfo[size];
1035            }
1036        };
1037
1038        private RunningAppProcessInfo(Parcel source) {
1039            readFromParcel(source);
1040        }
1041    }
1042
1043    /**
1044     * Returns a list of application processes installed on external media
1045     * that are running on the device.
1046     *
1047     * @return Returns a list of ApplicationInfo records, or null if none
1048     * This list ordering is not specified.
1049     * @hide
1050     */
1051    public List<ApplicationInfo> getRunningExternalApplications() {
1052        try {
1053            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1054        } catch (RemoteException e) {
1055            return null;
1056        }
1057    }
1058
1059    /**
1060     * Returns a list of application processes that are running on the device.
1061     *
1062     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
1063     * running processes (it will not return an empty list).  This list ordering is not
1064     * specified.
1065     */
1066    public List<RunningAppProcessInfo> getRunningAppProcesses() {
1067        try {
1068            return ActivityManagerNative.getDefault().getRunningAppProcesses();
1069        } catch (RemoteException e) {
1070            return null;
1071        }
1072    }
1073
1074    /**
1075     * Return information about the memory usage of one or more processes.
1076     *
1077     * @param pids The pids of the processes whose memory usage is to be
1078     * retrieved.
1079     * @return Returns an array of memory information, one for each
1080     * requested pid.
1081     */
1082    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
1083        try {
1084            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
1085        } catch (RemoteException e) {
1086            return null;
1087        }
1088    }
1089
1090    /**
1091     * @deprecated This is now just a wrapper for
1092     * {@link #killBackgroundProcesses(String)}; the previous behavior here
1093     * is no longer available to applications because it allows them to
1094     * break other applications by removing their alarms, stopping their
1095     * services, etc.
1096     */
1097    @Deprecated
1098    public void restartPackage(String packageName) {
1099        killBackgroundProcesses(packageName);
1100    }
1101
1102    /**
1103     * Have the system immediately kill all background processes associated
1104     * with the given package.  This is the same as the kernel killing those
1105     * processes to reclaim memory; the system will take care of restarting
1106     * these processes in the future as needed.
1107     *
1108     * <p>You must hold the permission
1109     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
1110     * call this method.
1111     *
1112     * @param packageName The name of the package whose processes are to
1113     * be killed.
1114     */
1115    public void killBackgroundProcesses(String packageName) {
1116        try {
1117            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName);
1118        } catch (RemoteException e) {
1119        }
1120    }
1121
1122    /**
1123     * Have the system perform a force stop of everything associated with
1124     * the given application package.  All processes that share its uid
1125     * will be killed, all services it has running stopped, all activities
1126     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
1127     * broadcast will be sent, so that any of its registered alarms can
1128     * be stopped, notifications removed, etc.
1129     *
1130     * <p>You must hold the permission
1131     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
1132     * call this method.
1133     *
1134     * @param packageName The name of the package to be stopped.
1135     *
1136     * @hide This is not available to third party applications due to
1137     * it allowing them to break other applications by stopping their
1138     * services, removing their alarms, etc.
1139     */
1140    public void forceStopPackage(String packageName) {
1141        try {
1142            ActivityManagerNative.getDefault().forceStopPackage(packageName);
1143        } catch (RemoteException e) {
1144        }
1145    }
1146
1147    /**
1148     * Get the device configuration attributes.
1149     */
1150    public ConfigurationInfo getDeviceConfigurationInfo() {
1151        try {
1152            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
1153        } catch (RemoteException e) {
1154        }
1155        return null;
1156    }
1157
1158    /**
1159     * Get the preferred density of icons for the launcher. This is used when
1160     * custom drawables are created (e.g., for shortcuts).
1161     *
1162     * @return density in terms of DPI
1163     */
1164    public int getLauncherLargeIconDensity() {
1165        final Resources res = mContext.getResources();
1166        final int density = res.getDisplayMetrics().densityDpi;
1167
1168        if ((res.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
1169                != Configuration.SCREENLAYOUT_SIZE_XLARGE) {
1170            return density;
1171        }
1172
1173        switch (density) {
1174            case DisplayMetrics.DENSITY_LOW:
1175                return DisplayMetrics.DENSITY_MEDIUM;
1176            case DisplayMetrics.DENSITY_MEDIUM:
1177                return DisplayMetrics.DENSITY_HIGH;
1178            case DisplayMetrics.DENSITY_HIGH:
1179                return DisplayMetrics.DENSITY_XHIGH;
1180            case DisplayMetrics.DENSITY_XHIGH:
1181                return DisplayMetrics.DENSITY_MEDIUM * 2;
1182            default:
1183                return density;
1184        }
1185    }
1186
1187    /**
1188     * Get the preferred launcher icon size. This is used when custom drawables
1189     * are created (e.g., for shortcuts).
1190     *
1191     * @return dimensions of square icons in terms of pixels
1192     */
1193    public int getLauncherLargeIconSize() {
1194        final Resources res = mContext.getResources();
1195        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
1196
1197        if ((res.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
1198                != Configuration.SCREENLAYOUT_SIZE_XLARGE) {
1199            return size;
1200        }
1201
1202        final int density = res.getDisplayMetrics().densityDpi;
1203
1204        switch (density) {
1205            case DisplayMetrics.DENSITY_LOW:
1206                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
1207            case DisplayMetrics.DENSITY_MEDIUM:
1208                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
1209            case DisplayMetrics.DENSITY_HIGH:
1210                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1211            case DisplayMetrics.DENSITY_XHIGH:
1212                return (size * DisplayMetrics.DENSITY_MEDIUM * 2) / DisplayMetrics.DENSITY_XHIGH;
1213            default:
1214                return size;
1215        }
1216    }
1217
1218    /**
1219     * Returns "true" if the user interface is currently being messed with
1220     * by a monkey.
1221     */
1222    public static boolean isUserAMonkey() {
1223        try {
1224            return ActivityManagerNative.getDefault().isUserAMonkey();
1225        } catch (RemoteException e) {
1226        }
1227        return false;
1228    }
1229
1230    /**
1231     * Returns "true" if device is running in a test harness.
1232     */
1233    public static boolean isRunningInTestHarness() {
1234        return SystemProperties.getBoolean("ro.test_harness", false);
1235    }
1236}
1237