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