检测当前前景 android 应用程序

Detect current foreground android application

我想编写一个 android 服务,每 5 秒检查一次当前的前台应用程序 运行 例如如果用户当前正在使用 Chrome,它应该给我 Chrome 作为 运行 应用程序。当用户切换到 Google 地图时,它应该在 5 秒后告诉我 Google 地图。

我试过用下面的代码获取当前前台应用

ActivityManager.RunningTaskInfo foregroundTaskInfo = mActivityManager.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();

当有我的服务的应用程序在前台时,代码运行良好,它 returns 我的应用程序的包名称但是当我切换到另一个应用程序时,它给了我 "com.sec.android.app.launcher"

此方法在 Android 5 中已弃用,因此出于安全原因,此方法将 return 如果您的应用程序在前台,但没有其他应用程序,则您的程序包名称。由于您使用的是 Android 6,我猜这种方法是 return 始终使用启动程序包名称来隐藏实际的前台应用程序。

来自documentation

List<ActivityManager.RunningTaskInfo> getRunningTasks (int maxNum)

This method was deprecated in API level 21. As of LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.