Home » Android » How to find the current foreground activity in android

How to find the current foreground activity in android

Posted by: admin June 15, 2020 Leave a comment

Questions:

Is it possible to find the current foreground activity in android.I am not using ActivityGroup.

How to&Answers:

My guess is that it you need to look at the ActivityManager class. I took a brief look at the docs and this is what I came up with.

There’s a function:

public List<ActivityManager.RunningTaskInfo> getRunningTasks (int maxNum)

From the Android docs:

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.

My thought would be if you pass in maxNum=1, it should give you the most recent task that was run, ie. the top task. Each ActivityManager.RunningTaskInfo has a property called topActivity.

public ComponentName topActivity 

From the Android docs: The activity component at the top of the history stack of the task. This is what the user is currently doing.

Answer:

try below code : you need to give proper permission

private String getCurrentTopActivity() {

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
        return ar.topActivity.getClassName().toString();
    }