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