Check if Activity is running from Service

前端 未结 8 459
星月不相逢
星月不相逢 2020-12-02 22:29

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

8条回答
  •  醉话见心
    2020-12-02 22:59

    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 runningTaskInfo = manager.getRunningTasks(1); 
        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        return componentInfo.getPackageName().equals(myPackage);
    }
    

    Update:

    Add Permission:

    
    

提交回复
热议问题