Remove app from recent apps programmatically

I know that Activities can be declared in manifest as being excluded from recents with android:excludeFromRecents: http://developer.android.com/guide/topics/manifest/activity-element.html#exclude

However, that's not what I'm looking for, I would like to know if there is a way to remove the app from recent apps programmatically


Solution 1:

Yes, generally when you want to have special properties for an Activity when starting it you supply special flags to the Intent. In this case FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS.

Updated:

If you need to hide the current already running activity, you might be able to use this flag in combination with FLAG_ACTIVITY_CLEAR_TOP which would send the new Intent to the existing Activity. You'll have to think and perhaps experiment with what happens as the user moves around your stack though and whether that will make your app re-appear in the recent apps.

Solution 2:

This can be done using the ActivityManager.AppTask functionality (starting in API 21)

    ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    if(am != null) {
        List<ActivityManager.AppTask> tasks = am.getAppTasks();
        if (tasks != null && tasks.size() > 0) {
            tasks.get(0).setExcludeFromRecents(true);
        }
    }

Solution 3:

Add these lines to the Activity from which you are exiting the application:

@Override
public void finish() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        super.finishAndRemoveTask();
    }
    else {
        super.finish();
    }
}

Solution 4:

Following is the definition of the flag android:excludeFromRecents (which i know you have already seen):

Whether or not the task initiated by this activity should be excluded from the list of recently used applications ("recent apps"). That is, when this activity is the root activity of a new task, this attribute determines whether the task should not appear in the list of recent apps. "true" if the task should be excluded from the list; "false" if it should be included. The default value is "false".

so to remove the app from the list of recent app you can set this flag on the first activity in your application since that activity launches the the task for you application. If you have multiple tasks (unlikely for most apps) in your application then you need o set this flag for root activity of all the task.