2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.os.BatteryStats;
20 import android.os.IBinder;
21 import android.os.ParcelFileDescriptor;
22 import com.android.internal.app.ProcessStats;
23 import com.android.internal.os.TransferPipe;
24 import com.android.internal.util.FastPrintWriter;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.pm.ApplicationInfo;
30 import android.content.pm.ConfigurationInfo;
31 import android.content.pm.IPackageDataObserver;
32 import android.content.pm.PackageManager;
33 import android.content.pm.UserInfo;
34 import android.content.res.Resources;
35 import android.graphics.Bitmap;
36 import android.graphics.Color;
37 import android.graphics.Rect;
38 import android.os.Bundle;
39 import android.os.Debug;
40 import android.os.Handler;
41 import android.os.Parcel;
42 import android.os.Parcelable;
43 import android.os.Process;
44 import android.os.RemoteException;
45 import android.os.ServiceManager;
46 import android.os.SystemProperties;
47 import android.os.UserHandle;
48 import android.text.TextUtils;
49 import android.util.DisplayMetrics;
50 import android.util.Log;
51 import android.util.Slog;
53 import java.io.FileDescriptor;
54 import java.io.FileOutputStream;
55 import java.io.PrintWriter;
56 import java.util.ArrayList;
57 import java.util.HashMap;
58 import java.util.List;
62 * Interact with the overall activities running in the system.
64 public class ActivityManager {
65 private static String TAG = "ActivityManager";
66 private static boolean localLOGV = false;
68 private final Context mContext;
69 private final Handler mHandler;
72 * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
73 * <meta-data>}</a> name for a 'home' Activity that declares a package that is to be
74 * uninstalled in lieu of the declaring one. The package named here must be
75 * signed with the same certificate as the one declaring the {@code <meta-data>}.
77 public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
80 * Result for IActivityManager.startActivity: trying to start an activity under voice
81 * control when that activity does not support the VOICE category.
84 public static final int START_NOT_VOICE_COMPATIBLE = -7;
87 * Result for IActivityManager.startActivity: an error where the
88 * start had to be canceled.
91 public static final int START_CANCELED = -6;
94 * Result for IActivityManager.startActivity: an error where the
95 * thing being started is not an activity.
98 public static final int START_NOT_ACTIVITY = -5;
101 * Result for IActivityManager.startActivity: an error where the
102 * caller does not have permission to start the activity.
105 public static final int START_PERMISSION_DENIED = -4;
108 * Result for IActivityManager.startActivity: an error where the
109 * caller has requested both to forward a result and to receive
113 public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
116 * Result for IActivityManager.startActivity: an error where the
117 * requested class is not found.
120 public static final int START_CLASS_NOT_FOUND = -2;
123 * Result for IActivityManager.startActivity: an error where the
124 * given Intent could not be resolved to an activity.
127 public static final int START_INTENT_NOT_RESOLVED = -1;
130 * Result for IActivityManaqer.startActivity: the activity was started
131 * successfully as normal.
134 public static final int START_SUCCESS = 0;
137 * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
138 * be executed if it is the recipient, and that is indeed the case.
141 public static final int START_RETURN_INTENT_TO_CALLER = 1;
144 * Result for IActivityManaqer.startActivity: activity wasn't really started, but
145 * a task was simply brought to the foreground.
148 public static final int START_TASK_TO_FRONT = 2;
151 * Result for IActivityManaqer.startActivity: activity wasn't really started, but
152 * the given Intent was given to the existing top activity.
155 public static final int START_DELIVERED_TO_TOP = 3;
158 * Result for IActivityManaqer.startActivity: request was canceled because
159 * app switches are temporarily canceled to ensure the user's last request
160 * (such as pressing home) is performed.
163 public static final int START_SWITCHES_CANCELED = 4;
166 * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
167 * while in Lock Task Mode.
170 public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION = 5;
173 * Flag for IActivityManaqer.startActivity: do special start mode where
174 * a new activity is launched only if it is needed.
177 public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
180 * Flag for IActivityManaqer.startActivity: launch the app for
184 public static final int START_FLAG_DEBUG = 1<<1;
187 * Flag for IActivityManaqer.startActivity: launch the app for
191 public static final int START_FLAG_OPENGL_TRACES = 1<<2;
194 * Flag for IActivityManaqer.startActivity: if the app is being
195 * launched for profiling, automatically stop the profiler once done.
198 public static final int START_FLAG_AUTO_STOP_PROFILER = 1<<3;
201 * Result for IActivityManaqer.broadcastIntent: success!
204 public static final int BROADCAST_SUCCESS = 0;
207 * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
208 * a sticky intent without appropriate permission.
211 public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
214 * Type for IActivityManaqer.getIntentSender: this PendingIntent is
215 * for a sendBroadcast operation.
218 public static final int INTENT_SENDER_BROADCAST = 1;
221 * Type for IActivityManaqer.getIntentSender: this PendingIntent is
222 * for a startActivity operation.
225 public static final int INTENT_SENDER_ACTIVITY = 2;
228 * Type for IActivityManaqer.getIntentSender: this PendingIntent is
229 * for an activity result operation.
232 public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
235 * Type for IActivityManaqer.getIntentSender: this PendingIntent is
236 * for a startService operation.
239 public static final int INTENT_SENDER_SERVICE = 4;
241 /** @hide User operation call: success! */
242 public static final int USER_OP_SUCCESS = 0;
244 /** @hide User operation call: given user id is not known. */
245 public static final int USER_OP_UNKNOWN_USER = -1;
247 /** @hide User operation call: given user id is the current user, can't be stopped. */
248 public static final int USER_OP_IS_CURRENT = -2;
250 /** @hide Process is a persistent system process. */
251 public static final int PROCESS_STATE_PERSISTENT = 0;
253 /** @hide Process is a persistent system process and is doing UI. */
254 public static final int PROCESS_STATE_PERSISTENT_UI = 1;
256 /** @hide Process is hosting the current top activities. Note that this covers
257 * all activities that are visible to the user. */
258 public static final int PROCESS_STATE_TOP = 2;
260 /** @hide Process is important to the user, and something they are aware of. */
261 public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 3;
263 /** @hide Process is important to the user, but not something they are aware of. */
264 public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 4;
266 /** @hide Process is in the background running a backup/restore operation. */
267 public static final int PROCESS_STATE_BACKUP = 5;
269 /** @hide Process is in the background, but it can't restore its state so we want
270 * to try to avoid killing it. */
271 public static final int PROCESS_STATE_HEAVY_WEIGHT = 6;
273 /** @hide Process is in the background running a service. Unlike oom_adj, this level
274 * is used for both the normal running in background state and the executing
275 * operations state. */
276 public static final int PROCESS_STATE_SERVICE = 7;
278 /** @hide Process is in the background running a receiver. Note that from the
279 * perspective of oom_adj receivers run at a higher foreground level, but for our
280 * prioritization here that is not necessary and putting them below services means
281 * many fewer changes in some process states as they receive broadcasts. */
282 public static final int PROCESS_STATE_RECEIVER = 8;
284 /** @hide Process is in the background but hosts the home activity. */
285 public static final int PROCESS_STATE_HOME = 9;
287 /** @hide Process is in the background but hosts the last shown activity. */
288 public static final int PROCESS_STATE_LAST_ACTIVITY = 10;
290 /** @hide Process is being cached for later use and contains activities. */
291 public static final int PROCESS_STATE_CACHED_ACTIVITY = 11;
293 /** @hide Process is being cached for later use and is a client of another cached
294 * process that contains activities. */
295 public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 12;
297 /** @hide Process is being cached for later use and is empty. */
298 public static final int PROCESS_STATE_CACHED_EMPTY = 13;
300 /*package*/ ActivityManager(Context context, Handler handler) {
306 * Screen compatibility mode: the application most always run in
307 * compatibility mode.
310 public static final int COMPAT_MODE_ALWAYS = -1;
313 * Screen compatibility mode: the application can never run in
314 * compatibility mode.
317 public static final int COMPAT_MODE_NEVER = -2;
320 * Screen compatibility mode: unknown.
323 public static final int COMPAT_MODE_UNKNOWN = -3;
326 * Screen compatibility mode: the application currently has compatibility
330 public static final int COMPAT_MODE_DISABLED = 0;
333 * Screen compatibility mode: the application currently has compatibility
337 public static final int COMPAT_MODE_ENABLED = 1;
340 * Screen compatibility mode: request to toggle the application's
341 * compatibility mode.
344 public static final int COMPAT_MODE_TOGGLE = 2;
347 public int getFrontActivityScreenCompatMode() {
349 return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
350 } catch (RemoteException e) {
351 // System dead, we will be dead too soon!
357 public void setFrontActivityScreenCompatMode(int mode) {
359 ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
360 } catch (RemoteException e) {
361 // System dead, we will be dead too soon!
366 public int getPackageScreenCompatMode(String packageName) {
368 return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
369 } catch (RemoteException e) {
370 // System dead, we will be dead too soon!
376 public void setPackageScreenCompatMode(String packageName, int mode) {
378 ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
379 } catch (RemoteException e) {
380 // System dead, we will be dead too soon!
385 public boolean getPackageAskScreenCompat(String packageName) {
387 return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
388 } catch (RemoteException e) {
389 // System dead, we will be dead too soon!
395 public void setPackageAskScreenCompat(String packageName, boolean ask) {
397 ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
398 } catch (RemoteException e) {
399 // System dead, we will be dead too soon!
404 * Return the approximate per-application memory class of the current
405 * device. This gives you an idea of how hard a memory limit you should
406 * impose on your application to let the overall system work best. The
407 * returned value is in megabytes; the baseline Android memory class is
408 * 16 (which happens to be the Java heap limit of those devices); some
409 * device with more memory may return 24 or even higher numbers.
411 public int getMemoryClass() {
412 return staticGetMemoryClass();
416 static public int staticGetMemoryClass() {
417 // Really brain dead right now -- just take this from the configured
418 // vm heap size, and assume it is in megabytes and thus ends with "m".
419 String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
420 if (vmHeapSize != null && !"".equals(vmHeapSize)) {
421 return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
423 return staticGetLargeMemoryClass();
427 * Return the approximate per-application memory class of the current
428 * device when an application is running with a large heap. This is the
429 * space available for memory-intensive applications; most applications
430 * should not need this amount of memory, and should instead stay with the
431 * {@link #getMemoryClass()} limit. The returned value is in megabytes.
432 * This may be the same size as {@link #getMemoryClass()} on memory
433 * constrained devices, or it may be significantly larger on devices with
434 * a large amount of available RAM.
436 * <p>The is the size of the application's Dalvik heap if it has
437 * specified <code>android:largeHeap="true"</code> in its manifest.
439 public int getLargeMemoryClass() {
440 return staticGetLargeMemoryClass();
444 static public int staticGetLargeMemoryClass() {
445 // Really brain dead right now -- just take this from the configured
446 // vm heap size, and assume it is in megabytes and thus ends with "m".
447 String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
448 return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
452 * Returns true if this is a low-RAM device. Exactly whether a device is low-RAM
453 * is ultimately up to the device configuration, but currently it generally means
454 * something in the class of a 512MB device with about a 800x480 or less screen.
455 * This is mostly intended to be used by apps to determine whether they should turn
456 * off certain features that require more RAM.
458 public boolean isLowRamDevice() {
459 return isLowRamDeviceStatic();
463 public static boolean isLowRamDeviceStatic() {
464 return "true".equals(SystemProperties.get("ro.config.low_ram", "false"));
468 * Used by persistent processes to determine if they are running on a
469 * higher-end device so should be okay using hardware drawing acceleration
470 * (which tends to consume a lot more RAM).
473 static public boolean isHighEndGfx() {
474 return !isLowRamDeviceStatic() &&
475 !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
479 * Information you can set and retrieve about the current activity within the recent task list.
481 public static class TaskDescription implements Parcelable {
482 private String mLabel;
483 private Bitmap mIcon;
484 private int mColorPrimary;
487 * Creates the TaskDescription to the specified values.
489 * @param label A label and description of the current state of this task.
490 * @param icon An icon that represents the current state of this task.
491 * @param colorPrimary A color to override the theme's primary color. This color must be opaque.
493 public TaskDescription(String label, Bitmap icon, int colorPrimary) {
494 if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
495 throw new RuntimeException("A TaskDescription's primary color should be opaque");
500 mColorPrimary = colorPrimary;
504 * Creates the TaskDescription to the specified values.
506 * @param label A label and description of the current state of this activity.
507 * @param icon An icon that represents the current state of this activity.
509 public TaskDescription(String label, Bitmap icon) {
510 this(label, icon, 0);
514 * Creates the TaskDescription to the specified values.
516 * @param label A label and description of the current state of this activity.
518 public TaskDescription(String label) {
519 this(label, null, 0);
523 * Creates an empty TaskDescription.
525 public TaskDescription() {
530 * Creates a copy of another TaskDescription.
532 public TaskDescription(TaskDescription td) {
533 this(td.getLabel(), td.getIcon(), td.getPrimaryColor());
536 private TaskDescription(Parcel source) {
537 readFromParcel(source);
541 * Sets the label for this task description.
544 public void setLabel(String label) {
549 * Sets the primary color for this task description.
552 public void setPrimaryColor(int primaryColor) {
553 mColorPrimary = primaryColor;
557 * Sets the icon for this task description.
560 public void setIcon(Bitmap icon) {
565 * @return The label and description of the current state of this task.
567 public String getLabel() {
572 * @return The icon that represents the current state of this task.
574 public Bitmap getIcon() {
579 * @return The color override on the theme's primary color.
581 public int getPrimaryColor() {
582 return mColorPrimary;
586 public int describeContents() {
591 public void writeToParcel(Parcel dest, int flags) {
592 if (mLabel == null) {
596 dest.writeString(mLabel);
602 mIcon.writeToParcel(dest, 0);
604 dest.writeInt(mColorPrimary);
607 public void readFromParcel(Parcel source) {
608 mLabel = source.readInt() > 0 ? source.readString() : null;
609 mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null;
610 mColorPrimary = source.readInt();
613 public static final Creator<TaskDescription> CREATOR
614 = new Creator<TaskDescription>() {
615 public TaskDescription createFromParcel(Parcel source) {
616 return new TaskDescription(source);
618 public TaskDescription[] newArray(int size) {
619 return new TaskDescription[size];
624 public String toString() {
625 return "TaskDescription Label: " + mLabel + " Icon: " + mIcon +
626 " colorPrimary: " + mColorPrimary;
631 * Information you can retrieve about tasks that the user has most recently
632 * started or visited.
634 public static class RecentTaskInfo implements Parcelable {
636 * If this task is currently running, this is the identifier for it.
637 * If it is not running, this will be -1.
642 * The true identifier of this task, valid even if it is not running.
644 public int persistentId;
647 * The original Intent used to launch the task. You can use this
648 * Intent to re-launch the task (if it is no longer running) or bring
649 * the current task to the front.
651 public Intent baseIntent;
654 * If this task was started from an alias, this is the actual
655 * activity component that was initially started; the component of
656 * the baseIntent in this case is the name of the actual activity
657 * implementation that the alias referred to. Otherwise, this is null.
659 public ComponentName origActivity;
662 * Description of the task's last state.
664 public CharSequence description;
667 * The id of the ActivityStack this Task was on most recently.
673 * The id of the user the task was running as.
679 * The first time this task was active.
682 public long firstActiveTime;
685 * The last time this task was active.
688 public long lastActiveTime;
691 * The recent activity values for the highest activity in the stack to have set the values.
692 * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
696 public TaskDescription taskDescription;
699 * Task affiliation for grouping with other tasks.
701 public int affiliatedTaskId;
704 * Task affiliation color of the source task with the affiliated task id.
708 public int affiliatedTaskColor;
710 public RecentTaskInfo() {
714 public int describeContents() {
719 public void writeToParcel(Parcel dest, int flags) {
721 dest.writeInt(persistentId);
722 if (baseIntent != null) {
724 baseIntent.writeToParcel(dest, 0);
728 ComponentName.writeToParcel(origActivity, dest);
729 TextUtils.writeToParcel(description, dest,
730 Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
731 if (taskDescription != null) {
733 taskDescription.writeToParcel(dest, 0);
737 dest.writeInt(stackId);
738 dest.writeInt(userId);
739 dest.writeLong(firstActiveTime);
740 dest.writeLong(lastActiveTime);
741 dest.writeInt(affiliatedTaskId);
742 dest.writeInt(affiliatedTaskColor);
745 public void readFromParcel(Parcel source) {
746 id = source.readInt();
747 persistentId = source.readInt();
748 baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
749 origActivity = ComponentName.readFromParcel(source);
750 description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
751 taskDescription = source.readInt() > 0 ?
752 TaskDescription.CREATOR.createFromParcel(source) : null;
753 stackId = source.readInt();
754 userId = source.readInt();
755 firstActiveTime = source.readLong();
756 lastActiveTime = source.readLong();
757 affiliatedTaskId = source.readInt();
758 affiliatedTaskColor = source.readInt();
761 public static final Creator<RecentTaskInfo> CREATOR
762 = new Creator<RecentTaskInfo>() {
763 public RecentTaskInfo createFromParcel(Parcel source) {
764 return new RecentTaskInfo(source);
766 public RecentTaskInfo[] newArray(int size) {
767 return new RecentTaskInfo[size];
771 private RecentTaskInfo(Parcel source) {
772 readFromParcel(source);
777 * Flag for use with {@link #getRecentTasks}: return all tasks, even those
778 * that have set their
779 * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
781 public static final int RECENT_WITH_EXCLUDED = 0x0001;
784 * Provides a list that does not contain any
785 * recent tasks that currently are not available to the user.
787 public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
790 * Provides a list that contains recent tasks for all
791 * profiles of a user.
794 public static final int RECENT_INCLUDE_PROFILES = 0x0004;
797 * <p></p>Return a list of the tasks that the user has recently launched, with
798 * the most recent being first and older ones after in order.
800 * <p><b>Note: this method is only intended for debugging and presenting
801 * task management user interfaces</b>. This should never be used for
802 * core logic in an application, such as deciding between different
803 * behaviors based on the information found here. Such uses are
804 * <em>not</em> supported, and will likely break in the future. For
805 * example, if multiple applications can be actively running at the
806 * same time, assumptions made about the meaning of the data here for
807 * purposes of control flow will be incorrect.</p>
809 * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method is
810 * no longer available to third party applications: as the introduction of
811 * document-centric recents means
812 * it can leak personal information to the caller. For backwards compatibility,
813 * it will still return a small subset of its data: at least the caller's
814 * own tasks (though see {@link #getAppTasks()} for the correct supported
815 * way to retrieve that information), and possibly some other tasks
816 * such as home that are known to not be sensitive.
818 * @param maxNum The maximum number of entries to return in the list. The
819 * actual number returned may be smaller, depending on how many tasks the
820 * user has started and the maximum number the system can remember.
821 * @param flags Information about what to return. May be any combination
822 * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
824 * @return Returns a list of RecentTaskInfo records describing each of
827 * @throws SecurityException Throws SecurityException if the caller does
828 * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
831 public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
832 throws SecurityException {
834 return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
835 flags, UserHandle.myUserId());
836 } catch (RemoteException e) {
837 // System dead, we will be dead too soon!
843 * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
844 * specific user. It requires holding
845 * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
846 * @param maxNum The maximum number of entries to return in the list. The
847 * actual number returned may be smaller, depending on how many tasks the
848 * user has started and the maximum number the system can remember.
849 * @param flags Information about what to return. May be any combination
850 * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
852 * @return Returns a list of RecentTaskInfo records describing each of
855 * @throws SecurityException Throws SecurityException if the caller does
856 * not hold the {@link android.Manifest.permission#GET_TASKS} or the
857 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
860 public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
861 throws SecurityException {
863 return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
865 } catch (RemoteException e) {
866 // System dead, we will be dead too soon!
872 * Information you can retrieve about a particular task that is currently
873 * "running" in the system. Note that a running task does not mean the
874 * given task actually has a process it is actively running in; it simply
875 * means that the user has gone to it and never closed it, but currently
876 * the system may have killed its process and is only holding on to its
877 * last state in order to restart it when the user returns.
879 public static class RunningTaskInfo implements Parcelable {
881 * A unique identifier for this task.
886 * The component launched as the first activity in the task. This can
887 * be considered the "application" of this task.
889 public ComponentName baseActivity;
892 * The activity component at the top of the history stack of the task.
893 * This is what the user is currently doing.
895 public ComponentName topActivity;
898 * Thumbnail representation of the task's current state. Currently
901 public Bitmap thumbnail;
904 * Description of the task's current state.
906 public CharSequence description;
909 * Number of activities in this task.
911 public int numActivities;
914 * Number of activities that are currently running (not stopped
915 * and persisted) in this task.
917 public int numRunning;
920 * Last time task was run. For sorting.
923 public long lastActiveTime;
925 public RunningTaskInfo() {
928 public int describeContents() {
932 public void writeToParcel(Parcel dest, int flags) {
934 ComponentName.writeToParcel(baseActivity, dest);
935 ComponentName.writeToParcel(topActivity, dest);
936 if (thumbnail != null) {
938 thumbnail.writeToParcel(dest, 0);
942 TextUtils.writeToParcel(description, dest,
943 Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
944 dest.writeInt(numActivities);
945 dest.writeInt(numRunning);
948 public void readFromParcel(Parcel source) {
949 id = source.readInt();
950 baseActivity = ComponentName.readFromParcel(source);
951 topActivity = ComponentName.readFromParcel(source);
952 if (source.readInt() != 0) {
953 thumbnail = Bitmap.CREATOR.createFromParcel(source);
957 description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
958 numActivities = source.readInt();
959 numRunning = source.readInt();
962 public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
963 public RunningTaskInfo createFromParcel(Parcel source) {
964 return new RunningTaskInfo(source);
966 public RunningTaskInfo[] newArray(int size) {
967 return new RunningTaskInfo[size];
971 private RunningTaskInfo(Parcel source) {
972 readFromParcel(source);
977 * Get the list of tasks associated with the calling application.
979 * @return The list of tasks associated with the application making this call.
980 * @throws SecurityException
982 public List<ActivityManager.AppTask> getAppTasks() {
983 ArrayList<AppTask> tasks = new ArrayList<AppTask>();
984 List<IAppTask> appTasks;
986 appTasks = ActivityManagerNative.getDefault().getAppTasks();
987 } catch (RemoteException e) {
988 // System dead, we will be dead too soon!
991 int numAppTasks = appTasks.size();
992 for (int i = 0; i < numAppTasks; i++) {
993 tasks.add(new AppTask(appTasks.get(i)));
999 * Return a list of the tasks that are currently running, with
1000 * the most recent being first and older ones after in order. Note that
1001 * "running" does not mean any of the task's code is currently loaded or
1002 * activity -- the task may have been frozen by the system, so that it
1003 * can be restarted in its previous state when next brought to the
1006 * <p><b>Note: this method is only intended for debugging and presenting
1007 * task management user interfaces</b>. This should never be used for
1008 * core logic in an application, such as deciding between different
1009 * behaviors based on the information found here. Such uses are
1010 * <em>not</em> supported, and will likely break in the future. For
1011 * example, if multiple applications can be actively running at the
1012 * same time, assumptions made about the meaning of the data here for
1013 * purposes of control flow will be incorrect.</p>
1015 * @deprecated As of {@link android.os.Build.VERSION_CODES#L}, this method
1016 * is no longer available to third party
1017 * applications: the introduction of document-centric recents means
1018 * it can leak person information to the caller. For backwards compatibility,
1019 * it will still retu rn a small subset of its data: at least the caller's
1020 * own tasks, and possibly some other tasks
1021 * such as home that are known to not be sensitive.
1023 * @param maxNum The maximum number of entries to return in the list. The
1024 * actual number returned may be smaller, depending on how many tasks the
1027 * @return Returns a list of RunningTaskInfo records describing each of
1028 * the running tasks.
1030 * @throws SecurityException Throws SecurityException if the caller does
1031 * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
1034 public List<RunningTaskInfo> getRunningTasks(int maxNum)
1035 throws SecurityException {
1037 return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
1038 } catch (RemoteException e) {
1039 // System dead, we will be dead too soon!
1045 * If set, the process of the root activity of the task will be killed
1046 * as part of removing the task.
1049 public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
1052 * Completely remove the given task.
1054 * @param taskId Identifier of the task to be removed.
1055 * @param flags Additional operational flags. May be 0 or
1056 * {@link #REMOVE_TASK_KILL_PROCESS}.
1057 * @return Returns true if the given task was found and removed.
1061 public boolean removeTask(int taskId, int flags)
1062 throws SecurityException {
1064 return ActivityManagerNative.getDefault().removeTask(taskId, flags);
1065 } catch (RemoteException e) {
1066 // System dead, we will be dead too soon!
1072 public static class TaskThumbnail implements Parcelable {
1073 public Bitmap mainThumbnail;
1074 public ParcelFileDescriptor thumbnailFileDescriptor;
1076 public TaskThumbnail() {
1079 public int describeContents() {
1080 if (thumbnailFileDescriptor != null) {
1081 return thumbnailFileDescriptor.describeContents();
1086 public void writeToParcel(Parcel dest, int flags) {
1087 if (mainThumbnail != null) {
1089 mainThumbnail.writeToParcel(dest, 0);
1093 if (thumbnailFileDescriptor != null) {
1095 thumbnailFileDescriptor.writeToParcel(dest, 0);
1101 public void readFromParcel(Parcel source) {
1102 if (source.readInt() != 0) {
1103 mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
1105 mainThumbnail = null;
1107 if (source.readInt() != 0) {
1108 thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
1110 thumbnailFileDescriptor = null;
1114 public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
1115 public TaskThumbnail createFromParcel(Parcel source) {
1116 return new TaskThumbnail(source);
1118 public TaskThumbnail[] newArray(int size) {
1119 return new TaskThumbnail[size];
1123 private TaskThumbnail(Parcel source) {
1124 readFromParcel(source);
1129 public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
1131 return ActivityManagerNative.getDefault().getTaskThumbnail(id);
1132 } catch (RemoteException e) {
1133 // System dead, we will be dead too soon!
1139 public boolean isInHomeStack(int taskId) {
1141 return ActivityManagerNative.getDefault().isInHomeStack(taskId);
1142 } catch (RemoteException e) {
1143 // System dead, we will be dead too soon!
1149 * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
1150 * activity along with the task, so it is positioned immediately behind
1153 public static final int MOVE_TASK_WITH_HOME = 0x00000001;
1156 * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
1157 * user-instigated action, so the current activity will not receive a
1158 * hint that the user is leaving.
1160 public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
1163 * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
1164 * with a null options argument.
1166 * @param taskId The identifier of the task to be moved, as found in
1167 * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1168 * @param flags Additional operational flags, 0 or more of
1169 * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1171 public void moveTaskToFront(int taskId, int flags) {
1172 moveTaskToFront(taskId, flags, null);
1176 * Ask that the task associated with a given task ID be moved to the
1177 * front of the stack, so it is now visible to the user. Requires that
1178 * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
1179 * or a SecurityException will be thrown.
1181 * @param taskId The identifier of the task to be moved, as found in
1182 * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
1183 * @param flags Additional operational flags, 0 or more of
1184 * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
1185 * @param options Additional options for the operation, either null or
1186 * as per {@link Context#startActivity(Intent, android.os.Bundle)
1187 * Context.startActivity(Intent, Bundle)}.
1189 public void moveTaskToFront(int taskId, int flags, Bundle options) {
1191 ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
1192 } catch (RemoteException e) {
1193 // System dead, we will be dead too soon!
1198 * Information you can retrieve about a particular Service that is
1199 * currently running in the system.
1201 public static class RunningServiceInfo implements Parcelable {
1203 * The service component.
1205 public ComponentName service;
1208 * If non-zero, this is the process the service is running in.
1213 * The UID that owns this service.
1218 * The name of the process this service runs in.
1220 public String process;
1223 * Set to true if the service has asked to run as a foreground process.
1225 public boolean foreground;
1228 * The time when the service was first made active, either by someone
1229 * starting or binding to it. This
1230 * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
1232 public long activeSince;
1235 * Set to true if this service has been explicitly started.
1237 public boolean started;
1240 * Number of clients connected to the service.
1242 public int clientCount;
1245 * Number of times the service's process has crashed while the service
1248 public int crashCount;
1251 * The time when there was last activity in the service (either
1252 * explicit requests to start it or clients binding to it). This
1253 * is in units of {@link android.os.SystemClock#uptimeMillis()}.
1255 public long lastActivityTime;
1258 * If non-zero, this service is not currently running, but scheduled to
1259 * restart at the given time.
1261 public long restarting;
1264 * Bit for {@link #flags}: set if this service has been
1265 * explicitly started.
1267 public static final int FLAG_STARTED = 1<<0;
1270 * Bit for {@link #flags}: set if the service has asked to
1271 * run as a foreground process.
1273 public static final int FLAG_FOREGROUND = 1<<1;
1276 * Bit for {@link #flags): set if the service is running in a
1277 * core system process.
1279 public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1282 * Bit for {@link #flags): set if the service is running in a
1283 * persistent process.
1285 public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1293 * For special services that are bound to by system code, this is
1294 * the package that holds the binding.
1296 public String clientPackage;
1299 * For special services that are bound to by system code, this is
1300 * a string resource providing a user-visible label for who the
1303 public int clientLabel;
1305 public RunningServiceInfo() {
1308 public int describeContents() {
1312 public void writeToParcel(Parcel dest, int flags) {
1313 ComponentName.writeToParcel(service, dest);
1316 dest.writeString(process);
1317 dest.writeInt(foreground ? 1 : 0);
1318 dest.writeLong(activeSince);
1319 dest.writeInt(started ? 1 : 0);
1320 dest.writeInt(clientCount);
1321 dest.writeInt(crashCount);
1322 dest.writeLong(lastActivityTime);
1323 dest.writeLong(restarting);
1324 dest.writeInt(this.flags);
1325 dest.writeString(clientPackage);
1326 dest.writeInt(clientLabel);
1329 public void readFromParcel(Parcel source) {
1330 service = ComponentName.readFromParcel(source);
1331 pid = source.readInt();
1332 uid = source.readInt();
1333 process = source.readString();
1334 foreground = source.readInt() != 0;
1335 activeSince = source.readLong();
1336 started = source.readInt() != 0;
1337 clientCount = source.readInt();
1338 crashCount = source.readInt();
1339 lastActivityTime = source.readLong();
1340 restarting = source.readLong();
1341 flags = source.readInt();
1342 clientPackage = source.readString();
1343 clientLabel = source.readInt();
1346 public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1347 public RunningServiceInfo createFromParcel(Parcel source) {
1348 return new RunningServiceInfo(source);
1350 public RunningServiceInfo[] newArray(int size) {
1351 return new RunningServiceInfo[size];
1355 private RunningServiceInfo(Parcel source) {
1356 readFromParcel(source);
1361 * Return a list of the services that are currently running.
1363 * <p><b>Note: this method is only intended for debugging or implementing
1364 * service management type user interfaces.</b></p>
1366 * @param maxNum The maximum number of entries to return in the list. The
1367 * actual number returned may be smaller, depending on how many services
1370 * @return Returns a list of RunningServiceInfo records describing each of
1371 * the running tasks.
1373 public List<RunningServiceInfo> getRunningServices(int maxNum)
1374 throws SecurityException {
1376 return ActivityManagerNative.getDefault()
1377 .getServices(maxNum, 0);
1378 } catch (RemoteException e) {
1379 // System dead, we will be dead too soon!
1385 * Returns a PendingIntent you can start to show a control panel for the
1386 * given running service. If the service does not have a control panel,
1389 public PendingIntent getRunningServiceControlPanel(ComponentName service)
1390 throws SecurityException {
1392 return ActivityManagerNative.getDefault()
1393 .getRunningServiceControlPanel(service);
1394 } catch (RemoteException e) {
1395 // System dead, we will be dead too soon!
1401 * Information you can retrieve about the available memory through
1402 * {@link ActivityManager#getMemoryInfo}.
1404 public static class MemoryInfo implements Parcelable {
1406 * The available memory on the system. This number should not
1407 * be considered absolute: due to the nature of the kernel, a significant
1408 * portion of this memory is actually in use and needed for the overall
1409 * system to run well.
1411 public long availMem;
1414 * The total memory accessible by the kernel. This is basically the
1415 * RAM size of the device, not including below-kernel fixed allocations
1416 * like DMA buffers, RAM for the baseband CPU, etc.
1418 public long totalMem;
1421 * The threshold of {@link #availMem} at which we consider memory to be
1422 * low and start killing background services and other non-extraneous
1425 public long threshold;
1428 * Set to true if the system considers itself to currently be in a low
1431 public boolean lowMemory;
1434 public long hiddenAppThreshold;
1436 public long secondaryServerThreshold;
1438 public long visibleAppThreshold;
1440 public long foregroundAppThreshold;
1442 public MemoryInfo() {
1445 public int describeContents() {
1449 public void writeToParcel(Parcel dest, int flags) {
1450 dest.writeLong(availMem);
1451 dest.writeLong(totalMem);
1452 dest.writeLong(threshold);
1453 dest.writeInt(lowMemory ? 1 : 0);
1454 dest.writeLong(hiddenAppThreshold);
1455 dest.writeLong(secondaryServerThreshold);
1456 dest.writeLong(visibleAppThreshold);
1457 dest.writeLong(foregroundAppThreshold);
1460 public void readFromParcel(Parcel source) {
1461 availMem = source.readLong();
1462 totalMem = source.readLong();
1463 threshold = source.readLong();
1464 lowMemory = source.readInt() != 0;
1465 hiddenAppThreshold = source.readLong();
1466 secondaryServerThreshold = source.readLong();
1467 visibleAppThreshold = source.readLong();
1468 foregroundAppThreshold = source.readLong();
1471 public static final Creator<MemoryInfo> CREATOR
1472 = new Creator<MemoryInfo>() {
1473 public MemoryInfo createFromParcel(Parcel source) {
1474 return new MemoryInfo(source);
1476 public MemoryInfo[] newArray(int size) {
1477 return new MemoryInfo[size];
1481 private MemoryInfo(Parcel source) {
1482 readFromParcel(source);
1487 * Return general information about the memory state of the system. This
1488 * can be used to help decide how to manage your own memory, though note
1489 * that polling is not recommended and
1490 * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1491 * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1492 * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1493 * level of your process as needed, which gives a better hint for how to
1494 * manage its memory.
1496 public void getMemoryInfo(MemoryInfo outInfo) {
1498 ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1499 } catch (RemoteException e) {
1504 * Information you can retrieve about an ActivityStack in the system.
1507 public static class StackInfo implements Parcelable {
1509 public Rect bounds = new Rect();
1510 public int[] taskIds;
1511 public String[] taskNames;
1512 public int displayId;
1515 public int describeContents() {
1520 public void writeToParcel(Parcel dest, int flags) {
1521 dest.writeInt(stackId);
1522 dest.writeInt(bounds.left);
1523 dest.writeInt(bounds.top);
1524 dest.writeInt(bounds.right);
1525 dest.writeInt(bounds.bottom);
1526 dest.writeIntArray(taskIds);
1527 dest.writeStringArray(taskNames);
1528 dest.writeInt(displayId);
1531 public void readFromParcel(Parcel source) {
1532 stackId = source.readInt();
1534 source.readInt(), source.readInt(), source.readInt(), source.readInt());
1535 taskIds = source.createIntArray();
1536 taskNames = source.createStringArray();
1537 displayId = source.readInt();
1540 public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1542 public StackInfo createFromParcel(Parcel source) {
1543 return new StackInfo(source);
1546 public StackInfo[] newArray(int size) {
1547 return new StackInfo[size];
1551 public StackInfo() {
1554 private StackInfo(Parcel source) {
1555 readFromParcel(source);
1558 public String toString(String prefix) {
1559 StringBuilder sb = new StringBuilder(256);
1560 sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1561 sb.append(" bounds="); sb.append(bounds.toShortString());
1562 sb.append(" displayId="); sb.append(displayId);
1564 prefix = prefix + " ";
1565 for (int i = 0; i < taskIds.length; ++i) {
1566 sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1567 sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
1569 return sb.toString();
1573 public String toString() {
1574 return toString("");
1581 public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1583 return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1584 observer, UserHandle.myUserId());
1585 } catch (RemoteException e) {
1591 * Permits an application to erase its own data from disk. This is equivalent to
1592 * the user choosing to clear the app's data from within the device settings UI. It
1593 * erases all dynamic data associated with the app -- its private data and data in its
1594 * private area on external storage -- but does not remove the installed application
1595 * itself, nor any OBB files.
1597 * @return {@code true} if the application successfully requested that the application's
1598 * data be erased; {@code false} otherwise.
1600 public boolean clearApplicationUserData() {
1601 return clearApplicationUserData(mContext.getPackageName(), null);
1605 * Information you can retrieve about any processes that are in an error condition.
1607 public static class ProcessErrorStateInfo implements Parcelable {
1611 public static final int NO_ERROR = 0;
1612 public static final int CRASHED = 1;
1613 public static final int NOT_RESPONDING = 2;
1616 * The condition that the process is in.
1618 public int condition;
1621 * The process name in which the crash or error occurred.
1623 public String processName;
1626 * The pid of this process; 0 if none
1631 * The kernel user-ID that has been assigned to this process;
1632 * currently this is not a unique ID (multiple applications can have
1638 * The activity name associated with the error, if known. May be null.
1643 * A short message describing the error condition.
1645 public String shortMsg;
1648 * A long message describing the error condition.
1650 public String longMsg;
1653 * The stack trace where the error originated. May be null.
1655 public String stackTrace;
1658 * to be deprecated: This value will always be null.
1660 public byte[] crashData = null;
1662 public ProcessErrorStateInfo() {
1666 public int describeContents() {
1671 public void writeToParcel(Parcel dest, int flags) {
1672 dest.writeInt(condition);
1673 dest.writeString(processName);
1676 dest.writeString(tag);
1677 dest.writeString(shortMsg);
1678 dest.writeString(longMsg);
1679 dest.writeString(stackTrace);
1682 public void readFromParcel(Parcel source) {
1683 condition = source.readInt();
1684 processName = source.readString();
1685 pid = source.readInt();
1686 uid = source.readInt();
1687 tag = source.readString();
1688 shortMsg = source.readString();
1689 longMsg = source.readString();
1690 stackTrace = source.readString();
1693 public static final Creator<ProcessErrorStateInfo> CREATOR =
1694 new Creator<ProcessErrorStateInfo>() {
1695 public ProcessErrorStateInfo createFromParcel(Parcel source) {
1696 return new ProcessErrorStateInfo(source);
1698 public ProcessErrorStateInfo[] newArray(int size) {
1699 return new ProcessErrorStateInfo[size];
1703 private ProcessErrorStateInfo(Parcel source) {
1704 readFromParcel(source);
1709 * Returns a list of any processes that are currently in an error condition. The result
1710 * will be null if all processes are running properly at this time.
1712 * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1713 * current error conditions (it will not return an empty list). This list ordering is not
1716 public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1718 return ActivityManagerNative.getDefault().getProcessesInErrorState();
1719 } catch (RemoteException e) {
1725 * Information you can retrieve about a running process.
1727 public static class RunningAppProcessInfo implements Parcelable {
1729 * The name of the process that this object is associated with
1731 public String processName;
1734 * The pid of this process; 0 if none
1739 * The user id of this process.
1744 * All packages that have been loaded into the process.
1746 public String pkgList[];
1749 * Constant for {@link #flags}: this is an app that is unable to
1750 * correctly save its state when going to the background,
1751 * so it can not be killed while in the background.
1754 public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1757 * Constant for {@link #flags}: this process is associated with a
1758 * persistent system app.
1761 public static final int FLAG_PERSISTENT = 1<<1;
1764 * Constant for {@link #flags}: this process is associated with a
1765 * persistent system app.
1768 public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1771 * Flags of information. May be any of
1772 * {@link #FLAG_CANT_SAVE_STATE}.
1778 * Last memory trim level reported to the process: corresponds to
1779 * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1780 * ComponentCallbacks2.onTrimMemory(int)}.
1782 public int lastTrimLevel;
1785 * Constant for {@link #importance}: this process is running the
1788 public static final int IMPORTANCE_FOREGROUND = 100;
1791 * Constant for {@link #importance}: this process is running something
1792 * that is actively visible to the user, though not in the immediate
1795 public static final int IMPORTANCE_VISIBLE = 200;
1798 * Constant for {@link #importance}: this process is running something
1799 * that is considered to be actively perceptible to the user. An
1800 * example would be an application performing background music playback.
1802 public static final int IMPORTANCE_PERCEPTIBLE = 130;
1805 * Constant for {@link #importance}: this process is running an
1806 * application that can not save its state, and thus can't be killed
1807 * while in the background.
1810 public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1813 * Constant for {@link #importance}: this process is contains services
1814 * that should remain running.
1816 public static final int IMPORTANCE_SERVICE = 300;
1819 * Constant for {@link #importance}: this process process contains
1820 * background code that is expendable.
1822 public static final int IMPORTANCE_BACKGROUND = 400;
1825 * Constant for {@link #importance}: this process is empty of any
1826 * actively running code.
1828 public static final int IMPORTANCE_EMPTY = 500;
1831 * Constant for {@link #importance}: this process does not exist.
1833 public static final int IMPORTANCE_GONE = 1000;
1836 public static int procStateToImportance(int procState) {
1837 if (procState >= ActivityManager.PROCESS_STATE_HOME) {
1838 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
1839 } else if (procState >= ActivityManager.PROCESS_STATE_SERVICE) {
1840 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
1841 } else if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
1842 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
1843 } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
1844 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
1845 } else if (procState >= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1846 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
1848 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
1853 * The relative importance level that the system places on this
1854 * process. May be one of {@link #IMPORTANCE_FOREGROUND},
1855 * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1856 * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}. These
1857 * constants are numbered so that "more important" values are always
1858 * smaller than "less important" values.
1860 public int importance;
1863 * An additional ordering within a particular {@link #importance}
1864 * category, providing finer-grained information about the relative
1865 * utility of processes within a category. This number means nothing
1866 * except that a smaller values are more recently used (and thus
1867 * more important). Currently an LRU value is only maintained for
1868 * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1869 * be maintained in the future.
1874 * Constant for {@link #importanceReasonCode}: nothing special has
1875 * been specified for the reason for this level.
1877 public static final int REASON_UNKNOWN = 0;
1880 * Constant for {@link #importanceReasonCode}: one of the application's
1881 * content providers is being used by another process. The pid of
1882 * the client process is in {@link #importanceReasonPid} and the
1883 * target provider in this process is in
1884 * {@link #importanceReasonComponent}.
1886 public static final int REASON_PROVIDER_IN_USE = 1;
1889 * Constant for {@link #importanceReasonCode}: one of the application's
1890 * content providers is being used by another process. The pid of
1891 * the client process is in {@link #importanceReasonPid} and the
1892 * target provider in this process is in
1893 * {@link #importanceReasonComponent}.
1895 public static final int REASON_SERVICE_IN_USE = 2;
1898 * The reason for {@link #importance}, if any.
1900 public int importanceReasonCode;
1903 * For the specified values of {@link #importanceReasonCode}, this
1904 * is the process ID of the other process that is a client of this
1905 * process. This will be 0 if no other process is using this one.
1907 public int importanceReasonPid;
1910 * For the specified values of {@link #importanceReasonCode}, this
1911 * is the name of the component that is being used in this process.
1913 public ComponentName importanceReasonComponent;
1916 * When {@link #importanceReasonPid} is non-0, this is the importance
1917 * of the other pid. @hide
1919 public int importanceReasonImportance;
1922 * Current process state, as per PROCESS_STATE_* constants.
1925 public int processState;
1927 public RunningAppProcessInfo() {
1928 importance = IMPORTANCE_FOREGROUND;
1929 importanceReasonCode = REASON_UNKNOWN;
1930 processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
1933 public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1934 processName = pProcessName;
1939 public int describeContents() {
1943 public void writeToParcel(Parcel dest, int flags) {
1944 dest.writeString(processName);
1947 dest.writeStringArray(pkgList);
1948 dest.writeInt(this.flags);
1949 dest.writeInt(lastTrimLevel);
1950 dest.writeInt(importance);
1952 dest.writeInt(importanceReasonCode);
1953 dest.writeInt(importanceReasonPid);
1954 ComponentName.writeToParcel(importanceReasonComponent, dest);
1955 dest.writeInt(importanceReasonImportance);
1956 dest.writeInt(processState);
1959 public void readFromParcel(Parcel source) {
1960 processName = source.readString();
1961 pid = source.readInt();
1962 uid = source.readInt();
1963 pkgList = source.readStringArray();
1964 flags = source.readInt();
1965 lastTrimLevel = source.readInt();
1966 importance = source.readInt();
1967 lru = source.readInt();
1968 importanceReasonCode = source.readInt();
1969 importanceReasonPid = source.readInt();
1970 importanceReasonComponent = ComponentName.readFromParcel(source);
1971 importanceReasonImportance = source.readInt();
1972 processState = source.readInt();
1975 public static final Creator<RunningAppProcessInfo> CREATOR =
1976 new Creator<RunningAppProcessInfo>() {
1977 public RunningAppProcessInfo createFromParcel(Parcel source) {
1978 return new RunningAppProcessInfo(source);
1980 public RunningAppProcessInfo[] newArray(int size) {
1981 return new RunningAppProcessInfo[size];
1985 private RunningAppProcessInfo(Parcel source) {
1986 readFromParcel(source);
1991 * Returns a list of application processes installed on external media
1992 * that are running on the device.
1994 * <p><b>Note: this method is only intended for debugging or building
1995 * a user-facing process management UI.</b></p>
1997 * @return Returns a list of ApplicationInfo records, or null if none
1998 * This list ordering is not specified.
2001 public List<ApplicationInfo> getRunningExternalApplications() {
2003 return ActivityManagerNative.getDefault().getRunningExternalApplications();
2004 } catch (RemoteException e) {
2010 * Returns a list of application processes that are running on the device.
2012 * <p><b>Note: this method is only intended for debugging or building
2013 * a user-facing process management UI.</b></p>
2015 * @return Returns a list of RunningAppProcessInfo records, or null if there are no
2016 * running processes (it will not return an empty list). This list ordering is not
2019 public List<RunningAppProcessInfo> getRunningAppProcesses() {
2021 return ActivityManagerNative.getDefault().getRunningAppProcesses();
2022 } catch (RemoteException e) {
2028 * Return global memory state information for the calling process. This
2029 * does not fill in all fields of the {@link RunningAppProcessInfo}. The
2030 * only fields that will be filled in are
2031 * {@link RunningAppProcessInfo#pid},
2032 * {@link RunningAppProcessInfo#uid},
2033 * {@link RunningAppProcessInfo#lastTrimLevel},
2034 * {@link RunningAppProcessInfo#importance},
2035 * {@link RunningAppProcessInfo#lru}, and
2036 * {@link RunningAppProcessInfo#importanceReasonCode}.
2038 static public void getMyMemoryState(RunningAppProcessInfo outState) {
2040 ActivityManagerNative.getDefault().getMyMemoryState(outState);
2041 } catch (RemoteException e) {
2046 * Return information about the memory usage of one or more processes.
2048 * <p><b>Note: this method is only intended for debugging or building
2049 * a user-facing process management UI.</b></p>
2051 * @param pids The pids of the processes whose memory usage is to be
2053 * @return Returns an array of memory information, one for each
2056 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
2058 return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
2059 } catch (RemoteException e) {
2065 * @deprecated This is now just a wrapper for
2066 * {@link #killBackgroundProcesses(String)}; the previous behavior here
2067 * is no longer available to applications because it allows them to
2068 * break other applications by removing their alarms, stopping their
2072 public void restartPackage(String packageName) {
2073 killBackgroundProcesses(packageName);
2077 * Have the system immediately kill all background processes associated
2078 * with the given package. This is the same as the kernel killing those
2079 * processes to reclaim memory; the system will take care of restarting
2080 * these processes in the future as needed.
2082 * <p>You must hold the permission
2083 * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
2086 * @param packageName The name of the package whose processes are to
2089 public void killBackgroundProcesses(String packageName) {
2091 ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
2092 UserHandle.myUserId());
2093 } catch (RemoteException e) {
2098 * Have the system perform a force stop of everything associated with
2099 * the given application package. All processes that share its uid
2100 * will be killed, all services it has running stopped, all activities
2101 * removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
2102 * broadcast will be sent, so that any of its registered alarms can
2103 * be stopped, notifications removed, etc.
2105 * <p>You must hold the permission
2106 * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
2109 * @param packageName The name of the package to be stopped.
2111 * @hide This is not available to third party applications due to
2112 * it allowing them to break other applications by stopping their
2113 * services, removing their alarms, etc.
2115 public void forceStopPackage(String packageName) {
2117 ActivityManagerNative.getDefault().forceStopPackage(packageName,
2118 UserHandle.myUserId());
2119 } catch (RemoteException e) {
2124 * Get the device configuration attributes.
2126 public ConfigurationInfo getDeviceConfigurationInfo() {
2128 return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
2129 } catch (RemoteException e) {
2135 * Get the preferred density of icons for the launcher. This is used when
2136 * custom drawables are created (e.g., for shortcuts).
2138 * @return density in terms of DPI
2140 public int getLauncherLargeIconDensity() {
2141 final Resources res = mContext.getResources();
2142 final int density = res.getDisplayMetrics().densityDpi;
2143 final int sw = res.getConfiguration().smallestScreenWidthDp;
2146 // Smaller than approx 7" tablets, use the regular icon size.
2151 case DisplayMetrics.DENSITY_LOW:
2152 return DisplayMetrics.DENSITY_MEDIUM;
2153 case DisplayMetrics.DENSITY_MEDIUM:
2154 return DisplayMetrics.DENSITY_HIGH;
2155 case DisplayMetrics.DENSITY_TV:
2156 return DisplayMetrics.DENSITY_XHIGH;
2157 case DisplayMetrics.DENSITY_HIGH:
2158 return DisplayMetrics.DENSITY_XHIGH;
2159 case DisplayMetrics.DENSITY_XHIGH:
2160 return DisplayMetrics.DENSITY_XXHIGH;
2161 case DisplayMetrics.DENSITY_XXHIGH:
2162 return DisplayMetrics.DENSITY_XHIGH * 2;
2164 // The density is some abnormal value. Return some other
2165 // abnormal value that is a reasonable scaling of it.
2166 return (int)((density*1.5f)+.5f);
2171 * Get the preferred launcher icon size. This is used when custom drawables
2172 * are created (e.g., for shortcuts).
2174 * @return dimensions of square icons in terms of pixels
2176 public int getLauncherLargeIconSize() {
2177 return getLauncherLargeIconSizeInner(mContext);
2180 static int getLauncherLargeIconSizeInner(Context context) {
2181 final Resources res = context.getResources();
2182 final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
2183 final int sw = res.getConfiguration().smallestScreenWidthDp;
2186 // Smaller than approx 7" tablets, use the regular icon size.
2190 final int density = res.getDisplayMetrics().densityDpi;
2193 case DisplayMetrics.DENSITY_LOW:
2194 return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
2195 case DisplayMetrics.DENSITY_MEDIUM:
2196 return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
2197 case DisplayMetrics.DENSITY_TV:
2198 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2199 case DisplayMetrics.DENSITY_HIGH:
2200 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
2201 case DisplayMetrics.DENSITY_XHIGH:
2202 return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
2203 case DisplayMetrics.DENSITY_XXHIGH:
2204 return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
2206 // The density is some abnormal value. Return some other
2207 // abnormal value that is a reasonable scaling of it.
2208 return (int)((size*1.5f) + .5f);
2213 * Returns "true" if the user interface is currently being messed with
2216 public static boolean isUserAMonkey() {
2218 return ActivityManagerNative.getDefault().isUserAMonkey();
2219 } catch (RemoteException e) {
2225 * Returns "true" if device is running in a test harness.
2227 public static boolean isRunningInTestHarness() {
2228 return SystemProperties.getBoolean("ro.test_harness", false);
2232 * Returns the launch count of each installed package.
2236 /*public Map<String, Integer> getAllPackageLaunchCounts() {
2238 IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2239 ServiceManager.getService("usagestats"));
2240 if (usageStatsService == null) {
2241 return new HashMap<String, Integer>();
2244 UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
2245 ActivityThread.currentPackageName());
2246 if (allPkgUsageStats == null) {
2247 return new HashMap<String, Integer>();
2250 Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2251 for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
2252 launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
2255 return launchCounts;
2256 } catch (RemoteException e) {
2257 Log.w(TAG, "Could not query launch counts", e);
2258 return new HashMap<String, Integer>();
2263 public static int checkComponentPermission(String permission, int uid,
2264 int owningUid, boolean exported) {
2265 // Root, system server get to do everything.
2266 if (uid == 0 || uid == Process.SYSTEM_UID) {
2267 return PackageManager.PERMISSION_GRANTED;
2269 // Isolated processes don't get any permissions.
2270 if (UserHandle.isIsolated(uid)) {
2271 return PackageManager.PERMISSION_DENIED;
2273 // If there is a uid that owns whatever is being accessed, it has
2274 // blanket access to it regardless of the permissions it requires.
2275 if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2276 return PackageManager.PERMISSION_GRANTED;
2278 // If the target is not exported, then nobody else can get to it.
2281 RuntimeException here = new RuntimeException("here");
2282 here.fillInStackTrace();
2283 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
2286 return PackageManager.PERMISSION_DENIED;
2288 if (permission == null) {
2289 return PackageManager.PERMISSION_GRANTED;
2292 return AppGlobals.getPackageManager()
2293 .checkUidPermission(permission, uid);
2294 } catch (RemoteException e) {
2295 // Should never happen, but if it does... deny!
2296 Slog.e(TAG, "PackageManager is dead?!?", e);
2298 return PackageManager.PERMISSION_DENIED;
2302 public static int checkUidPermission(String permission, int uid) {
2304 return AppGlobals.getPackageManager()
2305 .checkUidPermission(permission, uid);
2306 } catch (RemoteException e) {
2307 // Should never happen, but if it does... deny!
2308 Slog.e(TAG, "PackageManager is dead?!?", e);
2310 return PackageManager.PERMISSION_DENIED;
2315 * Helper for dealing with incoming user arguments to system service calls.
2316 * Takes care of checking permissions and converting USER_CURRENT to the
2317 * actual current user.
2319 * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2320 * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2321 * @param userId The user id argument supplied by the caller -- this is the user
2322 * they want to run as.
2323 * @param allowAll If true, we will allow USER_ALL. This means you must be prepared
2324 * to get a USER_ALL returned and deal with it correctly. If false,
2325 * an exception will be thrown if USER_ALL is supplied.
2326 * @param requireFull If true, the caller must hold
2327 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2328 * different user than their current process; otherwise they must hold
2329 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2330 * @param name Optional textual name of the incoming call; only for generating error messages.
2331 * @param callerPackage Optional package name of caller; only for error messages.
2333 * @return Returns the user ID that the call should run as. Will always be a concrete
2334 * user number, unless <var>allowAll</var> is true in which case it could also be
2337 public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2338 boolean allowAll, boolean requireFull, String name, String callerPackage) {
2339 if (UserHandle.getUserId(callingUid) == userId) {
2343 return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2344 callingUid, userId, allowAll, requireFull, name, callerPackage);
2345 } catch (RemoteException e) {
2346 throw new SecurityException("Failed calling activity manager", e);
2351 public static int getCurrentUser() {
2354 ui = ActivityManagerNative.getDefault().getCurrentUser();
2355 return ui != null ? ui.id : 0;
2356 } catch (RemoteException e) {
2362 * @param userid the user's id. Zero indicates the default user
2365 public boolean switchUser(int userid) {
2367 return ActivityManagerNative.getDefault().switchUser(userid);
2368 } catch (RemoteException e) {
2374 * Return whether the given user is actively running. This means that
2375 * the user is in the "started" state, not "stopped" -- it is currently
2376 * allowed to run code through scheduled alarms, receiving broadcasts,
2377 * etc. A started user may be either the current foreground user or a
2378 * background user; the result here does not distinguish between the two.
2379 * @param userid the user's id. Zero indicates the default user.
2382 public boolean isUserRunning(int userid) {
2384 return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2385 } catch (RemoteException e) {
2391 * Perform a system dump of various state associated with the given application
2392 * package name. This call blocks while the dump is being performed, so should
2393 * not be done on a UI thread. The data will be written to the given file
2394 * descriptor as text. An application must hold the
2395 * {@link android.Manifest.permission#DUMP} permission to make this call.
2396 * @param fd The file descriptor that the dump should be written to. The file
2397 * descriptor is <em>not</em> closed by this function; the caller continues to
2399 * @param packageName The name of the package that is to be dumped.
2401 public void dumpPackageState(FileDescriptor fd, String packageName) {
2402 dumpPackageStateStatic(fd, packageName);
2408 public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2409 FileOutputStream fout = new FileOutputStream(fd);
2410 PrintWriter pw = new FastPrintWriter(fout);
2411 dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
2412 "-a", "package", packageName });
2414 dumpService(pw, fd, "meminfo", new String[] { "--local", packageName });
2416 dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { "-a", packageName });
2418 dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
2420 dumpService(pw, fd, "package", new String[] { packageName });
2422 dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
2426 private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2427 pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2428 IBinder service = ServiceManager.checkService(name);
2429 if (service == null) {
2430 pw.println(" (Service not found)");
2433 TransferPipe tp = null;
2436 tp = new TransferPipe();
2437 tp.setBufferPrefix(" ");
2438 service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
2440 } catch (Throwable e) {
2444 pw.println("Failure dumping service:");
2445 e.printStackTrace(pw);
2452 public void startLockTaskMode(int taskId) {
2454 ActivityManagerNative.getDefault().startLockTaskMode(taskId);
2455 } catch (RemoteException e) {
2462 public void stopLockTaskMode() {
2464 ActivityManagerNative.getDefault().stopLockTaskMode();
2465 } catch (RemoteException e) {
2470 * Return whether currently in lock task mode. When in this mode
2471 * no new tasks can be created or switched to.
2473 * @see Activity#startLockTask()
2475 public boolean isInLockTaskMode() {
2477 return ActivityManagerNative.getDefault().isInLockTaskMode();
2478 } catch (RemoteException e) {
2484 * The AppTask allows you to manage your own application's tasks.
2485 * See {@link android.app.ActivityManager#getAppTasks()}
2487 public static class AppTask {
2488 private IAppTask mAppTaskImpl;
2491 public AppTask(IAppTask task) {
2492 mAppTaskImpl = task;
2496 * Finishes all activities in this task and removes it from the recent tasks list.
2498 public void finishAndRemoveTask() {
2500 mAppTaskImpl.finishAndRemoveTask();
2501 } catch (RemoteException e) {
2502 Slog.e(TAG, "Invalid AppTask", e);
2507 * Get the RecentTaskInfo associated with this task.
2509 * @return The RecentTaskInfo for this task, or null if the task no longer exists.
2511 public RecentTaskInfo getTaskInfo() {
2513 return mAppTaskImpl.getTaskInfo();
2514 } catch (RemoteException e) {
2515 Slog.e(TAG, "Invalid AppTask", e);