ActivityManager.java revision 9066cfe9886ac131c34d59ed0e2d287b0e3c0087
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.ConfigurationInfo;
23import android.content.pm.IPackageDataObserver;
24import android.graphics.Bitmap;
25import android.os.RemoteException;
26import android.os.Handler;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.text.TextUtils;
30import java.util.List;
31
32/**
33 * Interact with the overall activities running in the system.
34 */
35public class ActivityManager {
36    private static String TAG = "ActivityManager";
37    private static boolean DEBUG = false;
38    private static boolean localLOGV = DEBUG || android.util.Config.LOGV;
39
40    private final Context mContext;
41    private final Handler mHandler;
42
43    /*package*/ ActivityManager(Context context, Handler handler) {
44        mContext = context;
45        mHandler = handler;
46    }
47
48    /**
49     * Information you can retrieve about tasks that the user has most recently
50     * started or visited.
51     */
52    public static class RecentTaskInfo implements Parcelable {
53        /**
54         * If this task is currently running, this is the identifier for it.
55         * If it is not running, this will be -1.
56         */
57        public int id;
58
59        /**
60         * The original Intent used to launch the task.  You can use this
61         * Intent to re-launch the task (if it is no longer running) or bring
62         * the current task to the front.
63         */
64        public Intent baseIntent;
65
66        /**
67         * If this task was started from an alias, this is the actual
68         * activity component that was initially started; the component of
69         * the baseIntent in this case is the name of the actual activity
70         * implementation that the alias referred to.  Otherwise, this is null.
71         */
72        public ComponentName origActivity;
73
74        public RecentTaskInfo() {
75        }
76
77        public int describeContents() {
78            return 0;
79        }
80
81        public void writeToParcel(Parcel dest, int flags) {
82            dest.writeInt(id);
83            if (baseIntent != null) {
84                dest.writeInt(1);
85                baseIntent.writeToParcel(dest, 0);
86            } else {
87                dest.writeInt(0);
88            }
89            ComponentName.writeToParcel(origActivity, dest);
90        }
91
92        public void readFromParcel(Parcel source) {
93            id = source.readInt();
94            if (source.readInt() != 0) {
95                baseIntent = Intent.CREATOR.createFromParcel(source);
96            } else {
97                baseIntent = null;
98            }
99            origActivity = ComponentName.readFromParcel(source);
100        }
101
102        public static final Creator<RecentTaskInfo> CREATOR
103                = new Creator<RecentTaskInfo>() {
104            public RecentTaskInfo createFromParcel(Parcel source) {
105                return new RecentTaskInfo(source);
106            }
107            public RecentTaskInfo[] newArray(int size) {
108                return new RecentTaskInfo[size];
109            }
110        };
111
112        private RecentTaskInfo(Parcel source) {
113            readFromParcel(source);
114        }
115    }
116
117    /**
118     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
119     * that have set their
120     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
121     */
122    public static final int RECENT_WITH_EXCLUDED = 0x0001;
123
124    /**
125     * Return a list of the tasks that the user has recently launched, with
126     * the most recent being first and older ones after in order.
127     *
128     * @param maxNum The maximum number of entries to return in the list.  The
129     * actual number returned may be smaller, depending on how many tasks the
130     * user has started and the maximum number the system can remember.
131     *
132     * @return Returns a list of RecentTaskInfo records describing each of
133     * the recent tasks.
134     *
135     * @throws SecurityException Throws SecurityException if the caller does
136     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
137     */
138    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
139            throws SecurityException {
140        try {
141            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
142                    flags);
143        } catch (RemoteException e) {
144            // System dead, we will be dead too soon!
145            return null;
146        }
147    }
148
149    /**
150     * Information you can retrieve about a particular task that is currently
151     * "running" in the system.  Note that a running task does not mean the
152     * given task actual has a process it is actively running in; it simply
153     * means that the user has gone to it and never closed it, but currently
154     * the system may have killed its process and is only holding on to its
155     * last state in order to restart it when the user returns.
156     */
157    public static class RunningTaskInfo implements Parcelable {
158        /**
159         * A unique identifier for this task.
160         */
161        public int id;
162
163        /**
164         * The component launched as the first activity in the task.  This can
165         * be considered the "application" of this task.
166         */
167        public ComponentName baseActivity;
168
169        /**
170         * The activity component at the top of the history stack of the task.
171         * This is what the user is currently doing.
172         */
173        public ComponentName topActivity;
174
175        /**
176         * Thumbnail representation of the task's current state.
177         */
178        public Bitmap thumbnail;
179
180        /**
181         * Description of the task's current state.
182         */
183        public CharSequence description;
184
185        /**
186         * Number of activities in this task.
187         */
188        public int numActivities;
189
190        /**
191         * Number of activities that are currently running (not stopped
192         * and persisted) in this task.
193         */
194        public int numRunning;
195
196        public RunningTaskInfo() {
197        }
198
199        public int describeContents() {
200            return 0;
201        }
202
203        public void writeToParcel(Parcel dest, int flags) {
204            dest.writeInt(id);
205            ComponentName.writeToParcel(baseActivity, dest);
206            ComponentName.writeToParcel(topActivity, dest);
207            if (thumbnail != null) {
208                dest.writeInt(1);
209                thumbnail.writeToParcel(dest, 0);
210            } else {
211                dest.writeInt(0);
212            }
213            TextUtils.writeToParcel(description, dest,
214                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
215            dest.writeInt(numActivities);
216            dest.writeInt(numRunning);
217        }
218
219        public void readFromParcel(Parcel source) {
220            id = source.readInt();
221            baseActivity = ComponentName.readFromParcel(source);
222            topActivity = ComponentName.readFromParcel(source);
223            if (source.readInt() != 0) {
224                thumbnail = Bitmap.CREATOR.createFromParcel(source);
225            } else {
226                thumbnail = null;
227            }
228            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
229            numActivities = source.readInt();
230            numRunning = source.readInt();
231        }
232
233        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
234            public RunningTaskInfo createFromParcel(Parcel source) {
235                return new RunningTaskInfo(source);
236            }
237            public RunningTaskInfo[] newArray(int size) {
238                return new RunningTaskInfo[size];
239            }
240        };
241
242        private RunningTaskInfo(Parcel source) {
243            readFromParcel(source);
244        }
245    }
246
247    /**
248     * Return a list of the tasks that are currently running, with
249     * the most recent being first and older ones after in order.  Note that
250     * "running" does not mean any of the task's code is currently loaded or
251     * activity -- the task may have been frozen by the system, so that it
252     * can be restarted in its previous state when next brought to the
253     * foreground.
254     *
255     * @param maxNum The maximum number of entries to return in the list.  The
256     * actual number returned may be smaller, depending on how many tasks the
257     * user has started.
258     *
259     * @return Returns a list of RunningTaskInfo records describing each of
260     * the running tasks.
261     *
262     * @throws SecurityException Throws SecurityException if the caller does
263     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
264     */
265    public List<RunningTaskInfo> getRunningTasks(int maxNum)
266            throws SecurityException {
267        try {
268            return (List<RunningTaskInfo>)ActivityManagerNative.getDefault()
269                    .getTasks(maxNum, 0, null);
270        } catch (RemoteException e) {
271            // System dead, we will be dead too soon!
272            return null;
273        }
274    }
275
276    /**
277     * Information you can retrieve about a particular Service that is
278     * currently running in the system.
279     */
280    public static class RunningServiceInfo implements Parcelable {
281        /**
282         * The service component.
283         */
284        public ComponentName service;
285
286        /**
287         * If non-zero, this is the process the service is running in.
288         */
289        public int pid;
290
291        /**
292         * The name of the process this service runs in.
293         */
294        public String process;
295
296        /**
297         * Set to true if the service has asked to run as a foreground process.
298         */
299        public boolean foreground;
300
301        /**
302         * The time when the service was first made activity, either by someone
303         * starting or binding to it.
304         */
305        public long activeSince;
306
307        /**
308         * Set to true if this service has been explicitly started.
309         */
310        public boolean started;
311
312        /**
313         * Number of clients connected to the service.
314         */
315        public int clientCount;
316
317        /**
318         * Number of times the service's process has crashed while the service
319         * is running.
320         */
321        public int crashCount;
322
323        /**
324         * The time when there was last activity in the service (either
325         * explicit requests to start it or clients binding to it).
326         */
327        public long lastActivityTime;
328
329        /**
330         * If non-zero, this service is not currently running, but scheduled to
331         * restart at the given time.
332         */
333        public long restarting;
334
335        public RunningServiceInfo() {
336        }
337
338        public int describeContents() {
339            return 0;
340        }
341
342        public void writeToParcel(Parcel dest, int flags) {
343            ComponentName.writeToParcel(service, dest);
344            dest.writeInt(pid);
345            dest.writeString(process);
346            dest.writeInt(foreground ? 1 : 0);
347            dest.writeLong(activeSince);
348            dest.writeInt(started ? 1 : 0);
349            dest.writeInt(clientCount);
350            dest.writeInt(crashCount);
351            dest.writeLong(lastActivityTime);
352            dest.writeLong(restarting);
353        }
354
355        public void readFromParcel(Parcel source) {
356            service = ComponentName.readFromParcel(source);
357            pid = source.readInt();
358            process = source.readString();
359            foreground = source.readInt() != 0;
360            activeSince = source.readLong();
361            started = source.readInt() != 0;
362            clientCount = source.readInt();
363            crashCount = source.readInt();
364            lastActivityTime = source.readLong();
365            restarting = source.readLong();
366        }
367
368        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
369            public RunningServiceInfo createFromParcel(Parcel source) {
370                return new RunningServiceInfo(source);
371            }
372            public RunningServiceInfo[] newArray(int size) {
373                return new RunningServiceInfo[size];
374            }
375        };
376
377        private RunningServiceInfo(Parcel source) {
378            readFromParcel(source);
379        }
380    }
381
382    /**
383     * Return a list of the services that are currently running.
384     *
385     * @param maxNum The maximum number of entries to return in the list.  The
386     * actual number returned may be smaller, depending on how many services
387     * are running.
388     *
389     * @return Returns a list of RunningServiceInfo records describing each of
390     * the running tasks.
391     */
392    public List<RunningServiceInfo> getRunningServices(int maxNum)
393            throws SecurityException {
394        try {
395            return (List<RunningServiceInfo>)ActivityManagerNative.getDefault()
396                    .getServices(maxNum, 0);
397        } catch (RemoteException e) {
398            // System dead, we will be dead too soon!
399            return null;
400        }
401    }
402
403    /**
404     * Information you can retrieve about the available memory through
405     * {@link ActivityManager#getMemoryInfo}.
406     */
407    public static class MemoryInfo implements Parcelable {
408        /**
409         * The total available memory on the system.  This number should not
410         * be considered absolute: due to the nature of the kernel, a significant
411         * portion of this memory is actually in use and needed for the overall
412         * system to run well.
413         */
414        public long availMem;
415
416        /**
417         * The threshold of {@link #availMem} at which we consider memory to be
418         * low and start killing background services and other non-extraneous
419         * processes.
420         */
421        public long threshold;
422
423        /**
424         * Set to true if the system considers itself to currently be in a low
425         * memory situation.
426         */
427        public boolean lowMemory;
428
429        public MemoryInfo() {
430        }
431
432        public int describeContents() {
433            return 0;
434        }
435
436        public void writeToParcel(Parcel dest, int flags) {
437            dest.writeLong(availMem);
438            dest.writeLong(threshold);
439            dest.writeInt(lowMemory ? 1 : 0);
440        }
441
442        public void readFromParcel(Parcel source) {
443            availMem = source.readLong();
444            threshold = source.readLong();
445            lowMemory = source.readInt() != 0;
446        }
447
448        public static final Creator<MemoryInfo> CREATOR
449                = new Creator<MemoryInfo>() {
450            public MemoryInfo createFromParcel(Parcel source) {
451                return new MemoryInfo(source);
452            }
453            public MemoryInfo[] newArray(int size) {
454                return new MemoryInfo[size];
455            }
456        };
457
458        private MemoryInfo(Parcel source) {
459            readFromParcel(source);
460        }
461    }
462
463    public void getMemoryInfo(MemoryInfo outInfo) {
464        try {
465            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
466        } catch (RemoteException e) {
467        }
468    }
469
470    /**
471     * @hide
472     */
473    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
474        try {
475            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
476                    observer);
477        } catch (RemoteException e) {
478            return false;
479        }
480    }
481
482    /**
483     * Information you can retrieve about any processes that are in an error condition.
484     */
485    public static class ProcessErrorStateInfo implements Parcelable {
486        /**
487         * Condition codes
488         */
489        public static final int NO_ERROR = 0;
490        public static final int CRASHED = 1;
491        public static final int NOT_RESPONDING = 2;
492
493        /**
494         * The condition that the process is in.
495         */
496        public int condition;
497
498        /**
499         * The process name in which the crash or error occurred.
500         */
501        public String processName;
502
503        /**
504         * The pid of this process; 0 if none
505         */
506        public int pid;
507
508        /**
509         * The kernel user-ID that has been assigned to this process;
510         * currently this is not a unique ID (multiple applications can have
511         * the same uid).
512         */
513        public int uid;
514
515        /**
516         * The tag that was provided when the process crashed.
517         */
518        public String tag;
519
520        /**
521         * A short message describing the error condition.
522         */
523        public String shortMsg;
524
525        /**
526         * A long message describing the error condition.
527         */
528        public String longMsg;
529
530        /**
531         * Raw data about the crash (typically a stack trace).
532         */
533        public byte[] crashData;
534
535        public ProcessErrorStateInfo() {
536        }
537
538        public int describeContents() {
539            return 0;
540        }
541
542        public void writeToParcel(Parcel dest, int flags) {
543            dest.writeInt(condition);
544            dest.writeString(processName);
545            dest.writeInt(pid);
546            dest.writeInt(uid);
547            dest.writeString(tag);
548            dest.writeString(shortMsg);
549            dest.writeString(longMsg);
550            dest.writeInt(crashData == null ? -1 : crashData.length);
551            dest.writeByteArray(crashData);
552        }
553
554        public void readFromParcel(Parcel source) {
555            condition = source.readInt();
556            processName = source.readString();
557            pid = source.readInt();
558            uid = source.readInt();
559            tag = source.readString();
560            shortMsg = source.readString();
561            longMsg = source.readString();
562            int cdLen = source.readInt();
563            if (cdLen == -1) {
564                crashData = null;
565            } else {
566                crashData = new byte[cdLen];
567                source.readByteArray(crashData);
568            }
569        }
570
571        public static final Creator<ProcessErrorStateInfo> CREATOR =
572                new Creator<ProcessErrorStateInfo>() {
573            public ProcessErrorStateInfo createFromParcel(Parcel source) {
574                return new ProcessErrorStateInfo(source);
575            }
576            public ProcessErrorStateInfo[] newArray(int size) {
577                return new ProcessErrorStateInfo[size];
578            }
579        };
580
581        private ProcessErrorStateInfo(Parcel source) {
582            readFromParcel(source);
583        }
584    }
585
586    /**
587     * Returns a list of any processes that are currently in an error condition.  The result
588     * will be null if all processes are running properly at this time.
589     *
590     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
591     * current error conditions (it will not return an empty list).  This list ordering is not
592     * specified.
593     */
594    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
595        try {
596            return ActivityManagerNative.getDefault().getProcessesInErrorState();
597        } catch (RemoteException e) {
598            return null;
599        }
600    }
601
602    /**
603     * Information you can retrieve about a running process.
604     */
605    public static class RunningAppProcessInfo implements Parcelable {
606        /**
607         * The name of the process that this object is associated with
608         */
609        public String processName;
610
611        /**
612         * The pid of this process; 0 if none
613         */
614        public int pid;
615
616        public String pkgList[];
617
618        /**
619         * Constant for {@link #importance}: this process is running the
620         * foreground UI.
621         */
622        public static final int IMPORTANCE_FOREGROUND = 100;
623
624        /**
625         * Constant for {@link #importance}: this process is running something
626         * that is considered to be actively visible to the user.
627         */
628        public static final int IMPORTANCE_VISIBLE = 200;
629
630        /**
631         * Constant for {@link #importance}: this process is contains services
632         * that should remain running.
633         */
634        public static final int IMPORTANCE_SERVICE = 300;
635
636        /**
637         * Constant for {@link #importance}: this process process contains
638         * background code that is expendable.
639         */
640        public static final int IMPORTANCE_BACKGROUND = 400;
641
642        /**
643         * Constant for {@link #importance}: this process is empty of any
644         * actively running code.
645         */
646        public static final int IMPORTANCE_EMPTY = 500;
647
648        /**
649         * The relative importance level that the system places on this
650         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
651         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
652         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
653         * constants are numbered so that "more important" values are always
654         * smaller than "less important" values.
655         */
656        public int importance;
657
658        /**
659         * An additional ordering within a particular {@link #importance}
660         * category, providing finer-grained information about the relative
661         * utility of processes within a category.  This number means nothing
662         * except that a smaller values are more recently used (and thus
663         * more important).  Currently an LRU value is only maintained for
664         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
665         * be maintained in the future.
666         */
667        public int lru;
668
669        public RunningAppProcessInfo() {
670            importance = IMPORTANCE_FOREGROUND;
671        }
672
673        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
674            processName = pProcessName;
675            pid = pPid;
676            pkgList = pArr;
677        }
678
679        public int describeContents() {
680            return 0;
681        }
682
683        public void writeToParcel(Parcel dest, int flags) {
684            dest.writeString(processName);
685            dest.writeInt(pid);
686            dest.writeStringArray(pkgList);
687            dest.writeInt(importance);
688            dest.writeInt(lru);
689        }
690
691        public void readFromParcel(Parcel source) {
692            processName = source.readString();
693            pid = source.readInt();
694            pkgList = source.readStringArray();
695            importance = source.readInt();
696            lru = source.readInt();
697        }
698
699        public static final Creator<RunningAppProcessInfo> CREATOR =
700            new Creator<RunningAppProcessInfo>() {
701            public RunningAppProcessInfo createFromParcel(Parcel source) {
702                return new RunningAppProcessInfo(source);
703            }
704            public RunningAppProcessInfo[] newArray(int size) {
705                return new RunningAppProcessInfo[size];
706            }
707        };
708
709        private RunningAppProcessInfo(Parcel source) {
710            readFromParcel(source);
711        }
712    }
713
714    /**
715     * Returns a list of application processes that are running on the device.
716     *
717     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
718     * running processes (it will not return an empty list).  This list ordering is not
719     * specified.
720     */
721    public List<RunningAppProcessInfo> getRunningAppProcesses() {
722        try {
723            return ActivityManagerNative.getDefault().getRunningAppProcesses();
724        } catch (RemoteException e) {
725            return null;
726        }
727    }
728
729    /**
730     * Have the system perform a force stop of everything associated with
731     * the given application package.  All processes that share its uid
732     * will be killed, all services it has running stopped, all activities
733     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
734     * broadcast will be sent, so that any of its registered alarms can
735     * be stopped, notifications removed, etc.
736     *
737     * <p>You must hold the permission
738     * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to
739     * call this method.
740     *
741     * @param packageName The name of the package to be stopped.
742     */
743    public void restartPackage(String packageName) {
744        try {
745            ActivityManagerNative.getDefault().restartPackage(packageName);
746        } catch (RemoteException e) {
747        }
748    }
749
750    /**
751     * Get the device configuration attributes.
752     */
753    public ConfigurationInfo getDeviceConfigurationInfo() {
754        try {
755            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
756        } catch (RemoteException e) {
757        }
758        return null;
759    }
760
761}
762