FileDocCategorySizeDatePackage
ActivityManager.javaAPI DocAndroid 5.1 API100615Thu Mar 12 22:22:08 GMT 2015android.app

ActivityManager

public class ActivityManager extends Object
Interact with the overall activities running in the system.

Fields Summary
private static String
TAG
private static boolean
localLOGV
private static int
gMaxRecentTasks
private final android.content.Context
mContext
private final android.os.Handler
mHandler
public static final String
META_HOME_ALTERNATE
{@code <meta-data>} name for a 'home' Activity that declares a package that is to be uninstalled in lieu of the declaring one. The package named here must be signed with the same certificate as the one declaring the {@code <meta-data>}.
public static final int
START_NOT_VOICE_COMPATIBLE
Result for IActivityManager.startActivity: trying to start an activity under voice control when that activity does not support the VOICE category.
public static final int
START_CANCELED
Result for IActivityManager.startActivity: an error where the start had to be canceled.
public static final int
START_NOT_ACTIVITY
Result for IActivityManager.startActivity: an error where the thing being started is not an activity.
public static final int
START_PERMISSION_DENIED
Result for IActivityManager.startActivity: an error where the caller does not have permission to start the activity.
public static final int
START_FORWARD_AND_REQUEST_CONFLICT
Result for IActivityManager.startActivity: an error where the caller has requested both to forward a result and to receive a result.
public static final int
START_CLASS_NOT_FOUND
Result for IActivityManager.startActivity: an error where the requested class is not found.
public static final int
START_INTENT_NOT_RESOLVED
Result for IActivityManager.startActivity: an error where the given Intent could not be resolved to an activity.
public static final int
START_SUCCESS
Result for IActivityManaqer.startActivity: the activity was started successfully as normal.
public static final int
START_RETURN_INTENT_TO_CALLER
Result for IActivityManaqer.startActivity: the caller asked that the Intent not be executed if it is the recipient, and that is indeed the case.
public static final int
START_TASK_TO_FRONT
Result for IActivityManaqer.startActivity: activity wasn't really started, but a task was simply brought to the foreground.
public static final int
START_DELIVERED_TO_TOP
Result for IActivityManaqer.startActivity: activity wasn't really started, but the given Intent was given to the existing top activity.
public static final int
START_SWITCHES_CANCELED
Result for IActivityManaqer.startActivity: request was canceled because app switches are temporarily canceled to ensure the user's last request (such as pressing home) is performed.
public static final int
START_RETURN_LOCK_TASK_MODE_VIOLATION
Result for IActivityManaqer.startActivity: a new activity was attempted to be started while in Lock Task Mode.
public static final int
START_FLAG_ONLY_IF_NEEDED
Flag for IActivityManaqer.startActivity: do special start mode where a new activity is launched only if it is needed.
public static final int
START_FLAG_DEBUG
Flag for IActivityManaqer.startActivity: launch the app for debugging.
public static final int
START_FLAG_OPENGL_TRACES
Flag for IActivityManaqer.startActivity: launch the app for OpenGL tracing.
public static final int
BROADCAST_SUCCESS
Result for IActivityManaqer.broadcastIntent: success!
public static final int
BROADCAST_STICKY_CANT_HAVE_PERMISSION
Result for IActivityManaqer.broadcastIntent: attempt to broadcast a sticky intent without appropriate permission.
public static final int
BROADCAST_FAILED_USER_STOPPED
Result for IActivityManager.broadcastIntent: trying to send a broadcast to a stopped user. Fail.
public static final int
INTENT_SENDER_BROADCAST
Type for IActivityManaqer.getIntentSender: this PendingIntent is for a sendBroadcast operation.
public static final int
INTENT_SENDER_ACTIVITY
Type for IActivityManaqer.getIntentSender: this PendingIntent is for a startActivity operation.
public static final int
INTENT_SENDER_ACTIVITY_RESULT
Type for IActivityManaqer.getIntentSender: this PendingIntent is for an activity result operation.
public static final int
INTENT_SENDER_SERVICE
Type for IActivityManaqer.getIntentSender: this PendingIntent is for a startService operation.
public static final int
USER_OP_SUCCESS
public static final int
USER_OP_UNKNOWN_USER
public static final int
USER_OP_IS_CURRENT
public static final int
PROCESS_STATE_PERSISTENT
public static final int
PROCESS_STATE_PERSISTENT_UI
public static final int
PROCESS_STATE_TOP
public static final int
PROCESS_STATE_IMPORTANT_FOREGROUND
public static final int
PROCESS_STATE_IMPORTANT_BACKGROUND
public static final int
PROCESS_STATE_BACKUP
public static final int
PROCESS_STATE_HEAVY_WEIGHT
public static final int
PROCESS_STATE_SERVICE
public static final int
PROCESS_STATE_RECEIVER
public static final int
PROCESS_STATE_HOME
public static final int
PROCESS_STATE_LAST_ACTIVITY
public static final int
PROCESS_STATE_CACHED_ACTIVITY
public static final int
PROCESS_STATE_CACHED_ACTIVITY_CLIENT
public static final int
PROCESS_STATE_CACHED_EMPTY
android.graphics.Point
mAppTaskThumbnailSize
public static final int
COMPAT_MODE_ALWAYS
Screen compatibility mode: the application most always run in compatibility mode.
public static final int
COMPAT_MODE_NEVER
Screen compatibility mode: the application can never run in compatibility mode.
public static final int
COMPAT_MODE_UNKNOWN
Screen compatibility mode: unknown.
public static final int
COMPAT_MODE_DISABLED
Screen compatibility mode: the application currently has compatibility mode disabled.
public static final int
COMPAT_MODE_ENABLED
Screen compatibility mode: the application currently has compatibility mode enabled.
public static final int
COMPAT_MODE_TOGGLE
Screen compatibility mode: request to toggle the application's compatibility mode.
public static final int
RECENT_WITH_EXCLUDED
Flag for use with {@link #getRecentTasks}: return all tasks, even those that have set their {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
public static final int
RECENT_IGNORE_UNAVAILABLE
Provides a list that does not contain any recent tasks that currently are not available to the user.
public static final int
RECENT_INCLUDE_PROFILES
Provides a list that contains recent tasks for all profiles of a user.
public static final int
RECENT_IGNORE_HOME_STACK_TASKS
Ignores all tasks that are on the home stack.
public static final int
MOVE_TASK_WITH_HOME
Flag for {@link #moveTaskToFront(int, int)}: also move the "home" activity along with the task, so it is positioned immediately behind the task.
public static final int
MOVE_TASK_NO_USER_ACTION
Flag for {@link #moveTaskToFront(int, int)}: don't count this as a user-instigated action, so the current activity will not receive a hint that the user is leaving.
Constructors Summary
ActivityManager(android.content.Context context, android.os.Handler handler)


    /*package*/     
        mContext = context;
        mHandler = handler;
    
Methods Summary
public intaddAppTask(Activity activity, android.content.Intent intent, android.app.ActivityManager$TaskDescription description, android.graphics.Bitmap thumbnail)
Add a new {@link AppTask} for the calling application. This will create a new recents entry that is added to the end of all existing recents.

param
activity The activity that is adding the entry. This is used to help determine the context that the new recents entry will be in.
param
intent The Intent that describes the recents entry. This is the same Intent that you would have used to launch the activity for it. In generally you will want to set both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents entry will exist without an activity, so it doesn't make sense to not retain it when its activity disappears. The given Intent here also must have an explicit ComponentName set on it.
param
description Optional additional description information.
param
thumbnail Thumbnail to use for the recents entry. Should be the size given by {@link #getAppTaskThumbnailSize()}. If the bitmap is not that exact size, it will be recreated in your process, probably in a way you don't like, before the recents entry is added.
return
Returns the task id of the newly added app task, or -1 if the add failed. The most likely cause of failure is that there is no more room for more tasks for your app.

        Point size;
        synchronized (this) {
            ensureAppTaskThumbnailSizeLocked();
            size = mAppTaskThumbnailSize;
        }
        final int tw = thumbnail.getWidth();
        final int th = thumbnail.getHeight();
        if (tw != size.x || th != size.y) {
            Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());

            // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
            float scale;
            float dx = 0, dy = 0;
            if (tw * size.x > size.y * th) {
                scale = (float) size.x / (float) th;
                dx = (size.y - tw * scale) * 0.5f;
            } else {
                scale = (float) size.y / (float) tw;
                dy = (size.x - th * scale) * 0.5f;
            }
            Matrix matrix = new Matrix();
            matrix.setScale(scale, scale);
            matrix.postTranslate((int) (dx + 0.5f), 0);

            Canvas canvas = new Canvas(bm);
            canvas.drawBitmap(thumbnail, matrix, null);
            canvas.setBitmap(null);

            thumbnail = bm;
        }
        if (description == null) {
            description = new TaskDescription();
        }
        try {
            return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(),
                    intent, description, thumbnail);
        } catch (RemoteException e) {
            throw new IllegalStateException("System dead?", e);
        }
    
public static intcheckComponentPermission(java.lang.String permission, int uid, int owningUid, boolean exported)

hide

        // Root, system server get to do everything.
        if (uid == 0 || uid == Process.SYSTEM_UID) {
            return PackageManager.PERMISSION_GRANTED;
        }
        // Isolated processes don't get any permissions.
        if (UserHandle.isIsolated(uid)) {
            return PackageManager.PERMISSION_DENIED;
        }
        // If there is a uid that owns whatever is being accessed, it has
        // blanket access to it regardless of the permissions it requires.
        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
            return PackageManager.PERMISSION_GRANTED;
        }
        // If the target is not exported, then nobody else can get to it.
        if (!exported) {
            /*
            RuntimeException here = new RuntimeException("here");
            here.fillInStackTrace();
            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
                    here);
            */
            return PackageManager.PERMISSION_DENIED;
        }
        if (permission == null) {
            return PackageManager.PERMISSION_GRANTED;
        }
        try {
            return AppGlobals.getPackageManager()
                    .checkUidPermission(permission, uid);
        } catch (RemoteException e) {
            // Should never happen, but if it does... deny!
            Slog.e(TAG, "PackageManager is dead?!?", e);
        }
        return PackageManager.PERMISSION_DENIED;
    
public static intcheckUidPermission(java.lang.String permission, int uid)

hide

        try {
            return AppGlobals.getPackageManager()
                    .checkUidPermission(permission, uid);
        } catch (RemoteException e) {
            // Should never happen, but if it does... deny!
            Slog.e(TAG, "PackageManager is dead?!?", e);
        }
        return PackageManager.PERMISSION_DENIED;
    
public booleanclearApplicationUserData(java.lang.String packageName, android.content.pm.IPackageDataObserver observer)

hide

        try {
            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName, 
                    observer, UserHandle.myUserId());
        } catch (RemoteException e) {
            return false;
        }
    
public booleanclearApplicationUserData()
Permits an application to erase its own data from disk. This is equivalent to the user choosing to clear the app's data from within the device settings UI. It erases all dynamic data associated with the app -- its private data and data in its private area on external storage -- but does not remove the installed application itself, nor any OBB files.

return
{@code true} if the application successfully requested that the application's data be erased; {@code false} otherwise.

        return clearApplicationUserData(mContext.getPackageName(), null);
    
public voiddumpPackageState(java.io.FileDescriptor fd, java.lang.String packageName)
Perform a system dump of various state associated with the given application package name. This call blocks while the dump is being performed, so should not be done on a UI thread. The data will be written to the given file descriptor as text. An application must hold the {@link android.Manifest.permission#DUMP} permission to make this call.

param
fd The file descriptor that the dump should be written to. The file descriptor is not closed by this function; the caller continues to own it.
param
packageName The name of the package that is to be dumped.

        dumpPackageStateStatic(fd, packageName);
    
public static voiddumpPackageStateStatic(java.io.FileDescriptor fd, java.lang.String packageName)

hide

        FileOutputStream fout = new FileOutputStream(fd);
        PrintWriter pw = new FastPrintWriter(fout);
        dumpService(pw, fd, "package", new String[] { packageName });
        pw.println();
        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
                "-a", "package", packageName });
        pw.println();
        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
        pw.println();
        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
        pw.println();
        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
        pw.println();
        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
        pw.flush();
    
private static voiddumpService(java.io.PrintWriter pw, java.io.FileDescriptor fd, java.lang.String name, java.lang.String[] args)

        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
        IBinder service = ServiceManager.checkService(name);
        if (service == null) {
            pw.println("  (Service not found)");
            return;
        }
        TransferPipe tp = null;
        try {
            pw.flush();
            tp = new TransferPipe();
            tp.setBufferPrefix("  ");
            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
            tp.go(fd, 10000);
        } catch (Throwable e) {
            if (tp != null) {
                tp.kill();
            }
            pw.println("Failure dumping service:");
            e.printStackTrace(pw);
        }
    
private voidensureAppTaskThumbnailSizeLocked()

        if (mAppTaskThumbnailSize == null) {
            try {
                mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize();
            } catch (RemoteException e) {
                throw new IllegalStateException("System dead?", e);
            }
        }
    
public voidforceStopPackage(java.lang.String packageName)

see
#forceStopPackageAsUser(String, int)
hide

        forceStopPackageAsUser(packageName, UserHandle.myUserId());
    
public voidforceStopPackageAsUser(java.lang.String packageName, int userId)
Have the system perform a force stop of everything associated with the given application package. All processes that share its uid will be killed, all services it has running stopped, all activities removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED} broadcast will be sent, so that any of its registered alarms can be stopped, notifications removed, etc.

You must hold the permission {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to call this method.

param
packageName The name of the package to be stopped.
param
userId The user for which the running package is to be stopped.
hide
This is not available to third party applications due to it allowing them to break other applications by stopping their services, removing their alarms, etc.

        try {
            ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
        } catch (RemoteException e) {
        }
    
public android.util.SizegetAppTaskThumbnailSize()
Return the current design dimensions for {@link AppTask} thumbnails, for use with {@link #addAppTask}.

        synchronized (this) {
            ensureAppTaskThumbnailSizeLocked();
            return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
        }
    
public java.util.ListgetAppTasks()
Get the list of tasks associated with the calling application.

return
The list of tasks associated with the application making this call.
throws
SecurityException

        ArrayList<AppTask> tasks = new ArrayList<AppTask>();
        List<IAppTask> appTasks;
        try {
            appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName());
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
        int numAppTasks = appTasks.size();
        for (int i = 0; i < numAppTasks; i++) {
            tasks.add(new AppTask(appTasks.get(i)));
        }
        return tasks;
    
public static intgetCurrentUser()
Gets the userId of the current foreground user. Requires system permissions.

hide

        UserInfo ui;
        try {
            ui = ActivityManagerNative.getDefault().getCurrentUser();
            return ui != null ? ui.id : 0;
        } catch (RemoteException e) {
            return 0;
        }
    
public static intgetDefaultAppRecentsLimitStatic()
Return the default limit on the number of recents that an app can make.

hide

        return getMaxRecentTasksStatic() / 6;
    
public android.content.pm.ConfigurationInfogetDeviceConfigurationInfo()
Get the device configuration attributes.

        try {
            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
        } catch (RemoteException e) {
        }
        return null;
    
public intgetFrontActivityScreenCompatMode()

hide


      
       
        try {
            return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return 0;
        }
    
public intgetLargeMemoryClass()
Return the approximate per-application memory class of the current device when an application is running with a large heap. This is the space available for memory-intensive applications; most applications should not need this amount of memory, and should instead stay with the {@link #getMemoryClass()} limit. The returned value is in megabytes. This may be the same size as {@link #getMemoryClass()} on memory constrained devices, or it may be significantly larger on devices with a large amount of available RAM.

The is the size of the application's Dalvik heap if it has specified android:largeHeap="true" in its manifest.

        return staticGetLargeMemoryClass();
    
public intgetLauncherLargeIconDensity()
Get the preferred density of icons for the launcher. This is used when custom drawables are created (e.g., for shortcuts).

return
density in terms of DPI

        final Resources res = mContext.getResources();
        final int density = res.getDisplayMetrics().densityDpi;
        final int sw = res.getConfiguration().smallestScreenWidthDp;

        if (sw < 600) {
            // Smaller than approx 7" tablets, use the regular icon size.
            return density;
        }

        switch (density) {
            case DisplayMetrics.DENSITY_LOW:
                return DisplayMetrics.DENSITY_MEDIUM;
            case DisplayMetrics.DENSITY_MEDIUM:
                return DisplayMetrics.DENSITY_HIGH;
            case DisplayMetrics.DENSITY_TV:
                return DisplayMetrics.DENSITY_XHIGH;
            case DisplayMetrics.DENSITY_HIGH:
                return DisplayMetrics.DENSITY_XHIGH;
            case DisplayMetrics.DENSITY_XHIGH:
                return DisplayMetrics.DENSITY_XXHIGH;
            case DisplayMetrics.DENSITY_XXHIGH:
                return DisplayMetrics.DENSITY_XHIGH * 2;
            default:
                // The density is some abnormal value.  Return some other
                // abnormal value that is a reasonable scaling of it.
                return (int)((density*1.5f)+.5f);
        }
    
public intgetLauncherLargeIconSize()
Get the preferred launcher icon size. This is used when custom drawables are created (e.g., for shortcuts).

return
dimensions of square icons in terms of pixels

        return getLauncherLargeIconSizeInner(mContext);
    
static intgetLauncherLargeIconSizeInner(android.content.Context context)

        final Resources res = context.getResources();
        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
        final int sw = res.getConfiguration().smallestScreenWidthDp;

        if (sw < 600) {
            // Smaller than approx 7" tablets, use the regular icon size.
            return size;
        }

        final int density = res.getDisplayMetrics().densityDpi;

        switch (density) {
            case DisplayMetrics.DENSITY_LOW:
                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
            case DisplayMetrics.DENSITY_MEDIUM:
                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
            case DisplayMetrics.DENSITY_TV:
                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
            case DisplayMetrics.DENSITY_HIGH:
                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
            case DisplayMetrics.DENSITY_XHIGH:
                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
            case DisplayMetrics.DENSITY_XXHIGH:
                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
            default:
                // The density is some abnormal value.  Return some other
                // abnormal value that is a reasonable scaling of it.
                return (int)((size*1.5f) + .5f);
        }
    
public static intgetMaxAppRecentsLimitStatic()
Return the maximum limit on the number of recents that an app can make.

hide

        return getMaxRecentTasksStatic() / 2;
    
public static intgetMaxRecentTasksStatic()
Return the maximum number of recents entries that we will maintain and show.

hide

        if (gMaxRecentTasks < 0) {
            return gMaxRecentTasks = isLowRamDeviceStatic() ? 50 : 100;
        }
        return gMaxRecentTasks;
    
public intgetMemoryClass()
Return the approximate per-application memory class of the current device. This gives you an idea of how hard a memory limit you should impose on your application to let the overall system work best. The returned value is in megabytes; the baseline Android memory class is 16 (which happens to be the Java heap limit of those devices); some device with more memory may return 24 or even higher numbers.

        return staticGetMemoryClass();
    
public voidgetMemoryInfo(android.app.ActivityManager$MemoryInfo outInfo)
Return general information about the memory state of the system. This can be used to help decide how to manage your own memory, though note that polling is not recommended and {@link android.content.ComponentCallbacks2#onTrimMemory(int) ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this. Also see {@link #getMyMemoryState} for how to retrieve the current trim level of your process as needed, which gives a better hint for how to manage its memory.

        try {
            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
        } catch (RemoteException e) {
        }
    
public static voidgetMyMemoryState(android.app.ActivityManager$RunningAppProcessInfo outState)
Return global memory state information for the calling process. This does not fill in all fields of the {@link RunningAppProcessInfo}. The only fields that will be filled in are {@link RunningAppProcessInfo#pid}, {@link RunningAppProcessInfo#uid}, {@link RunningAppProcessInfo#lastTrimLevel}, {@link RunningAppProcessInfo#importance}, {@link RunningAppProcessInfo#lru}, and {@link RunningAppProcessInfo#importanceReasonCode}.

        try {
            ActivityManagerNative.getDefault().getMyMemoryState(outState);
        } catch (RemoteException e) {
        }
    
public booleangetPackageAskScreenCompat(java.lang.String packageName)

hide

        try {
            return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return false;
        }
    
public intgetPackageScreenCompatMode(java.lang.String packageName)

hide

        try {
            return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return 0;
        }
    
public Debug.MemoryInfo[]getProcessMemoryInfo(int[] pids)
Return information about the memory usage of one or more processes.

Note: this method is only intended for debugging or building a user-facing process management UI.

param
pids The pids of the processes whose memory usage is to be retrieved.
return
Returns an array of memory information, one for each requested pid.

        try {
            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
        } catch (RemoteException e) {
            return null;
        }
    
public java.util.ListgetProcessesInErrorState()
Returns a list of any processes that are currently in an error condition. The result will be null if all processes are running properly at this time.

return
Returns a list of ProcessErrorStateInfo records, or null if there are no current error conditions (it will not return an empty list). This list ordering is not specified.

        try {
            return ActivityManagerNative.getDefault().getProcessesInErrorState();
        } catch (RemoteException e) {
            return null;
        }
    
public java.util.ListgetRecentTasks(int maxNum, int flags)

Return a list of the tasks that the user has recently launched, with the most recent being first and older ones after in order.

Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here. Such uses are not supported, and will likely break in the future. For example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.

deprecated
As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak personal information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks (though see {@link #getAppTasks()} for the correct supported way to retrieve that information), and possibly some other tasks such as home that are known to not be sensitive.
param
maxNum The maximum number of entries to return in the list. The actual number returned may be smaller, depending on how many tasks the user has started and the maximum number the system can remember.
param
flags Information about what to return. May be any combination of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
return
Returns a list of RecentTaskInfo records describing each of the recent tasks.


                                                                                                                                                                                                                                                                     
    
         
              
        try {
            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
                    flags, UserHandle.myUserId());
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
    
public java.util.ListgetRecentTasksForUser(int maxNum, int flags, int userId)
Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a specific user. It requires holding the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.

param
maxNum The maximum number of entries to return in the list. The actual number returned may be smaller, depending on how many tasks the user has started and the maximum number the system can remember.
param
flags Information about what to return. May be any combination of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
return
Returns a list of RecentTaskInfo records describing each of the recent tasks.
hide

        try {
            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
                    flags, userId);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
    
public java.util.ListgetRunningAppProcesses()
Returns a list of application processes that are running on the device.

Note: this method is only intended for debugging or building a user-facing process management UI.

return
Returns a list of RunningAppProcessInfo records, or null if there are no running processes (it will not return an empty list). This list ordering is not specified.

        try {
            return ActivityManagerNative.getDefault().getRunningAppProcesses();
        } catch (RemoteException e) {
            return null;
        }
    
public java.util.ListgetRunningExternalApplications()
Returns a list of application processes installed on external media that are running on the device.

Note: this method is only intended for debugging or building a user-facing process management UI.

return
Returns a list of ApplicationInfo records, or null if none This list ordering is not specified.
hide

        try {
            return ActivityManagerNative.getDefault().getRunningExternalApplications();
        } catch (RemoteException e) {
            return null;
        }
    
public PendingIntentgetRunningServiceControlPanel(android.content.ComponentName service)
Returns a PendingIntent you can start to show a control panel for the given running service. If the service does not have a control panel, null is returned.

        try {
            return ActivityManagerNative.getDefault()
                    .getRunningServiceControlPanel(service);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
    
public java.util.ListgetRunningServices(int maxNum)
Return a list of the services that are currently running.

Note: this method is only intended for debugging or implementing service management type user interfaces.

param
maxNum The maximum number of entries to return in the list. The actual number returned may be smaller, depending on how many services are running.
return
Returns a list of RunningServiceInfo records describing each of the running tasks.

        try {
            return ActivityManagerNative.getDefault()
                    .getServices(maxNum, 0);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
    
public java.util.ListgetRunningTasks(int maxNum)
Return a list of the tasks that are currently running, with the most recent being first and older ones after in order. Note that "running" does not mean any of the task's code is currently loaded or activity -- the task may have been frozen by the system, so that it can be restarted in its previous state when next brought to the foreground.

Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here. Such uses are not supported, and will likely break in the future. For example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.

deprecated
As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still retu rn a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.
param
maxNum The maximum number of entries to return in the list. The actual number returned may be smaller, depending on how many tasks the user has started.
return
Returns a list of RunningTaskInfo records describing each of the running tasks.

        try {
            return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
    
public android.app.ActivityManager$TaskThumbnailgetTaskThumbnail(int id)

hide

        try {
            return ActivityManagerNative.getDefault().getTaskThumbnail(id);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return null;
        }
    
public static inthandleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, java.lang.String name, java.lang.String callerPackage)

hide
Helper for dealing with incoming user arguments to system service calls. Takes care of checking permissions and converting USER_CURRENT to the actual current user.
param
callingPid The pid of the incoming call, as per Binder.getCallingPid().
param
callingUid The uid of the incoming call, as per Binder.getCallingUid().
param
userId The user id argument supplied by the caller -- this is the user they want to run as.
param
allowAll If true, we will allow USER_ALL. This means you must be prepared to get a USER_ALL returned and deal with it correctly. If false, an exception will be thrown if USER_ALL is supplied.
param
requireFull If true, the caller must hold {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a different user than their current process; otherwise they must hold {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
param
name Optional textual name of the incoming call; only for generating error messages.
param
callerPackage Optional package name of caller; only for error messages.
return
Returns the user ID that the call should run as. Will always be a concrete user number, unless allowAll is true in which case it could also be USER_ALL.

        if (UserHandle.getUserId(callingUid) == userId) {
            return userId;
        }
        try {
            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
                    callingUid, userId, allowAll, requireFull, name, callerPackage);
        } catch (RemoteException e) {
            throw new SecurityException("Failed calling activity manager", e);
        }
    
public static booleanisHighEndGfx()
Used by persistent processes to determine if they are running on a higher-end device so should be okay using hardware drawing acceleration (which tends to consume a lot more RAM).

hide

        return !isLowRamDeviceStatic() &&
                !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
    
public booleanisInHomeStack(int taskId)

hide

        try {
            return ActivityManagerNative.getDefault().isInHomeStack(taskId);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return false;
        }
    
public booleanisInLockTaskMode()
Return whether currently in lock task mode. When in this mode no new tasks can be created or switched to.

see
Activity#startLockTask()

        try {
            return ActivityManagerNative.getDefault().isInLockTaskMode();
        } catch (RemoteException e) {
            return false;
        }
    
public booleanisLowRamDevice()
Returns true if this is a low-RAM device. Exactly whether a device is low-RAM is ultimately up to the device configuration, but currently it generally means something in the class of a 512MB device with about a 800x480 or less screen. This is mostly intended to be used by apps to determine whether they should turn off certain features that require more RAM.

        return isLowRamDeviceStatic();
    
public static booleanisLowRamDeviceStatic()

hide

        return "true".equals(SystemProperties.get("ro.config.low_ram", "false"));
    
public static booleanisRunningInTestHarness()
Returns "true" if device is running in a test harness.

        return SystemProperties.getBoolean("ro.test_harness", false);
    
public static booleanisUserAMonkey()
Returns "true" if the user interface is currently being messed with by a monkey.

        try {
            return ActivityManagerNative.getDefault().isUserAMonkey();
        } catch (RemoteException e) {
        }
        return false;
    
public booleanisUserRunning(int userid)
Return whether the given user is actively running. This means that the user is in the "started" state, not "stopped" -- it is currently allowed to run code through scheduled alarms, receiving broadcasts, etc. A started user may be either the current foreground user or a background user; the result here does not distinguish between the two.

param
userid the user's id. Zero indicates the default user.
hide

        try {
            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
        } catch (RemoteException e) {
            return false;
        }
    
public voidkillBackgroundProcesses(java.lang.String packageName)
Have the system immediately kill all background processes associated with the given package. This is the same as the kernel killing those processes to reclaim memory; the system will take care of restarting these processes in the future as needed.

You must hold the permission {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to call this method.

param
packageName The name of the package whose processes are to be killed.

        try {
            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
                    UserHandle.myUserId());
        } catch (RemoteException e) {
        }
    
public voidmoveTaskToFront(int taskId, int flags)
Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)} with a null options argument.

param
taskId The identifier of the task to be moved, as found in {@link RunningTaskInfo} or {@link RecentTaskInfo}.
param
flags Additional operational flags, 0 or more of {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.


                                                    
          
        moveTaskToFront(taskId, flags, null);
    
public voidmoveTaskToFront(int taskId, int flags, android.os.Bundle options)
Ask that the task associated with a given task ID be moved to the front of the stack, so it is now visible to the user. Requires that the caller hold permission {@link android.Manifest.permission#REORDER_TASKS} or a SecurityException will be thrown.

param
taskId The identifier of the task to be moved, as found in {@link RunningTaskInfo} or {@link RecentTaskInfo}.
param
flags Additional operational flags, 0 or more of {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
param
options Additional options for the operation, either null or as per {@link Context#startActivity(Intent, android.os.Bundle) Context.startActivity(Intent, Bundle)}.

        try {
            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
        }
    
public booleanremoveTask(int taskId)
Completely remove the given task.

param
taskId Identifier of the task to be removed.
return
Returns true if the given task was found and removed.
hide

        try {
            return ActivityManagerNative.getDefault().removeTask(taskId);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
            return false;
        }
    
public voidrestartPackage(java.lang.String packageName)

deprecated
This is now just a wrapper for {@link #killBackgroundProcesses(String)}; the previous behavior here is no longer available to applications because it allows them to break other applications by removing their alarms, stopping their services, etc.

        killBackgroundProcesses(packageName);
    
public voidsetFrontActivityScreenCompatMode(int mode)

hide

        try {
            ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
        }
    
public voidsetPackageAskScreenCompat(java.lang.String packageName, boolean ask)

hide

        try {
            ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
        }
    
public voidsetPackageScreenCompatMode(java.lang.String packageName, int mode)

hide

        try {
            ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
        } catch (RemoteException e) {
            // System dead, we will be dead too soon!
        }
    
public voidstartLockTaskMode(int taskId)

hide

        try {
            ActivityManagerNative.getDefault().startLockTaskMode(taskId);
        } catch (RemoteException e) {
        }
    
public static intstaticGetLargeMemoryClass()

hide

        // Really brain dead right now -- just take this from the configured
        // vm heap size, and assume it is in megabytes and thus ends with "m".
        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1));
    
public static intstaticGetMemoryClass()

hide

        // Really brain dead right now -- just take this from the configured
        // vm heap size, and assume it is in megabytes and thus ends with "m".
        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
        }
        return staticGetLargeMemoryClass();
    
public voidstopLockTaskMode()

hide

        try {
            ActivityManagerNative.getDefault().stopLockTaskMode();
        } catch (RemoteException e) {
        }
    
public booleanswitchUser(int userid)

param
userid the user's id. Zero indicates the default user
hide

        try {
            return ActivityManagerNative.getDefault().switchUser(userid);
        } catch (RemoteException e) {
            return false;
        }