检查活动从服务运行

2023-09-12 04:26:44 作者:为了孩子他娘奋斗

如何才能服务检查,如果它的一个应用程序的活动在前台运行?

How can a Service check if one of it's application's Activity is running in foreground?

推荐答案

使用下面的方法与你的包名。这将返回true,如果你的任何活动是在前台。

Use the below method with your package name. It will return true if any of your activities is in foreground.

public boolean isForeground(String myPackage) {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1); 
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(myPackage);
}

更新:

添加权限:

Update:

Add Permission:

<uses-permission android:name="android.permission.GET_TASKS" />
相关推荐