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