3

In MainActivity I want to know the current Top Activity opened inside App.

For pre-lollipop I used following

ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

On other posts I found, I should use:

getAppTasks() and gettaskinfo

But I am not able to find any complete example demonstrating how to use the above. Any help is thankful. Regards.

Edit: Current code:

if (Build.VERSION.SDK_INT >= 23) {
      cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
}else{
      cn = am.getRunningTasks(1).get(0).topActivity;
}

am.getRunningTasks is deprecated in API 21. And am.getAppTasks#topActivity is available in API 23. So updated question is how to handle it for API 21 and 22.

user1590595
  • 795
  • 2
  • 13
  • 37

1 Answers1

6
ActivityManager mgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (mgr != null) {
  List<ActivityManager.AppTask> tasks = mgr.getAppTasks();
  String className;
  if (tasks != null && !tasks.isEmpty()) {
    className = tasks.get(0).getTaskInfo().topActivity.getClassName();
  }
}      

Credits go to https://www.intertech.com/Blog/android-5-api-changes-getapptasks/

David
  • 3,971
  • 1
  • 26
  • 65