How to determine if an Android Service is running in the foreground?

后端 未结 6 937
眼角桃花
眼角桃花 2020-11-29 04:31

I have a service which I believe to have running in the foreground, How do I check if my implementation is working?

6条回答
  •  难免孤独
    2020-11-29 05:19

    private boolean isServiceRunning(String serviceName){
        boolean serviceRunning = false;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningServices(50);
        Iterator i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningServiceInfo runningServiceInfo = i
                    .next();
    
            if(runningServiceInfo.service.getClassName().equals(serviceName)){
                serviceRunning = true;
    
                if(runningServiceInfo.foreground)
                {
                    //service run in foreground
                }
            }
        }
        return serviceRunning;
    }
    

    If you want to know if your service is running in foreground just open some others fat applications and then check if service is still running or just check flag service.foreground.

提交回复
热议问题