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