Check if Activity is running from Service

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

    Use the below method to get full class name (package+class name) of the current activity and check if it is equal to full class name (package+class name) of activity you want:

     public String getCurrentClass() {
    
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List runningTaskInfo = manager.getRunningTasks(1);
    
        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
        String className = componentInfo.getClassName();
        return className;
     }
    

提交回复
热议问题