androidserviceforeground

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


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


Solution

  • private boolean isServiceRunning(String serviceName){
        boolean serviceRunning = false;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
        Iterator<ActivityManager.RunningServiceInfo> 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.