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