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