user1590595
user1590595

Reputation: 805

How to get Top Activity name of own App

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.

Upvotes: 4

Views: 5743

Answers (1)

David
David

Reputation: 4817

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/

Upvotes: 7

Related Questions