Check if Activity is running from Service

前端 未结 8 436
星月不相逢
星月不相逢 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 23:01

    I think you can getRunninTasks on Android and check with your packagename if the task is running or not.

    public boolean isServiceRunning() { 
    
    ActivityManager activityManager = (ActivityManager)Monitor.this.getSystemService (Context.ACTIVITY_SERVICE); 
    List services = activityManager.getRunningTasks(Integer.MAX_VALUE); 
    isServiceFound = false; 
    for (int i = 0; i < services.size(); i++) { 
        if (services.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.lyo.AutoMessage/com.lyo.AutoMessage.TextLogList}")) {
            isServiceFound = true;
        }
    } 
    return isServiceFound; 
    } 
    

提交回复
热议问题