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