Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the current foreground activity in android

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

like image 884
Shabbir Panjesha Avatar asked Nov 15 '11 05:11

Shabbir Panjesha


2 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.

like image 160
brianestey Avatar answered Sep 19 '22 16:09

brianestey


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();
    }
like image 43
Dinesh Prajapati Avatar answered Sep 21 '22 16:09

Dinesh Prajapati