Launch most recent app

411 views Asked by At

I'm working on a productivity app and I would like to be able to launch the users most recent app when a gesture is detected, however, I can't figure out why this code below isn't launching my most recent app.

ActivityManager m = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
RecentTaskInfo task = m.getRecentTasks(1, 0).get(0);
startActivity(task.baseIntent);

I also have this permission in my manifest

android.permission.GET_TASKS

Thank you for any help as to why this isn't working

2

There are 2 answers

0
Vikram On BEST ANSWER
RecentTaskInfo task = m.getRecentTasks(1, 0).get(0);

Since you are setting max number of results to 1, you are getting your own task with get(0). To get the result you are looking for, try setting the max # of results to 2 and use the second task from the returned list:

ActivityManager m = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
RecentTaskInfo task = m.getRecentTasks(2, 0).get(1);
startActivity(task.baseIntent);
0
herbertD On

Below code works for me to get recent 30 apps:

    private static final int MAX_TASKS = 30;

    final ActivityManager am = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);


    final List<ActivityManager.RecentTaskInfo> recentTasks =
                am.getRecentTasks(MAX_TASKS,                   ActivityManager.RECENT_IGNORE_UNAVAILABLE);