获取当前对用户可见的活动

4

我希望获取正在运行的前台活动。通过使用以下代码,我可以使用活动管理器获取此信息。

activityManager = (ActivityManager) FWCommon.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
runningTaskInfoList = activityManager.getRunningTasks(1);
componentName = runningTaskInfoList.get(0).topActivity;

假设我有两个活动A和B,并且我从两个活动A和B的onResume()方法中调用上述代码。
以下是问题:
1. 当活动A启动时,上述代码将返回topActivity = A。 2. 然后我从活动A移动到B,上述代码将返回topActivity = B。 3. 然后我按“返回”按钮从活动B返回到A,上述代码再次返回topActivity = B而不是A。
谢谢 Dalvin

1
抱歉,我已经放置了自定义类代码,请考虑以下代码以获取前台活动。activityManager =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); runningTaskInfoList = activityManager.getRunningTasks(1); componentName = runningTaskInfoList.get(0).topActivity; - Dalvinder Singh
1个回答

9

尝试使用getRunningAppProcesses()获取RunningAppProcessInfo列表。然后遍历每个RunningAppProcessInfo,并通过以下方式检查它是否在前台:

List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo process : processes)
{
    // Take a look at the IMPORTANCE_VISIBLE property as well in the link provided at the bottom
    if (process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
    {
        // Put code here
    }
}

点击这里这里获取更多信息。


1
有没有办法检查它是否在主屏幕上? - Talha Q

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接