ActivityManager.java revision 80a4af2bbc6af42ae605e454bf89558e564f5244
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;
21import com.android.internal.util.MemInfoReader;
22
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ApplicationInfo;
27import android.content.pm.ConfigurationInfo;
28import android.content.pm.IPackageDataObserver;
29import android.content.pm.PackageManager;
30import android.content.res.Resources;
31import android.graphics.Bitmap;
32import android.graphics.Point;
33import android.hardware.display.DisplayManager;
34import android.os.Binder;
35import android.os.Bundle;
36import android.os.Debug;
37import android.os.Handler;
38import android.os.Parcel;
39import android.os.Parcelable;
40import android.os.Process;
41import android.os.RemoteException;
42import android.os.ServiceManager;
43import android.os.SystemProperties;
44import android.os.UserHandle;
45import android.text.TextUtils;
46import android.util.DisplayMetrics;
47import android.util.Log;
48import android.util.Slog;
49import android.view.Display;
50
51import java.util.HashMap;
52import java.util.List;
53import java.util.Map;
54
55/**
56 * Interact with the overall activities running in the system.
57 */
58public class ActivityManager {
59    private static String TAG = "ActivityManager";
60    private static boolean localLOGV = false;
61
62    private final Context mContext;
63    private final Handler mHandler;
64
65    /**
66     * Result for IActivityManager.startActivity: an error where the
67     * start had to be canceled.
68     * @hide
69     */
70    public static final int START_CANCELED = -6;
71
72    /**
73     * Result for IActivityManager.startActivity: an error where the
74     * thing being started is not an activity.
75     * @hide
76     */
77    public static final int START_NOT_ACTIVITY = -5;
78
79    /**
80     * Result for IActivityManager.startActivity: an error where the
81     * caller does not have permission to start the activity.
82     * @hide
83     */
84    public static final int START_PERMISSION_DENIED = -4;
85
86    /**
87     * Result for IActivityManager.startActivity: an error where the
88     * caller has requested both to forward a result and to receive
89     * a result.
90     * @hide
91     */
92    public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
93
94    /**
95     * Result for IActivityManager.startActivity: an error where the
96     * requested class is not found.
97     * @hide
98     */
99    public static final int START_CLASS_NOT_FOUND = -2;
100
101    /**
102     * Result for IActivityManager.startActivity: an error where the
103     * given Intent could not be resolved to an activity.
104     * @hide
105     */
106    public static final int START_INTENT_NOT_RESOLVED = -1;
107
108    /**
109     * Result for IActivityManaqer.startActivity: the activity was started
110     * successfully as normal.
111     * @hide
112     */
113    public static final int START_SUCCESS = 0;
114
115    /**
116     * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
117     * be executed if it is the recipient, and that is indeed the case.
118     * @hide
119     */
120    public static final int START_RETURN_INTENT_TO_CALLER = 1;
121
122    /**
123     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
124     * a task was simply brought to the foreground.
125     * @hide
126     */
127    public static final int START_TASK_TO_FRONT = 2;
128
129    /**
130     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
131     * the given Intent was given to the existing top activity.
132     * @hide
133     */
134    public static final int START_DELIVERED_TO_TOP = 3;
135
136    /**
137     * Result for IActivityManaqer.startActivity: request was canceled because
138     * app switches are temporarily canceled to ensure the user's last request
139     * (such as pressing home) is performed.
140     * @hide
141     */
142    public static final int START_SWITCHES_CANCELED = 4;
143
144    /**
145     * Flag for IActivityManaqer.startActivity: do special start mode where
146     * a new activity is launched only if it is needed.
147     * @hide
148     */
149    public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
150
151    /**
152     * Flag for IActivityManaqer.startActivity: launch the app for
153     * debugging.
154     * @hide
155     */
156    public static final int START_FLAG_DEBUG = 1<<1;
157
158    /**
159     * Flag for IActivityManaqer.startActivity: launch the app for
160     * OpenGL tracing.
161     * @hide
162     */
163    public static final int START_FLAG_OPENGL_TRACES = 1<<2;
164
165    /**
166     * Flag for IActivityManaqer.startActivity: if the app is being
167     * launched for profiling, automatically stop the profiler once done.
168     * @hide
169     */
170    public static final int START_FLAG_AUTO_STOP_PROFILER = 1<<3;
171
172    /**
173     * Result for IActivityManaqer.broadcastIntent: success!
174     * @hide
175     */
176    public static final int BROADCAST_SUCCESS = 0;
177
178    /**
179     * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
180     * a sticky intent without appropriate permission.
181     * @hide
182     */
183    public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
184
185    /**
186     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
187     * for a sendBroadcast operation.
188     * @hide
189     */
190    public static final int INTENT_SENDER_BROADCAST = 1;
191
192    /**
193     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
194     * for a startActivity operation.
195     * @hide
196     */
197    public static final int INTENT_SENDER_ACTIVITY = 2;
198
199    /**
200     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
201     * for an activity result operation.
202     * @hide
203     */
204    public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
205
206    /**
207     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
208     * for a startService operation.
209     * @hide
210     */
211    public static final int INTENT_SENDER_SERVICE = 4;
212
213    /** @hide User operation call: success! */
214    public static final int USER_OP_SUCCESS = 0;
215
216    /** @hide User operation call: given user id is not known. */
217    public static final int USER_OP_UNKNOWN_USER = -1;
218
219    /** @hide User operation call: given user id is the current user, can't be stopped. */
220    public static final int USER_OP_IS_CURRENT = -2;
221
222    /*package*/ ActivityManager(Context context, Handler handler) {
223        mContext = context;
224        mHandler = handler;
225    }
226
227    /**
228     * Screen compatibility mode: the application most always run in
229     * compatibility mode.
230     * @hide
231     */
232    public static final int COMPAT_MODE_ALWAYS = -1;
233
234    /**
235     * Screen compatibility mode: the application can never run in
236     * compatibility mode.
237     * @hide
238     */
239    public static final int COMPAT_MODE_NEVER = -2;
240
241    /**
242     * Screen compatibility mode: unknown.
243     * @hide
244     */
245    public static final int COMPAT_MODE_UNKNOWN = -3;
246
247    /**
248     * Screen compatibility mode: the application currently has compatibility
249     * mode disabled.
250     * @hide
251     */
252    public static final int COMPAT_MODE_DISABLED = 0;
253
254    /**
255     * Screen compatibility mode: the application currently has compatibility
256     * mode enabled.
257     * @hide
258     */
259    public static final int COMPAT_MODE_ENABLED = 1;
260
261    /**
262     * Screen compatibility mode: request to toggle the application's
263     * compatibility mode.
264     * @hide
265     */
266    public static final int COMPAT_MODE_TOGGLE = 2;
267
268    /** @hide */
269    public int getFrontActivityScreenCompatMode() {
270        try {
271            return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
272        } catch (RemoteException e) {
273            // System dead, we will be dead too soon!
274            return 0;
275        }
276    }
277
278    /** @hide */
279    public void setFrontActivityScreenCompatMode(int mode) {
280        try {
281            ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
282        } catch (RemoteException e) {
283            // System dead, we will be dead too soon!
284        }
285    }
286
287    /** @hide */
288    public int getPackageScreenCompatMode(String packageName) {
289        try {
290            return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
291        } catch (RemoteException e) {
292            // System dead, we will be dead too soon!
293            return 0;
294        }
295    }
296
297    /** @hide */
298    public void setPackageScreenCompatMode(String packageName, int mode) {
299        try {
300            ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
301        } catch (RemoteException e) {
302            // System dead, we will be dead too soon!
303        }
304    }
305
306    /** @hide */
307    public boolean getPackageAskScreenCompat(String packageName) {
308        try {
309            return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
310        } catch (RemoteException e) {
311            // System dead, we will be dead too soon!
312            return false;
313        }
314    }
315
316    /** @hide */
317    public void setPackageAskScreenCompat(String packageName, boolean ask) {
318        try {
319            ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
320        } catch (RemoteException e) {
321            // System dead, we will be dead too soon!
322        }
323    }
324
325    /**
326     * Return the approximate per-application memory class of the current
327     * device.  This gives you an idea of how hard a memory limit you should
328     * impose on your application to let the overall system work best.  The
329     * returned value is in megabytes; the baseline Android memory class is
330     * 16 (which happens to be the Java heap limit of those devices); some
331     * device with more memory may return 24 or even higher numbers.
332     */
333    public int getMemoryClass() {
334        return staticGetMemoryClass();
335    }
336
337    /** @hide */
338    static public int staticGetMemoryClass() {
339        // Really brain dead right now -- just take this from the configured
340        // vm heap size, and assume it is in megabytes and thus ends with "m".
341        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
342        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
343            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
344        }
345        return staticGetLargeMemoryClass();
346    }
347
348    /**
349     * Return the approximate per-application memory class of the current
350     * device when an application is running with a large heap.  This is the
351     * space available for memory-intensive applications; most applications
352     * should not need this amount of memory, and should instead stay with the
353     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
354     * This may be the same size as {@link #getMemoryClass()} on memory
355     * constrained devices, or it may be significantly larger on devices with
356     * a large amount of available RAM.
357     *
358     * <p>The is the size of the application's Dalvik heap if it has
359     * specified <code>android:largeHeap="true"</code> in its manifest.
360     */
361    public int getLargeMemoryClass() {
362        return staticGetLargeMemoryClass();
363    }
364
365    /** @hide */
366    static public int staticGetLargeMemoryClass() {
367        // Really brain dead right now -- just take this from the configured
368        // vm heap size, and assume it is in megabytes and thus ends with "m".
369        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
370        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
371    }
372
373    /**
374     * Used by persistent processes to determine if they are running on a
375     * higher-end device so should be okay using hardware drawing acceleration
376     * (which tends to consume a lot more RAM).
377     * @hide
378     */
379    static public boolean isHighEndGfx() {
380        MemInfoReader reader = new MemInfoReader();
381        reader.readMemInfo();
382        if (reader.getTotalSize() >= (512*1024*1024)) {
383            // If the device has at least 512MB RAM available to the kernel,
384            // we can afford the overhead of graphics acceleration.
385            return true;
386        }
387
388        Display display = DisplayManager.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
389        Point p = new Point();
390        display.getRealSize(p);
391        int pixels = p.x * p.y;
392        if (pixels >= (1024*600)) {
393            // If this is a sufficiently large screen, then there are enough
394            // pixels on it that we'd really like to use hw drawing.
395            return true;
396        }
397        return false;
398    }
399
400    /**
401     * Use to decide whether the running device can be considered a "large
402     * RAM" device.  Exactly what memory limit large RAM is will vary, but
403     * it essentially means there is plenty of RAM to have lots of background
404     * processes running under decent loads.
405     * @hide
406     */
407    static public boolean isLargeRAM() {
408        MemInfoReader reader = new MemInfoReader();
409        reader.readMemInfo();
410        if (reader.getTotalSize() >= (640*1024*1024)) {
411            // Currently 640MB RAM available to the kernel is the point at
412            // which we have plenty of RAM to spare.
413            return true;
414        }
415        return false;
416    }
417
418    /**
419     * Information you can retrieve about tasks that the user has most recently
420     * started or visited.
421     */
422    public static class RecentTaskInfo implements Parcelable {
423        /**
424         * If this task is currently running, this is the identifier for it.
425         * If it is not running, this will be -1.
426         */
427        public int id;
428
429        /**
430         * The true identifier of this task, valid even if it is not running.
431         */
432        public int persistentId;
433
434        /**
435         * The original Intent used to launch the task.  You can use this
436         * Intent to re-launch the task (if it is no longer running) or bring
437         * the current task to the front.
438         */
439        public Intent baseIntent;
440
441        /**
442         * If this task was started from an alias, this is the actual
443         * activity component that was initially started; the component of
444         * the baseIntent in this case is the name of the actual activity
445         * implementation that the alias referred to.  Otherwise, this is null.
446         */
447        public ComponentName origActivity;
448
449        /**
450         * Description of the task's last state.
451         */
452        public CharSequence description;
453
454        public RecentTaskInfo() {
455        }
456
457        public int describeContents() {
458            return 0;
459        }
460
461        public void writeToParcel(Parcel dest, int flags) {
462            dest.writeInt(id);
463            dest.writeInt(persistentId);
464            if (baseIntent != null) {
465                dest.writeInt(1);
466                baseIntent.writeToParcel(dest, 0);
467            } else {
468                dest.writeInt(0);
469            }
470            ComponentName.writeToParcel(origActivity, dest);
471            TextUtils.writeToParcel(description, dest,
472                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
473        }
474
475        public void readFromParcel(Parcel source) {
476            id = source.readInt();
477            persistentId = source.readInt();
478            if (source.readInt() != 0) {
479                baseIntent = Intent.CREATOR.createFromParcel(source);
480            } else {
481                baseIntent = null;
482            }
483            origActivity = ComponentName.readFromParcel(source);
484            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
485        }
486
487        public static final Creator<RecentTaskInfo> CREATOR
488                = new Creator<RecentTaskInfo>() {
489            public RecentTaskInfo createFromParcel(Parcel source) {
490                return new RecentTaskInfo(source);
491            }
492            public RecentTaskInfo[] newArray(int size) {
493                return new RecentTaskInfo[size];
494            }
495        };
496
497        private RecentTaskInfo(Parcel source) {
498            readFromParcel(source);
499        }
500    }
501
502    /**
503     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
504     * that have set their
505     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
506     */
507    public static final int RECENT_WITH_EXCLUDED = 0x0001;
508
509    /**
510     * Provides a list that does not contain any
511     * recent tasks that currently are not available to the user.
512     */
513    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
514
515    /**
516     * Return a list of the tasks that the user has recently launched, with
517     * the most recent being first and older ones after in order.
518     *
519     * <p><b>Note: this method is only intended for debugging and presenting
520     * task management user interfaces</b>.  This should never be used for
521     * core logic in an application, such as deciding between different
522     * behaviors based on the information found here.  Such uses are
523     * <em>not</em> supported, and will likely break in the future.  For
524     * example, if multiple applications can be actively running at the
525     * same time, assumptions made about the meaning of the data here for
526     * purposes of control flow will be incorrect.</p>
527     *
528     * @param maxNum The maximum number of entries to return in the list.  The
529     * actual number returned may be smaller, depending on how many tasks the
530     * user has started and the maximum number the system can remember.
531     * @param flags Information about what to return.  May be any combination
532     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
533     *
534     * @return Returns a list of RecentTaskInfo records describing each of
535     * the recent tasks.
536     *
537     * @throws SecurityException Throws SecurityException if the caller does
538     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
539     */
540    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
541            throws SecurityException {
542        try {
543            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
544                    flags, UserHandle.myUserId());
545        } catch (RemoteException e) {
546            // System dead, we will be dead too soon!
547            return null;
548        }
549    }
550
551    /**
552     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
553     * specific user. It requires holding
554     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
555     * @param maxNum The maximum number of entries to return in the list.  The
556     * actual number returned may be smaller, depending on how many tasks the
557     * user has started and the maximum number the system can remember.
558     * @param flags Information about what to return.  May be any combination
559     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
560     *
561     * @return Returns a list of RecentTaskInfo records describing each of
562     * the recent tasks.
563     *
564     * @throws SecurityException Throws SecurityException if the caller does
565     * not hold the {@link android.Manifest.permission#GET_TASKS} or the
566     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
567     * @hide
568     */
569    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
570            throws SecurityException {
571        try {
572            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
573                    flags, userId);
574        } catch (RemoteException e) {
575            // System dead, we will be dead too soon!
576            return null;
577        }
578    }
579
580    /**
581     * Information you can retrieve about a particular task that is currently
582     * "running" in the system.  Note that a running task does not mean the
583     * given task actually has a process it is actively running in; it simply
584     * means that the user has gone to it and never closed it, but currently
585     * the system may have killed its process and is only holding on to its
586     * last state in order to restart it when the user returns.
587     */
588    public static class RunningTaskInfo implements Parcelable {
589        /**
590         * A unique identifier for this task.
591         */
592        public int id;
593
594        /**
595         * The component launched as the first activity in the task.  This can
596         * be considered the "application" of this task.
597         */
598        public ComponentName baseActivity;
599
600        /**
601         * The activity component at the top of the history stack of the task.
602         * This is what the user is currently doing.
603         */
604        public ComponentName topActivity;
605
606        /**
607         * Thumbnail representation of the task's current state.  Currently
608         * always null.
609         */
610        public Bitmap thumbnail;
611
612        /**
613         * Description of the task's current state.
614         */
615        public CharSequence description;
616
617        /**
618         * Number of activities in this task.
619         */
620        public int numActivities;
621
622        /**
623         * Number of activities that are currently running (not stopped
624         * and persisted) in this task.
625         */
626        public int numRunning;
627
628        public RunningTaskInfo() {
629        }
630
631        public int describeContents() {
632            return 0;
633        }
634
635        public void writeToParcel(Parcel dest, int flags) {
636            dest.writeInt(id);
637            ComponentName.writeToParcel(baseActivity, dest);
638            ComponentName.writeToParcel(topActivity, dest);
639            if (thumbnail != null) {
640                dest.writeInt(1);
641                thumbnail.writeToParcel(dest, 0);
642            } else {
643                dest.writeInt(0);
644            }
645            TextUtils.writeToParcel(description, dest,
646                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
647            dest.writeInt(numActivities);
648            dest.writeInt(numRunning);
649        }
650
651        public void readFromParcel(Parcel source) {
652            id = source.readInt();
653            baseActivity = ComponentName.readFromParcel(source);
654            topActivity = ComponentName.readFromParcel(source);
655            if (source.readInt() != 0) {
656                thumbnail = Bitmap.CREATOR.createFromParcel(source);
657            } else {
658                thumbnail = null;
659            }
660            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
661            numActivities = source.readInt();
662            numRunning = source.readInt();
663        }
664
665        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
666            public RunningTaskInfo createFromParcel(Parcel source) {
667                return new RunningTaskInfo(source);
668            }
669            public RunningTaskInfo[] newArray(int size) {
670                return new RunningTaskInfo[size];
671            }
672        };
673
674        private RunningTaskInfo(Parcel source) {
675            readFromParcel(source);
676        }
677    }
678
679    /**
680     * Return a list of the tasks that are currently running, with
681     * the most recent being first and older ones after in order.  Note that
682     * "running" does not mean any of the task's code is currently loaded or
683     * activity -- the task may have been frozen by the system, so that it
684     * can be restarted in its previous state when next brought to the
685     * foreground.
686     *
687     * @param maxNum The maximum number of entries to return in the list.  The
688     * actual number returned may be smaller, depending on how many tasks the
689     * user has started.
690     *
691     * @param flags Optional flags
692     * @param receiver Optional receiver for delayed thumbnails
693     *
694     * @return Returns a list of RunningTaskInfo records describing each of
695     * the running tasks.
696     *
697     * Some thumbnails may not be available at the time of this call. The optional
698     * receiver may be used to receive those thumbnails.
699     *
700     * @throws SecurityException Throws SecurityException if the caller does
701     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
702     *
703     * @hide
704     */
705    public List<RunningTaskInfo> getRunningTasks(int maxNum, int flags, IThumbnailReceiver receiver)
706            throws SecurityException {
707        try {
708            return ActivityManagerNative.getDefault().getTasks(maxNum, flags, receiver);
709        } catch (RemoteException e) {
710            // System dead, we will be dead too soon!
711            return null;
712        }
713    }
714
715    /**
716     * Return a list of the tasks that are currently running, with
717     * the most recent being first and older ones after in order.  Note that
718     * "running" does not mean any of the task's code is currently loaded or
719     * activity -- the task may have been frozen by the system, so that it
720     * can be restarted in its previous state when next brought to the
721     * foreground.
722     *
723     * <p><b>Note: this method is only intended for debugging and presenting
724     * task management user interfaces</b>.  This should never be used for
725     * core logic in an application, such as deciding between different
726     * behaviors based on the information found here.  Such uses are
727     * <em>not</em> supported, and will likely break in the future.  For
728     * example, if multiple applications can be actively running at the
729     * same time, assumptions made about the meaning of the data here for
730     * purposes of control flow will be incorrect.</p>
731     *
732     * @param maxNum The maximum number of entries to return in the list.  The
733     * actual number returned may be smaller, depending on how many tasks the
734     * user has started.
735     *
736     * @return Returns a list of RunningTaskInfo records describing each of
737     * the running tasks.
738     *
739     * @throws SecurityException Throws SecurityException if the caller does
740     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
741     */
742    public List<RunningTaskInfo> getRunningTasks(int maxNum)
743            throws SecurityException {
744        return getRunningTasks(maxNum, 0, null);
745    }
746
747    /**
748     * Remove some end of a task's activity stack that is not part of
749     * the main application.  The selected activities will be finished, so
750     * they are no longer part of the main task.
751     *
752     * @param taskId The identifier of the task.
753     * @param subTaskIndex The number of the sub-task; this corresponds
754     * to the index of the thumbnail returned by {@link #getTaskThumbnails(int)}.
755     * @return Returns true if the sub-task was found and was removed.
756     *
757     * @hide
758     */
759    public boolean removeSubTask(int taskId, int subTaskIndex)
760            throws SecurityException {
761        try {
762            return ActivityManagerNative.getDefault().removeSubTask(taskId, subTaskIndex);
763        } catch (RemoteException e) {
764            // System dead, we will be dead too soon!
765            return false;
766        }
767    }
768
769    /**
770     * If set, the process of the root activity of the task will be killed
771     * as part of removing the task.
772     * @hide
773     */
774    public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
775
776    /**
777     * Completely remove the given task.
778     *
779     * @param taskId Identifier of the task to be removed.
780     * @param flags Additional operational flags.  May be 0 or
781     * {@link #REMOVE_TASK_KILL_PROCESS}.
782     * @return Returns true if the given task was found and removed.
783     *
784     * @hide
785     */
786    public boolean removeTask(int taskId, int flags)
787            throws SecurityException {
788        try {
789            return ActivityManagerNative.getDefault().removeTask(taskId, flags);
790        } catch (RemoteException e) {
791            // System dead, we will be dead too soon!
792            return false;
793        }
794    }
795
796    /** @hide */
797    public static class TaskThumbnails implements Parcelable {
798        public Bitmap mainThumbnail;
799
800        public int numSubThumbbails;
801
802        /** @hide */
803        public IThumbnailRetriever retriever;
804
805        public TaskThumbnails() {
806        }
807
808        public Bitmap getSubThumbnail(int index) {
809            try {
810                return retriever.getThumbnail(index);
811            } catch (RemoteException e) {
812                return null;
813            }
814        }
815
816        public int describeContents() {
817            return 0;
818        }
819
820        public void writeToParcel(Parcel dest, int flags) {
821            if (mainThumbnail != null) {
822                dest.writeInt(1);
823                mainThumbnail.writeToParcel(dest, 0);
824            } else {
825                dest.writeInt(0);
826            }
827            dest.writeInt(numSubThumbbails);
828            dest.writeStrongInterface(retriever);
829        }
830
831        public void readFromParcel(Parcel source) {
832            if (source.readInt() != 0) {
833                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
834            } else {
835                mainThumbnail = null;
836            }
837            numSubThumbbails = source.readInt();
838            retriever = IThumbnailRetriever.Stub.asInterface(source.readStrongBinder());
839        }
840
841        public static final Creator<TaskThumbnails> CREATOR = new Creator<TaskThumbnails>() {
842            public TaskThumbnails createFromParcel(Parcel source) {
843                return new TaskThumbnails(source);
844            }
845            public TaskThumbnails[] newArray(int size) {
846                return new TaskThumbnails[size];
847            }
848        };
849
850        private TaskThumbnails(Parcel source) {
851            readFromParcel(source);
852        }
853    }
854
855    /** @hide */
856    public TaskThumbnails getTaskThumbnails(int id) throws SecurityException {
857        try {
858            return ActivityManagerNative.getDefault().getTaskThumbnails(id);
859        } catch (RemoteException e) {
860            // System dead, we will be dead too soon!
861            return null;
862        }
863    }
864
865    /**
866     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
867     * activity along with the task, so it is positioned immediately behind
868     * the task.
869     */
870    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
871
872    /**
873     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
874     * user-instigated action, so the current activity will not receive a
875     * hint that the user is leaving.
876     */
877    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
878
879    /**
880     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
881     * with a null options argument.
882     *
883     * @param taskId The identifier of the task to be moved, as found in
884     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
885     * @param flags Additional operational flags, 0 or more of
886     * {@link #MOVE_TASK_WITH_HOME}.
887     */
888    public void moveTaskToFront(int taskId, int flags) {
889        moveTaskToFront(taskId, flags, null);
890    }
891
892    /**
893     * Ask that the task associated with a given task ID be moved to the
894     * front of the stack, so it is now visible to the user.  Requires that
895     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
896     * or a SecurityException will be thrown.
897     *
898     * @param taskId The identifier of the task to be moved, as found in
899     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
900     * @param flags Additional operational flags, 0 or more of
901     * {@link #MOVE_TASK_WITH_HOME}.
902     * @param options Additional options for the operation, either null or
903     * as per {@link Context#startActivity(Intent, android.os.Bundle)
904     * Context.startActivity(Intent, Bundle)}.
905     */
906    public void moveTaskToFront(int taskId, int flags, Bundle options) {
907        try {
908            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
909        } catch (RemoteException e) {
910            // System dead, we will be dead too soon!
911        }
912    }
913
914    /**
915     * Information you can retrieve about a particular Service that is
916     * currently running in the system.
917     */
918    public static class RunningServiceInfo implements Parcelable {
919        /**
920         * The service component.
921         */
922        public ComponentName service;
923
924        /**
925         * If non-zero, this is the process the service is running in.
926         */
927        public int pid;
928
929        /**
930         * The UID that owns this service.
931         */
932        public int uid;
933
934        /**
935         * The name of the process this service runs in.
936         */
937        public String process;
938
939        /**
940         * Set to true if the service has asked to run as a foreground process.
941         */
942        public boolean foreground;
943
944        /**
945         * The time when the service was first made active, either by someone
946         * starting or binding to it.  This
947         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
948         */
949        public long activeSince;
950
951        /**
952         * Set to true if this service has been explicitly started.
953         */
954        public boolean started;
955
956        /**
957         * Number of clients connected to the service.
958         */
959        public int clientCount;
960
961        /**
962         * Number of times the service's process has crashed while the service
963         * is running.
964         */
965        public int crashCount;
966
967        /**
968         * The time when there was last activity in the service (either
969         * explicit requests to start it or clients binding to it).  This
970         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
971         */
972        public long lastActivityTime;
973
974        /**
975         * If non-zero, this service is not currently running, but scheduled to
976         * restart at the given time.
977         */
978        public long restarting;
979
980        /**
981         * Bit for {@link #flags}: set if this service has been
982         * explicitly started.
983         */
984        public static final int FLAG_STARTED = 1<<0;
985
986        /**
987         * Bit for {@link #flags}: set if the service has asked to
988         * run as a foreground process.
989         */
990        public static final int FLAG_FOREGROUND = 1<<1;
991
992        /**
993         * Bit for {@link #flags): set if the service is running in a
994         * core system process.
995         */
996        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
997
998        /**
999         * Bit for {@link #flags): set if the service is running in a
1000         * persistent process.
1001         */
1002        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1003
1004        /**
1005         * Running flags.
1006         */
1007        public int flags;
1008
1009        /**
1010         * For special services that are bound to by system code, this is
1011         * the package that holds the binding.
1012         */
1013        public String clientPackage;
1014
1015        /**
1016         * For special services that are bound to by system code, this is
1017         * a string resource providing a user-visible label for who the
1018         * client is.
1019         */
1020        public int clientLabel;
1021
1022        public RunningServiceInfo() {
1023        }
1024
1025        public int describeContents() {
1026            return 0;
1027        }
1028
1029        public void writeToParcel(Parcel dest, int flags) {
1030            ComponentName.writeToParcel(service, dest);
1031            dest.writeInt(pid);
1032            dest.writeInt(uid);
1033            dest.writeString(process);
1034            dest.writeInt(foreground ? 1 : 0);
1035            dest.writeLong(activeSince);
1036            dest.writeInt(started ? 1 : 0);
1037            dest.writeInt(clientCount);
1038            dest.writeInt(crashCount);
1039            dest.writeLong(lastActivityTime);
1040            dest.writeLong(restarting);
1041            dest.writeInt(this.flags);
1042            dest.writeString(clientPackage);
1043            dest.writeInt(clientLabel);
1044        }
1045
1046        public void readFromParcel(Parcel source) {
1047            service = ComponentName.readFromParcel(source);
1048            pid = source.readInt();
1049            uid = source.readInt();
1050            process = source.readString();
1051            foreground = source.readInt() != 0;
1052            activeSince = source.readLong();
1053            started = source.readInt() != 0;
1054            clientCount = source.readInt();
1055            crashCount = source.readInt();
1056            lastActivityTime = source.readLong();
1057            restarting = source.readLong();
1058            flags = source.readInt();
1059            clientPackage = source.readString();
1060            clientLabel = source.readInt();
1061        }
1062
1063        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1064            public RunningServiceInfo createFromParcel(Parcel source) {
1065                return new RunningServiceInfo(source);
1066            }
1067            public RunningServiceInfo[] newArray(int size) {
1068                return new RunningServiceInfo[size];
1069            }
1070        };
1071
1072        private RunningServiceInfo(Parcel source) {
1073            readFromParcel(source);
1074        }
1075    }
1076
1077    /**
1078     * Return a list of the services that are currently running.
1079     *
1080     * <p><b>Note: this method is only intended for debugging or implementing
1081     * service management type user interfaces.</b></p>
1082     *
1083     * @param maxNum The maximum number of entries to return in the list.  The
1084     * actual number returned may be smaller, depending on how many services
1085     * are running.
1086     *
1087     * @return Returns a list of RunningServiceInfo records describing each of
1088     * the running tasks.
1089     */
1090    public List<RunningServiceInfo> getRunningServices(int maxNum)
1091            throws SecurityException {
1092        try {
1093            return ActivityManagerNative.getDefault()
1094                    .getServices(maxNum, 0);
1095        } catch (RemoteException e) {
1096            // System dead, we will be dead too soon!
1097            return null;
1098        }
1099    }
1100
1101    /**
1102     * Returns a PendingIntent you can start to show a control panel for the
1103     * given running service.  If the service does not have a control panel,
1104     * null is returned.
1105     */
1106    public PendingIntent getRunningServiceControlPanel(ComponentName service)
1107            throws SecurityException {
1108        try {
1109            return ActivityManagerNative.getDefault()
1110                    .getRunningServiceControlPanel(service);
1111        } catch (RemoteException e) {
1112            // System dead, we will be dead too soon!
1113            return null;
1114        }
1115    }
1116
1117    /**
1118     * Information you can retrieve about the available memory through
1119     * {@link ActivityManager#getMemoryInfo}.
1120     */
1121    public static class MemoryInfo implements Parcelable {
1122        /**
1123         * The available memory on the system.  This number should not
1124         * be considered absolute: due to the nature of the kernel, a significant
1125         * portion of this memory is actually in use and needed for the overall
1126         * system to run well.
1127         */
1128        public long availMem;
1129
1130        /**
1131         * The total memory accessible by the kernel.  This is basically the
1132         * RAM size of the device, not including below-kernel fixed allocations
1133         * like DMA buffers, RAM for the baseband CPU, etc.
1134         */
1135        public long totalMem;
1136
1137        /**
1138         * The threshold of {@link #availMem} at which we consider memory to be
1139         * low and start killing background services and other non-extraneous
1140         * processes.
1141         */
1142        public long threshold;
1143
1144        /**
1145         * Set to true if the system considers itself to currently be in a low
1146         * memory situation.
1147         */
1148        public boolean lowMemory;
1149
1150        /** @hide */
1151        public long hiddenAppThreshold;
1152        /** @hide */
1153        public long secondaryServerThreshold;
1154        /** @hide */
1155        public long visibleAppThreshold;
1156        /** @hide */
1157        public long foregroundAppThreshold;
1158
1159        public MemoryInfo() {
1160        }
1161
1162        public int describeContents() {
1163            return 0;
1164        }
1165
1166        public void writeToParcel(Parcel dest, int flags) {
1167            dest.writeLong(availMem);
1168            dest.writeLong(totalMem);
1169            dest.writeLong(threshold);
1170            dest.writeInt(lowMemory ? 1 : 0);
1171            dest.writeLong(hiddenAppThreshold);
1172            dest.writeLong(secondaryServerThreshold);
1173            dest.writeLong(visibleAppThreshold);
1174            dest.writeLong(foregroundAppThreshold);
1175        }
1176
1177        public void readFromParcel(Parcel source) {
1178            availMem = source.readLong();
1179            totalMem = source.readLong();
1180            threshold = source.readLong();
1181            lowMemory = source.readInt() != 0;
1182            hiddenAppThreshold = source.readLong();
1183            secondaryServerThreshold = source.readLong();
1184            visibleAppThreshold = source.readLong();
1185            foregroundAppThreshold = source.readLong();
1186        }
1187
1188        public static final Creator<MemoryInfo> CREATOR
1189                = new Creator<MemoryInfo>() {
1190            public MemoryInfo createFromParcel(Parcel source) {
1191                return new MemoryInfo(source);
1192            }
1193            public MemoryInfo[] newArray(int size) {
1194                return new MemoryInfo[size];
1195            }
1196        };
1197
1198        private MemoryInfo(Parcel source) {
1199            readFromParcel(source);
1200        }
1201    }
1202
1203    /**
1204     * Return general information about the memory state of the system.  This
1205     * can be used to help decide how to manage your own memory, though note
1206     * that polling is not recommended and
1207     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1208     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1209     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1210     * level of your process as needed, which gives a better hint for how to
1211     * manage its memory.
1212     */
1213    public void getMemoryInfo(MemoryInfo outInfo) {
1214        try {
1215            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1216        } catch (RemoteException e) {
1217        }
1218    }
1219
1220    /**
1221     * @hide
1222     */
1223    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1224        try {
1225            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1226                    observer, Binder.getOrigCallingUser());
1227        } catch (RemoteException e) {
1228            return false;
1229        }
1230    }
1231
1232    /**
1233     * Information you can retrieve about any processes that are in an error condition.
1234     */
1235    public static class ProcessErrorStateInfo implements Parcelable {
1236        /**
1237         * Condition codes
1238         */
1239        public static final int NO_ERROR = 0;
1240        public static final int CRASHED = 1;
1241        public static final int NOT_RESPONDING = 2;
1242
1243        /**
1244         * The condition that the process is in.
1245         */
1246        public int condition;
1247
1248        /**
1249         * The process name in which the crash or error occurred.
1250         */
1251        public String processName;
1252
1253        /**
1254         * The pid of this process; 0 if none
1255         */
1256        public int pid;
1257
1258        /**
1259         * The kernel user-ID that has been assigned to this process;
1260         * currently this is not a unique ID (multiple applications can have
1261         * the same uid).
1262         */
1263        public int uid;
1264
1265        /**
1266         * The activity name associated with the error, if known.  May be null.
1267         */
1268        public String tag;
1269
1270        /**
1271         * A short message describing the error condition.
1272         */
1273        public String shortMsg;
1274
1275        /**
1276         * A long message describing the error condition.
1277         */
1278        public String longMsg;
1279
1280        /**
1281         * The stack trace where the error originated.  May be null.
1282         */
1283        public String stackTrace;
1284
1285        /**
1286         * to be deprecated: This value will always be null.
1287         */
1288        public byte[] crashData = null;
1289
1290        public ProcessErrorStateInfo() {
1291        }
1292
1293        public int describeContents() {
1294            return 0;
1295        }
1296
1297        public void writeToParcel(Parcel dest, int flags) {
1298            dest.writeInt(condition);
1299            dest.writeString(processName);
1300            dest.writeInt(pid);
1301            dest.writeInt(uid);
1302            dest.writeString(tag);
1303            dest.writeString(shortMsg);
1304            dest.writeString(longMsg);
1305            dest.writeString(stackTrace);
1306        }
1307
1308        public void readFromParcel(Parcel source) {
1309            condition = source.readInt();
1310            processName = source.readString();
1311            pid = source.readInt();
1312            uid = source.readInt();
1313            tag = source.readString();
1314            shortMsg = source.readString();
1315            longMsg = source.readString();
1316            stackTrace = source.readString();
1317        }
1318
1319        public static final Creator<ProcessErrorStateInfo> CREATOR =
1320                new Creator<ProcessErrorStateInfo>() {
1321            public ProcessErrorStateInfo createFromParcel(Parcel source) {
1322                return new ProcessErrorStateInfo(source);
1323            }
1324            public ProcessErrorStateInfo[] newArray(int size) {
1325                return new ProcessErrorStateInfo[size];
1326            }
1327        };
1328
1329        private ProcessErrorStateInfo(Parcel source) {
1330            readFromParcel(source);
1331        }
1332    }
1333
1334    /**
1335     * Returns a list of any processes that are currently in an error condition.  The result
1336     * will be null if all processes are running properly at this time.
1337     *
1338     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1339     * current error conditions (it will not return an empty list).  This list ordering is not
1340     * specified.
1341     */
1342    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1343        try {
1344            return ActivityManagerNative.getDefault().getProcessesInErrorState();
1345        } catch (RemoteException e) {
1346            return null;
1347        }
1348    }
1349
1350    /**
1351     * Information you can retrieve about a running process.
1352     */
1353    public static class RunningAppProcessInfo implements Parcelable {
1354        /**
1355         * The name of the process that this object is associated with
1356         */
1357        public String processName;
1358
1359        /**
1360         * The pid of this process; 0 if none
1361         */
1362        public int pid;
1363
1364        /**
1365         * The user id of this process.
1366         */
1367        public int uid;
1368
1369        /**
1370         * All packages that have been loaded into the process.
1371         */
1372        public String pkgList[];
1373
1374        /**
1375         * Constant for {@link #flags}: this is an app that is unable to
1376         * correctly save its state when going to the background,
1377         * so it can not be killed while in the background.
1378         * @hide
1379         */
1380        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1381
1382        /**
1383         * Constant for {@link #flags}: this process is associated with a
1384         * persistent system app.
1385         * @hide
1386         */
1387        public static final int FLAG_PERSISTENT = 1<<1;
1388
1389        /**
1390         * Constant for {@link #flags}: this process is associated with a
1391         * persistent system app.
1392         * @hide
1393         */
1394        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1395
1396        /**
1397         * Flags of information.  May be any of
1398         * {@link #FLAG_CANT_SAVE_STATE}.
1399         * @hide
1400         */
1401        public int flags;
1402
1403        /**
1404         * Last memory trim level reported to the process: corresponds to
1405         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1406         * ComponentCallbacks2.onTrimMemory(int)}.
1407         */
1408        public int lastTrimLevel;
1409
1410        /**
1411         * Constant for {@link #importance}: this is a persistent process.
1412         * Only used when reporting to process observers.
1413         * @hide
1414         */
1415        public static final int IMPORTANCE_PERSISTENT = 50;
1416
1417        /**
1418         * Constant for {@link #importance}: this process is running the
1419         * foreground UI.
1420         */
1421        public static final int IMPORTANCE_FOREGROUND = 100;
1422
1423        /**
1424         * Constant for {@link #importance}: this process is running something
1425         * that is actively visible to the user, though not in the immediate
1426         * foreground.
1427         */
1428        public static final int IMPORTANCE_VISIBLE = 200;
1429
1430        /**
1431         * Constant for {@link #importance}: this process is running something
1432         * that is considered to be actively perceptible to the user.  An
1433         * example would be an application performing background music playback.
1434         */
1435        public static final int IMPORTANCE_PERCEPTIBLE = 130;
1436
1437        /**
1438         * Constant for {@link #importance}: this process is running an
1439         * application that can not save its state, and thus can't be killed
1440         * while in the background.
1441         * @hide
1442         */
1443        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1444
1445        /**
1446         * Constant for {@link #importance}: this process is contains services
1447         * that should remain running.
1448         */
1449        public static final int IMPORTANCE_SERVICE = 300;
1450
1451        /**
1452         * Constant for {@link #importance}: this process process contains
1453         * background code that is expendable.
1454         */
1455        public static final int IMPORTANCE_BACKGROUND = 400;
1456
1457        /**
1458         * Constant for {@link #importance}: this process is empty of any
1459         * actively running code.
1460         */
1461        public static final int IMPORTANCE_EMPTY = 500;
1462
1463        /**
1464         * The relative importance level that the system places on this
1465         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
1466         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1467         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
1468         * constants are numbered so that "more important" values are always
1469         * smaller than "less important" values.
1470         */
1471        public int importance;
1472
1473        /**
1474         * An additional ordering within a particular {@link #importance}
1475         * category, providing finer-grained information about the relative
1476         * utility of processes within a category.  This number means nothing
1477         * except that a smaller values are more recently used (and thus
1478         * more important).  Currently an LRU value is only maintained for
1479         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1480         * be maintained in the future.
1481         */
1482        public int lru;
1483
1484        /**
1485         * Constant for {@link #importanceReasonCode}: nothing special has
1486         * been specified for the reason for this level.
1487         */
1488        public static final int REASON_UNKNOWN = 0;
1489
1490        /**
1491         * Constant for {@link #importanceReasonCode}: one of the application's
1492         * content providers is being used by another process.  The pid of
1493         * the client process is in {@link #importanceReasonPid} and the
1494         * target provider in this process is in
1495         * {@link #importanceReasonComponent}.
1496         */
1497        public static final int REASON_PROVIDER_IN_USE = 1;
1498
1499        /**
1500         * Constant for {@link #importanceReasonCode}: one of the application's
1501         * content providers is being used by another process.  The pid of
1502         * the client process is in {@link #importanceReasonPid} and the
1503         * target provider in this process is in
1504         * {@link #importanceReasonComponent}.
1505         */
1506        public static final int REASON_SERVICE_IN_USE = 2;
1507
1508        /**
1509         * The reason for {@link #importance}, if any.
1510         */
1511        public int importanceReasonCode;
1512
1513        /**
1514         * For the specified values of {@link #importanceReasonCode}, this
1515         * is the process ID of the other process that is a client of this
1516         * process.  This will be 0 if no other process is using this one.
1517         */
1518        public int importanceReasonPid;
1519
1520        /**
1521         * For the specified values of {@link #importanceReasonCode}, this
1522         * is the name of the component that is being used in this process.
1523         */
1524        public ComponentName importanceReasonComponent;
1525
1526        /**
1527         * When {@link importanceReasonPid} is non-0, this is the importance
1528         * of the other pid. @hide
1529         */
1530        public int importanceReasonImportance;
1531
1532        public RunningAppProcessInfo() {
1533            importance = IMPORTANCE_FOREGROUND;
1534            importanceReasonCode = REASON_UNKNOWN;
1535        }
1536
1537        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1538            processName = pProcessName;
1539            pid = pPid;
1540            pkgList = pArr;
1541        }
1542
1543        public int describeContents() {
1544            return 0;
1545        }
1546
1547        public void writeToParcel(Parcel dest, int flags) {
1548            dest.writeString(processName);
1549            dest.writeInt(pid);
1550            dest.writeInt(uid);
1551            dest.writeStringArray(pkgList);
1552            dest.writeInt(this.flags);
1553            dest.writeInt(lastTrimLevel);
1554            dest.writeInt(importance);
1555            dest.writeInt(lru);
1556            dest.writeInt(importanceReasonCode);
1557            dest.writeInt(importanceReasonPid);
1558            ComponentName.writeToParcel(importanceReasonComponent, dest);
1559            dest.writeInt(importanceReasonImportance);
1560        }
1561
1562        public void readFromParcel(Parcel source) {
1563            processName = source.readString();
1564            pid = source.readInt();
1565            uid = source.readInt();
1566            pkgList = source.readStringArray();
1567            flags = source.readInt();
1568            lastTrimLevel = source.readInt();
1569            importance = source.readInt();
1570            lru = source.readInt();
1571            importanceReasonCode = source.readInt();
1572            importanceReasonPid = source.readInt();
1573            importanceReasonComponent = ComponentName.readFromParcel(source);
1574            importanceReasonImportance = source.readInt();
1575        }
1576
1577        public static final Creator<RunningAppProcessInfo> CREATOR =
1578            new Creator<RunningAppProcessInfo>() {
1579            public RunningAppProcessInfo createFromParcel(Parcel source) {
1580                return new RunningAppProcessInfo(source);
1581            }
1582            public RunningAppProcessInfo[] newArray(int size) {
1583                return new RunningAppProcessInfo[size];
1584            }
1585        };
1586
1587        private RunningAppProcessInfo(Parcel source) {
1588            readFromParcel(source);
1589        }
1590    }
1591
1592    /**
1593     * Returns a list of application processes installed on external media
1594     * that are running on the device.
1595     *
1596     * <p><b>Note: this method is only intended for debugging or building
1597     * a user-facing process management UI.</b></p>
1598     *
1599     * @return Returns a list of ApplicationInfo records, or null if none
1600     * This list ordering is not specified.
1601     * @hide
1602     */
1603    public List<ApplicationInfo> getRunningExternalApplications() {
1604        try {
1605            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1606        } catch (RemoteException e) {
1607            return null;
1608        }
1609    }
1610
1611    /**
1612     * Returns a list of application processes that are running on the device.
1613     *
1614     * <p><b>Note: this method is only intended for debugging or building
1615     * a user-facing process management UI.</b></p>
1616     *
1617     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
1618     * running processes (it will not return an empty list).  This list ordering is not
1619     * specified.
1620     */
1621    public List<RunningAppProcessInfo> getRunningAppProcesses() {
1622        try {
1623            return ActivityManagerNative.getDefault().getRunningAppProcesses();
1624        } catch (RemoteException e) {
1625            return null;
1626        }
1627    }
1628
1629    /**
1630     * Return global memory state information for the calling process.  This
1631     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
1632     * only fields that will be filled in are
1633     * {@link RunningAppProcessInfo#pid},
1634     * {@link RunningAppProcessInfo#uid},
1635     * {@link RunningAppProcessInfo#lastTrimLevel},
1636     * {@link RunningAppProcessInfo#importance},
1637     * {@link RunningAppProcessInfo#lru}, and
1638     * {@link RunningAppProcessInfo#importanceReasonCode}.
1639     */
1640    static public void getMyMemoryState(RunningAppProcessInfo outState) {
1641        try {
1642            ActivityManagerNative.getDefault().getMyMemoryState(outState);
1643        } catch (RemoteException e) {
1644        }
1645    }
1646
1647    /**
1648     * Return information about the memory usage of one or more processes.
1649     *
1650     * <p><b>Note: this method is only intended for debugging or building
1651     * a user-facing process management UI.</b></p>
1652     *
1653     * @param pids The pids of the processes whose memory usage is to be
1654     * retrieved.
1655     * @return Returns an array of memory information, one for each
1656     * requested pid.
1657     */
1658    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
1659        try {
1660            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
1661        } catch (RemoteException e) {
1662            return null;
1663        }
1664    }
1665
1666    /**
1667     * @deprecated This is now just a wrapper for
1668     * {@link #killBackgroundProcesses(String)}; the previous behavior here
1669     * is no longer available to applications because it allows them to
1670     * break other applications by removing their alarms, stopping their
1671     * services, etc.
1672     */
1673    @Deprecated
1674    public void restartPackage(String packageName) {
1675        killBackgroundProcesses(packageName);
1676    }
1677
1678    /**
1679     * Have the system immediately kill all background processes associated
1680     * with the given package.  This is the same as the kernel killing those
1681     * processes to reclaim memory; the system will take care of restarting
1682     * these processes in the future as needed.
1683     *
1684     * <p>You must hold the permission
1685     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
1686     * call this method.
1687     *
1688     * @param packageName The name of the package whose processes are to
1689     * be killed.
1690     */
1691    public void killBackgroundProcesses(String packageName) {
1692        try {
1693            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName);
1694        } catch (RemoteException e) {
1695        }
1696    }
1697
1698    /**
1699     * Have the system perform a force stop of everything associated with
1700     * the given application package.  All processes that share its uid
1701     * will be killed, all services it has running stopped, all activities
1702     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
1703     * broadcast will be sent, so that any of its registered alarms can
1704     * be stopped, notifications removed, etc.
1705     *
1706     * <p>You must hold the permission
1707     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
1708     * call this method.
1709     *
1710     * @param packageName The name of the package to be stopped.
1711     *
1712     * @hide This is not available to third party applications due to
1713     * it allowing them to break other applications by stopping their
1714     * services, removing their alarms, etc.
1715     */
1716    public void forceStopPackage(String packageName) {
1717        try {
1718            ActivityManagerNative.getDefault().forceStopPackage(packageName);
1719        } catch (RemoteException e) {
1720        }
1721    }
1722
1723    /**
1724     * Get the device configuration attributes.
1725     */
1726    public ConfigurationInfo getDeviceConfigurationInfo() {
1727        try {
1728            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
1729        } catch (RemoteException e) {
1730        }
1731        return null;
1732    }
1733
1734    /**
1735     * Get the preferred density of icons for the launcher. This is used when
1736     * custom drawables are created (e.g., for shortcuts).
1737     *
1738     * @return density in terms of DPI
1739     */
1740    public int getLauncherLargeIconDensity() {
1741        final Resources res = mContext.getResources();
1742        final int density = res.getDisplayMetrics().densityDpi;
1743        final int sw = res.getConfiguration().smallestScreenWidthDp;
1744
1745        if (sw < 600) {
1746            // Smaller than approx 7" tablets, use the regular icon size.
1747            return density;
1748        }
1749
1750        switch (density) {
1751            case DisplayMetrics.DENSITY_LOW:
1752                return DisplayMetrics.DENSITY_MEDIUM;
1753            case DisplayMetrics.DENSITY_MEDIUM:
1754                return DisplayMetrics.DENSITY_HIGH;
1755            case DisplayMetrics.DENSITY_TV:
1756                return DisplayMetrics.DENSITY_XHIGH;
1757            case DisplayMetrics.DENSITY_HIGH:
1758                return DisplayMetrics.DENSITY_XHIGH;
1759            case DisplayMetrics.DENSITY_XHIGH:
1760                return DisplayMetrics.DENSITY_XXHIGH;
1761            case DisplayMetrics.DENSITY_XXHIGH:
1762                return DisplayMetrics.DENSITY_XHIGH * 2;
1763            default:
1764                // The density is some abnormal value.  Return some other
1765                // abnormal value that is a reasonable scaling of it.
1766                return (int)((density*1.5f)+.5f);
1767        }
1768    }
1769
1770    /**
1771     * Get the preferred launcher icon size. This is used when custom drawables
1772     * are created (e.g., for shortcuts).
1773     *
1774     * @return dimensions of square icons in terms of pixels
1775     */
1776    public int getLauncherLargeIconSize() {
1777        final Resources res = mContext.getResources();
1778        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
1779        final int sw = res.getConfiguration().smallestScreenWidthDp;
1780
1781        if (sw < 600) {
1782            // Smaller than approx 7" tablets, use the regular icon size.
1783            return size;
1784        }
1785
1786        final int density = res.getDisplayMetrics().densityDpi;
1787
1788        switch (density) {
1789            case DisplayMetrics.DENSITY_LOW:
1790                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
1791            case DisplayMetrics.DENSITY_MEDIUM:
1792                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
1793            case DisplayMetrics.DENSITY_TV:
1794                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1795            case DisplayMetrics.DENSITY_HIGH:
1796                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1797            case DisplayMetrics.DENSITY_XHIGH:
1798                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
1799            case DisplayMetrics.DENSITY_XXHIGH:
1800                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
1801            default:
1802                // The density is some abnormal value.  Return some other
1803                // abnormal value that is a reasonable scaling of it.
1804                return (int)((size*1.5f) + .5f);
1805        }
1806    }
1807
1808    /**
1809     * Returns "true" if the user interface is currently being messed with
1810     * by a monkey.
1811     */
1812    public static boolean isUserAMonkey() {
1813        try {
1814            return ActivityManagerNative.getDefault().isUserAMonkey();
1815        } catch (RemoteException e) {
1816        }
1817        return false;
1818    }
1819
1820    /**
1821     * Returns "true" if device is running in a test harness.
1822     */
1823    public static boolean isRunningInTestHarness() {
1824        return SystemProperties.getBoolean("ro.test_harness", false);
1825    }
1826
1827    /**
1828     * Returns the launch count of each installed package.
1829     *
1830     * @hide
1831     */
1832    public Map<String, Integer> getAllPackageLaunchCounts() {
1833        try {
1834            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
1835                    ServiceManager.getService("usagestats"));
1836            if (usageStatsService == null) {
1837                return new HashMap<String, Integer>();
1838            }
1839
1840            PkgUsageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats();
1841            if (allPkgUsageStats == null) {
1842                return new HashMap<String, Integer>();
1843            }
1844
1845            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
1846            for (PkgUsageStats pkgUsageStats : allPkgUsageStats) {
1847                launchCounts.put(pkgUsageStats.packageName, pkgUsageStats.launchCount);
1848            }
1849
1850            return launchCounts;
1851        } catch (RemoteException e) {
1852            Log.w(TAG, "Could not query launch counts", e);
1853            return new HashMap<String, Integer>();
1854        }
1855    }
1856
1857    /** @hide */
1858    public static int checkComponentPermission(String permission, int uid,
1859            int owningUid, boolean exported) {
1860        // Root, system server get to do everything.
1861        if (uid == 0 || uid == Process.SYSTEM_UID) {
1862            return PackageManager.PERMISSION_GRANTED;
1863        }
1864        // Isolated processes don't get any permissions.
1865        if (UserHandle.isIsolated(uid)) {
1866            return PackageManager.PERMISSION_DENIED;
1867        }
1868        // If there is a uid that owns whatever is being accessed, it has
1869        // blanket access to it regardless of the permissions it requires.
1870        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
1871            return PackageManager.PERMISSION_GRANTED;
1872        }
1873        // If the target is not exported, then nobody else can get to it.
1874        if (!exported) {
1875            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
1876            return PackageManager.PERMISSION_DENIED;
1877        }
1878        if (permission == null) {
1879            return PackageManager.PERMISSION_GRANTED;
1880        }
1881        try {
1882            return AppGlobals.getPackageManager()
1883                    .checkUidPermission(permission, uid);
1884        } catch (RemoteException e) {
1885            // Should never happen, but if it does... deny!
1886            Slog.e(TAG, "PackageManager is dead?!?", e);
1887        }
1888        return PackageManager.PERMISSION_DENIED;
1889    }
1890
1891    /** @hide */
1892    public static int checkUidPermission(String permission, int uid) {
1893        try {
1894            return AppGlobals.getPackageManager()
1895                    .checkUidPermission(permission, uid);
1896        } catch (RemoteException e) {
1897            // Should never happen, but if it does... deny!
1898            Slog.e(TAG, "PackageManager is dead?!?", e);
1899        }
1900        return PackageManager.PERMISSION_DENIED;
1901    }
1902
1903    /**
1904     * Returns the usage statistics of each installed package.
1905     *
1906     * @hide
1907     */
1908    public PkgUsageStats[] getAllPackageUsageStats() {
1909        try {
1910            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
1911                    ServiceManager.getService("usagestats"));
1912            if (usageStatsService != null) {
1913                return usageStatsService.getAllPkgUsageStats();
1914            }
1915        } catch (RemoteException e) {
1916            Log.w(TAG, "Could not query usage stats", e);
1917        }
1918        return new PkgUsageStats[0];
1919    }
1920
1921    /**
1922     * @param userid the user's id. Zero indicates the default user
1923     * @hide
1924     */
1925    public boolean switchUser(int userid) {
1926        try {
1927            return ActivityManagerNative.getDefault().switchUser(userid);
1928        } catch (RemoteException e) {
1929            return false;
1930        }
1931    }
1932}
1933