Check if Activity is running from Service

前端 未结 8 457
星月不相逢
星月不相逢 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:53

    There is one flaw to most of the answers above, if your activity has some feature which triggers another activity over the top, e.g. sending an email

    enter image description here

    the topActivity will not return your package name but instead the Android activity selector package name.

    Thus, it is better to check for the baseActivity instead of the topActivity.

    public boolean isMainActivityRunning(String packageName) {
        ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);
        List tasksInfo = activityManager.getRunningTasks(Integer.MAX_VALUE); 
    
        for (int i = 0; i < tasksInfo.size(); i++) {
            if (tasksInfo.get(i).baseActivity.getPackageName().toString().equals(packageName)
                return true;
        }
    
        return false;
    } 
    

提交回复
热议问题