ActivityManager.java revision f26fd99a7c2f554b0297760bb66336473c7db61f
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.ServiceManager;
34import android.os.SystemProperties;
35import android.text.TextUtils;
36import android.util.DisplayMetrics;
37import android.util.Log;
38import com.android.internal.app.IUsageStats;
39import com.android.internal.os.PkgUsageStats;
40
41import java.util.ArrayList;
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 static class TaskThumbnails implements Parcelable {
401        public Bitmap mainThumbnail;
402
403        public int numSubThumbbails;
404
405        /** @hide */
406        public IThumbnailRetriever retriever;
407
408        /** @hide Magic for ActivityManagerService.  Not marshalled */
409        public ArrayList<Bitmap> otherThumbnails;
410
411        public TaskThumbnails() {
412        }
413
414        public Bitmap getSubThumbnail(int index) {
415            try {
416                return retriever.getThumbnail(index);
417            } catch (RemoteException e) {
418                return null;
419            }
420        }
421
422        public int describeContents() {
423            return 0;
424        }
425
426        public void writeToParcel(Parcel dest, int flags) {
427            if (mainThumbnail != null) {
428                dest.writeInt(1);
429                mainThumbnail.writeToParcel(dest, 0);
430            } else {
431                dest.writeInt(0);
432            }
433            dest.writeInt(numSubThumbbails);
434            dest.writeStrongInterface(retriever);
435        }
436
437        public void readFromParcel(Parcel source) {
438            if (source.readInt() != 0) {
439                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
440            } else {
441                mainThumbnail = null;
442            }
443            numSubThumbbails = source.readInt();
444            retriever = IThumbnailRetriever.Stub.asInterface(source.readStrongBinder());
445        }
446
447        public static final Creator<TaskThumbnails> CREATOR = new Creator<TaskThumbnails>() {
448            public TaskThumbnails createFromParcel(Parcel source) {
449                return new TaskThumbnails(source);
450            }
451            public TaskThumbnails[] newArray(int size) {
452                return new TaskThumbnails[size];
453            }
454        };
455
456        private TaskThumbnails(Parcel source) {
457            readFromParcel(source);
458        }
459    }
460
461    /** @hide */
462    public TaskThumbnails getTaskThumbnails(int id) throws SecurityException {
463        try {
464            return ActivityManagerNative.getDefault().getTaskThumbnails(id);
465        } catch (RemoteException e) {
466            // System dead, we will be dead too soon!
467            return null;
468        }
469    }
470
471    /**
472     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
473     * activity along with the task, so it is positioned immediately behind
474     * the task.
475     */
476    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
477
478    /**
479     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
480     * user-instigated action, so the current activity will not receive a
481     * hint that the user is leaving.
482     */
483    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
484
485    /**
486     * Ask that the task associated with a given task ID be moved to the
487     * front of the stack, so it is now visible to the user.  Requires that
488     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
489     * or a SecurityException will be thrown.
490     *
491     * @param taskId The identifier of the task to be moved, as found in
492     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
493     * @param flags Additional operational flags, 0 or more of
494     * {@link #MOVE_TASK_WITH_HOME}.
495     */
496    public void moveTaskToFront(int taskId, int flags) {
497        try {
498            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags);
499        } catch (RemoteException e) {
500            // System dead, we will be dead too soon!
501        }
502    }
503
504    /**
505     * Information you can retrieve about a particular Service that is
506     * currently running in the system.
507     */
508    public static class RunningServiceInfo implements Parcelable {
509        /**
510         * The service component.
511         */
512        public ComponentName service;
513
514        /**
515         * If non-zero, this is the process the service is running in.
516         */
517        public int pid;
518
519        /**
520         * The UID that owns this service.
521         */
522        public int uid;
523
524        /**
525         * The name of the process this service runs in.
526         */
527        public String process;
528
529        /**
530         * Set to true if the service has asked to run as a foreground process.
531         */
532        public boolean foreground;
533
534        /**
535         * The time when the service was first made active, either by someone
536         * starting or binding to it.  This
537         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
538         */
539        public long activeSince;
540
541        /**
542         * Set to true if this service has been explicitly started.
543         */
544        public boolean started;
545
546        /**
547         * Number of clients connected to the service.
548         */
549        public int clientCount;
550
551        /**
552         * Number of times the service's process has crashed while the service
553         * is running.
554         */
555        public int crashCount;
556
557        /**
558         * The time when there was last activity in the service (either
559         * explicit requests to start it or clients binding to it).  This
560         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
561         */
562        public long lastActivityTime;
563
564        /**
565         * If non-zero, this service is not currently running, but scheduled to
566         * restart at the given time.
567         */
568        public long restarting;
569
570        /**
571         * Bit for {@link #flags}: set if this service has been
572         * explicitly started.
573         */
574        public static final int FLAG_STARTED = 1<<0;
575
576        /**
577         * Bit for {@link #flags}: set if the service has asked to
578         * run as a foreground process.
579         */
580        public static final int FLAG_FOREGROUND = 1<<1;
581
582        /**
583         * Bit for {@link #flags): set if the service is running in a
584         * core system process.
585         */
586        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
587
588        /**
589         * Bit for {@link #flags): set if the service is running in a
590         * persistent process.
591         */
592        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
593
594        /**
595         * Running flags.
596         */
597        public int flags;
598
599        /**
600         * For special services that are bound to by system code, this is
601         * the package that holds the binding.
602         */
603        public String clientPackage;
604
605        /**
606         * For special services that are bound to by system code, this is
607         * a string resource providing a user-visible label for who the
608         * client is.
609         */
610        public int clientLabel;
611
612        public RunningServiceInfo() {
613        }
614
615        public int describeContents() {
616            return 0;
617        }
618
619        public void writeToParcel(Parcel dest, int flags) {
620            ComponentName.writeToParcel(service, dest);
621            dest.writeInt(pid);
622            dest.writeInt(uid);
623            dest.writeString(process);
624            dest.writeInt(foreground ? 1 : 0);
625            dest.writeLong(activeSince);
626            dest.writeInt(started ? 1 : 0);
627            dest.writeInt(clientCount);
628            dest.writeInt(crashCount);
629            dest.writeLong(lastActivityTime);
630            dest.writeLong(restarting);
631            dest.writeInt(this.flags);
632            dest.writeString(clientPackage);
633            dest.writeInt(clientLabel);
634        }
635
636        public void readFromParcel(Parcel source) {
637            service = ComponentName.readFromParcel(source);
638            pid = source.readInt();
639            uid = source.readInt();
640            process = source.readString();
641            foreground = source.readInt() != 0;
642            activeSince = source.readLong();
643            started = source.readInt() != 0;
644            clientCount = source.readInt();
645            crashCount = source.readInt();
646            lastActivityTime = source.readLong();
647            restarting = source.readLong();
648            flags = source.readInt();
649            clientPackage = source.readString();
650            clientLabel = source.readInt();
651        }
652
653        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
654            public RunningServiceInfo createFromParcel(Parcel source) {
655                return new RunningServiceInfo(source);
656            }
657            public RunningServiceInfo[] newArray(int size) {
658                return new RunningServiceInfo[size];
659            }
660        };
661
662        private RunningServiceInfo(Parcel source) {
663            readFromParcel(source);
664        }
665    }
666
667    /**
668     * Return a list of the services that are currently running.
669     *
670     * @param maxNum The maximum number of entries to return in the list.  The
671     * actual number returned may be smaller, depending on how many services
672     * are running.
673     *
674     * @return Returns a list of RunningServiceInfo records describing each of
675     * the running tasks.
676     */
677    public List<RunningServiceInfo> getRunningServices(int maxNum)
678            throws SecurityException {
679        try {
680            return (List<RunningServiceInfo>)ActivityManagerNative.getDefault()
681                    .getServices(maxNum, 0);
682        } catch (RemoteException e) {
683            // System dead, we will be dead too soon!
684            return null;
685        }
686    }
687
688    /**
689     * Returns a PendingIntent you can start to show a control panel for the
690     * given running service.  If the service does not have a control panel,
691     * null is returned.
692     */
693    public PendingIntent getRunningServiceControlPanel(ComponentName service)
694            throws SecurityException {
695        try {
696            return ActivityManagerNative.getDefault()
697                    .getRunningServiceControlPanel(service);
698        } catch (RemoteException e) {
699            // System dead, we will be dead too soon!
700            return null;
701        }
702    }
703
704    /**
705     * Information you can retrieve about the available memory through
706     * {@link ActivityManager#getMemoryInfo}.
707     */
708    public static class MemoryInfo implements Parcelable {
709        /**
710         * The total available memory on the system.  This number should not
711         * be considered absolute: due to the nature of the kernel, a significant
712         * portion of this memory is actually in use and needed for the overall
713         * system to run well.
714         */
715        public long availMem;
716
717        /**
718         * The threshold of {@link #availMem} at which we consider memory to be
719         * low and start killing background services and other non-extraneous
720         * processes.
721         */
722        public long threshold;
723
724        /**
725         * Set to true if the system considers itself to currently be in a low
726         * memory situation.
727         */
728        public boolean lowMemory;
729
730        public MemoryInfo() {
731        }
732
733        public int describeContents() {
734            return 0;
735        }
736
737        public void writeToParcel(Parcel dest, int flags) {
738            dest.writeLong(availMem);
739            dest.writeLong(threshold);
740            dest.writeInt(lowMemory ? 1 : 0);
741        }
742
743        public void readFromParcel(Parcel source) {
744            availMem = source.readLong();
745            threshold = source.readLong();
746            lowMemory = source.readInt() != 0;
747        }
748
749        public static final Creator<MemoryInfo> CREATOR
750                = new Creator<MemoryInfo>() {
751            public MemoryInfo createFromParcel(Parcel source) {
752                return new MemoryInfo(source);
753            }
754            public MemoryInfo[] newArray(int size) {
755                return new MemoryInfo[size];
756            }
757        };
758
759        private MemoryInfo(Parcel source) {
760            readFromParcel(source);
761        }
762    }
763
764    public void getMemoryInfo(MemoryInfo outInfo) {
765        try {
766            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
767        } catch (RemoteException e) {
768        }
769    }
770
771    /**
772     * @hide
773     */
774    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
775        try {
776            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
777                    observer);
778        } catch (RemoteException e) {
779            return false;
780        }
781    }
782
783    /**
784     * Information you can retrieve about any processes that are in an error condition.
785     */
786    public static class ProcessErrorStateInfo implements Parcelable {
787        /**
788         * Condition codes
789         */
790        public static final int NO_ERROR = 0;
791        public static final int CRASHED = 1;
792        public static final int NOT_RESPONDING = 2;
793
794        /**
795         * The condition that the process is in.
796         */
797        public int condition;
798
799        /**
800         * The process name in which the crash or error occurred.
801         */
802        public String processName;
803
804        /**
805         * The pid of this process; 0 if none
806         */
807        public int pid;
808
809        /**
810         * The kernel user-ID that has been assigned to this process;
811         * currently this is not a unique ID (multiple applications can have
812         * the same uid).
813         */
814        public int uid;
815
816        /**
817         * The activity name associated with the error, if known.  May be null.
818         */
819        public String tag;
820
821        /**
822         * A short message describing the error condition.
823         */
824        public String shortMsg;
825
826        /**
827         * A long message describing the error condition.
828         */
829        public String longMsg;
830
831        /**
832         * The stack trace where the error originated.  May be null.
833         */
834        public String stackTrace;
835
836        /**
837         * to be deprecated: This value will always be null.
838         */
839        public byte[] crashData = null;
840
841        public ProcessErrorStateInfo() {
842        }
843
844        public int describeContents() {
845            return 0;
846        }
847
848        public void writeToParcel(Parcel dest, int flags) {
849            dest.writeInt(condition);
850            dest.writeString(processName);
851            dest.writeInt(pid);
852            dest.writeInt(uid);
853            dest.writeString(tag);
854            dest.writeString(shortMsg);
855            dest.writeString(longMsg);
856            dest.writeString(stackTrace);
857        }
858
859        public void readFromParcel(Parcel source) {
860            condition = source.readInt();
861            processName = source.readString();
862            pid = source.readInt();
863            uid = source.readInt();
864            tag = source.readString();
865            shortMsg = source.readString();
866            longMsg = source.readString();
867            stackTrace = source.readString();
868        }
869
870        public static final Creator<ProcessErrorStateInfo> CREATOR =
871                new Creator<ProcessErrorStateInfo>() {
872            public ProcessErrorStateInfo createFromParcel(Parcel source) {
873                return new ProcessErrorStateInfo(source);
874            }
875            public ProcessErrorStateInfo[] newArray(int size) {
876                return new ProcessErrorStateInfo[size];
877            }
878        };
879
880        private ProcessErrorStateInfo(Parcel source) {
881            readFromParcel(source);
882        }
883    }
884
885    /**
886     * Returns a list of any processes that are currently in an error condition.  The result
887     * will be null if all processes are running properly at this time.
888     *
889     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
890     * current error conditions (it will not return an empty list).  This list ordering is not
891     * specified.
892     */
893    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
894        try {
895            return ActivityManagerNative.getDefault().getProcessesInErrorState();
896        } catch (RemoteException e) {
897            return null;
898        }
899    }
900
901    /**
902     * Information you can retrieve about a running process.
903     */
904    public static class RunningAppProcessInfo implements Parcelable {
905        /**
906         * The name of the process that this object is associated with
907         */
908        public String processName;
909
910        /**
911         * The pid of this process; 0 if none
912         */
913        public int pid;
914
915        /**
916         * The user id of this process.
917         */
918        public int uid;
919
920        /**
921         * All packages that have been loaded into the process.
922         */
923        public String pkgList[];
924
925        /**
926         * Constant for {@link #flags}: this is an app that is unable to
927         * correctly save its state when going to the background,
928         * so it can not be killed while in the background.
929         * @hide
930         */
931        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
932
933        /**
934         * Constant for {@link #flags}: this process is associated with a
935         * persistent system app.
936         * @hide
937         */
938        public static final int FLAG_PERSISTENT = 1<<1;
939
940        /**
941         * Flags of information.  May be any of
942         * {@link #FLAG_CANT_SAVE_STATE}.
943         * @hide
944         */
945        public int flags;
946
947        /**
948         * Constant for {@link #importance}: this process is running the
949         * foreground UI.
950         */
951        public static final int IMPORTANCE_FOREGROUND = 100;
952
953        /**
954         * Constant for {@link #importance}: this process is running something
955         * that is actively visible to the user, though not in the immediate
956         * foreground.
957         */
958        public static final int IMPORTANCE_VISIBLE = 200;
959
960        /**
961         * Constant for {@link #importance}: this process is running something
962         * that is considered to be actively perceptible to the user.  An
963         * example would be an application performing background music playback.
964         */
965        public static final int IMPORTANCE_PERCEPTIBLE = 130;
966
967        /**
968         * Constant for {@link #importance}: this process is running an
969         * application that can not save its state, and thus can't be killed
970         * while in the background.
971         * @hide
972         */
973        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
974
975        /**
976         * Constant for {@link #importance}: this process is contains services
977         * that should remain running.
978         */
979        public static final int IMPORTANCE_SERVICE = 300;
980
981        /**
982         * Constant for {@link #importance}: this process process contains
983         * background code that is expendable.
984         */
985        public static final int IMPORTANCE_BACKGROUND = 400;
986
987        /**
988         * Constant for {@link #importance}: this process is empty of any
989         * actively running code.
990         */
991        public static final int IMPORTANCE_EMPTY = 500;
992
993        /**
994         * The relative importance level that the system places on this
995         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
996         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
997         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
998         * constants are numbered so that "more important" values are always
999         * smaller than "less important" values.
1000         */
1001        public int importance;
1002
1003        /**
1004         * An additional ordering within a particular {@link #importance}
1005         * category, providing finer-grained information about the relative
1006         * utility of processes within a category.  This number means nothing
1007         * except that a smaller values are more recently used (and thus
1008         * more important).  Currently an LRU value is only maintained for
1009         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1010         * be maintained in the future.
1011         */
1012        public int lru;
1013
1014        /**
1015         * Constant for {@link #importanceReasonCode}: nothing special has
1016         * been specified for the reason for this level.
1017         */
1018        public static final int REASON_UNKNOWN = 0;
1019
1020        /**
1021         * Constant for {@link #importanceReasonCode}: one of the application's
1022         * content providers is being used by another process.  The pid of
1023         * the client process is in {@link #importanceReasonPid} and the
1024         * target provider in this process is in
1025         * {@link #importanceReasonComponent}.
1026         */
1027        public static final int REASON_PROVIDER_IN_USE = 1;
1028
1029        /**
1030         * Constant for {@link #importanceReasonCode}: one of the application's
1031         * content providers is being used by another process.  The pid of
1032         * the client process is in {@link #importanceReasonPid} and the
1033         * target provider in this process is in
1034         * {@link #importanceReasonComponent}.
1035         */
1036        public static final int REASON_SERVICE_IN_USE = 2;
1037
1038        /**
1039         * The reason for {@link #importance}, if any.
1040         */
1041        public int importanceReasonCode;
1042
1043        /**
1044         * For the specified values of {@link #importanceReasonCode}, this
1045         * is the process ID of the other process that is a client of this
1046         * process.  This will be 0 if no other process is using this one.
1047         */
1048        public int importanceReasonPid;
1049
1050        /**
1051         * For the specified values of {@link #importanceReasonCode}, this
1052         * is the name of the component that is being used in this process.
1053         */
1054        public ComponentName importanceReasonComponent;
1055
1056        public RunningAppProcessInfo() {
1057            importance = IMPORTANCE_FOREGROUND;
1058            importanceReasonCode = REASON_UNKNOWN;
1059        }
1060
1061        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1062            processName = pProcessName;
1063            pid = pPid;
1064            pkgList = pArr;
1065        }
1066
1067        public int describeContents() {
1068            return 0;
1069        }
1070
1071        public void writeToParcel(Parcel dest, int flags) {
1072            dest.writeString(processName);
1073            dest.writeInt(pid);
1074            dest.writeInt(uid);
1075            dest.writeStringArray(pkgList);
1076            dest.writeInt(this.flags);
1077            dest.writeInt(importance);
1078            dest.writeInt(lru);
1079            dest.writeInt(importanceReasonCode);
1080            dest.writeInt(importanceReasonPid);
1081            ComponentName.writeToParcel(importanceReasonComponent, dest);
1082        }
1083
1084        public void readFromParcel(Parcel source) {
1085            processName = source.readString();
1086            pid = source.readInt();
1087            uid = source.readInt();
1088            pkgList = source.readStringArray();
1089            flags = source.readInt();
1090            importance = source.readInt();
1091            lru = source.readInt();
1092            importanceReasonCode = source.readInt();
1093            importanceReasonPid = source.readInt();
1094            importanceReasonComponent = ComponentName.readFromParcel(source);
1095        }
1096
1097        public static final Creator<RunningAppProcessInfo> CREATOR =
1098            new Creator<RunningAppProcessInfo>() {
1099            public RunningAppProcessInfo createFromParcel(Parcel source) {
1100                return new RunningAppProcessInfo(source);
1101            }
1102            public RunningAppProcessInfo[] newArray(int size) {
1103                return new RunningAppProcessInfo[size];
1104            }
1105        };
1106
1107        private RunningAppProcessInfo(Parcel source) {
1108            readFromParcel(source);
1109        }
1110    }
1111
1112    /**
1113     * Returns a list of application processes installed on external media
1114     * that are running on the device.
1115     *
1116     * @return Returns a list of ApplicationInfo records, or null if none
1117     * This list ordering is not specified.
1118     * @hide
1119     */
1120    public List<ApplicationInfo> getRunningExternalApplications() {
1121        try {
1122            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1123        } catch (RemoteException e) {
1124            return null;
1125        }
1126    }
1127
1128    /**
1129     * Returns a list of application processes that are running on the device.
1130     *
1131     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
1132     * running processes (it will not return an empty list).  This list ordering is not
1133     * specified.
1134     */
1135    public List<RunningAppProcessInfo> getRunningAppProcesses() {
1136        try {
1137            return ActivityManagerNative.getDefault().getRunningAppProcesses();
1138        } catch (RemoteException e) {
1139            return null;
1140        }
1141    }
1142
1143    /**
1144     * Return information about the memory usage of one or more processes.
1145     *
1146     * @param pids The pids of the processes whose memory usage is to be
1147     * retrieved.
1148     * @return Returns an array of memory information, one for each
1149     * requested pid.
1150     */
1151    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
1152        try {
1153            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
1154        } catch (RemoteException e) {
1155            return null;
1156        }
1157    }
1158
1159    /**
1160     * @deprecated This is now just a wrapper for
1161     * {@link #killBackgroundProcesses(String)}; the previous behavior here
1162     * is no longer available to applications because it allows them to
1163     * break other applications by removing their alarms, stopping their
1164     * services, etc.
1165     */
1166    @Deprecated
1167    public void restartPackage(String packageName) {
1168        killBackgroundProcesses(packageName);
1169    }
1170
1171    /**
1172     * Have the system immediately kill all background processes associated
1173     * with the given package.  This is the same as the kernel killing those
1174     * processes to reclaim memory; the system will take care of restarting
1175     * these processes in the future as needed.
1176     *
1177     * <p>You must hold the permission
1178     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
1179     * call this method.
1180     *
1181     * @param packageName The name of the package whose processes are to
1182     * be killed.
1183     */
1184    public void killBackgroundProcesses(String packageName) {
1185        try {
1186            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName);
1187        } catch (RemoteException e) {
1188        }
1189    }
1190
1191    /**
1192     * Have the system perform a force stop of everything associated with
1193     * the given application package.  All processes that share its uid
1194     * will be killed, all services it has running stopped, all activities
1195     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
1196     * broadcast will be sent, so that any of its registered alarms can
1197     * be stopped, notifications removed, etc.
1198     *
1199     * <p>You must hold the permission
1200     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
1201     * call this method.
1202     *
1203     * @param packageName The name of the package to be stopped.
1204     *
1205     * @hide This is not available to third party applications due to
1206     * it allowing them to break other applications by stopping their
1207     * services, removing their alarms, etc.
1208     */
1209    public void forceStopPackage(String packageName) {
1210        try {
1211            ActivityManagerNative.getDefault().forceStopPackage(packageName);
1212        } catch (RemoteException e) {
1213        }
1214    }
1215
1216    /**
1217     * Get the device configuration attributes.
1218     */
1219    public ConfigurationInfo getDeviceConfigurationInfo() {
1220        try {
1221            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
1222        } catch (RemoteException e) {
1223        }
1224        return null;
1225    }
1226
1227    /**
1228     * Get the preferred density of icons for the launcher. This is used when
1229     * custom drawables are created (e.g., for shortcuts).
1230     *
1231     * @return density in terms of DPI
1232     */
1233    public int getLauncherLargeIconDensity() {
1234        final Resources res = mContext.getResources();
1235        final int density = res.getDisplayMetrics().densityDpi;
1236
1237        if ((res.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
1238                != Configuration.SCREENLAYOUT_SIZE_XLARGE) {
1239            return density;
1240        }
1241
1242        switch (density) {
1243            case DisplayMetrics.DENSITY_LOW:
1244                return DisplayMetrics.DENSITY_MEDIUM;
1245            case DisplayMetrics.DENSITY_MEDIUM:
1246                return DisplayMetrics.DENSITY_HIGH;
1247            case DisplayMetrics.DENSITY_HIGH:
1248                return DisplayMetrics.DENSITY_XHIGH;
1249            case DisplayMetrics.DENSITY_XHIGH:
1250                return DisplayMetrics.DENSITY_MEDIUM * 2;
1251            default:
1252                return density;
1253        }
1254    }
1255
1256    /**
1257     * Get the preferred launcher icon size. This is used when custom drawables
1258     * are created (e.g., for shortcuts).
1259     *
1260     * @return dimensions of square icons in terms of pixels
1261     */
1262    public int getLauncherLargeIconSize() {
1263        final Resources res = mContext.getResources();
1264        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
1265
1266        if ((res.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
1267                != Configuration.SCREENLAYOUT_SIZE_XLARGE) {
1268            return size;
1269        }
1270
1271        final int density = res.getDisplayMetrics().densityDpi;
1272
1273        switch (density) {
1274            case DisplayMetrics.DENSITY_LOW:
1275                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
1276            case DisplayMetrics.DENSITY_MEDIUM:
1277                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
1278            case DisplayMetrics.DENSITY_HIGH:
1279                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1280            case DisplayMetrics.DENSITY_XHIGH:
1281                return (size * DisplayMetrics.DENSITY_MEDIUM * 2) / DisplayMetrics.DENSITY_XHIGH;
1282            default:
1283                return size;
1284        }
1285    }
1286
1287    /**
1288     * Returns "true" if the user interface is currently being messed with
1289     * by a monkey.
1290     */
1291    public static boolean isUserAMonkey() {
1292        try {
1293            return ActivityManagerNative.getDefault().isUserAMonkey();
1294        } catch (RemoteException e) {
1295        }
1296        return false;
1297    }
1298
1299    /**
1300     * Returns "true" if device is running in a test harness.
1301     */
1302    public static boolean isRunningInTestHarness() {
1303        return SystemProperties.getBoolean("ro.test_harness", false);
1304    }
1305
1306    /**
1307     * Returns the launch count of each installed package.
1308     *
1309     * @hide
1310     */
1311    public Map<String, Integer> getAllPackageLaunchCounts() {
1312        try {
1313            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
1314                    ServiceManager.getService("usagestats"));
1315            if (usageStatsService == null) {
1316                return new HashMap<String, Integer>();
1317            }
1318
1319            PkgUsageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats();
1320            if (allPkgUsageStats == null) {
1321                return new HashMap<String, Integer>();
1322            }
1323
1324            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
1325            for (PkgUsageStats pkgUsageStats : allPkgUsageStats) {
1326                launchCounts.put(pkgUsageStats.packageName, pkgUsageStats.launchCount);
1327            }
1328
1329            return launchCounts;
1330        } catch (RemoteException e) {
1331            Log.w(TAG, "Could not query launch counts", e);
1332            return new HashMap<String, Integer>();
1333        }
1334    }
1335}
1336