How to find the current foreground activity in android

前端 未结 2 564
别跟我提以往
别跟我提以往 2020-12-06 12:11

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

相关标签:
2条回答
  • 2020-12-06 12:41

    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.

    0 讨论(0)
  • 2020-12-06 13:00

    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();
        }
    
    0 讨论(0)
提交回复
热议问题