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