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

user811985 picture user811985 · Jun 23, 2011 · Viewed 22k times · Source

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

Answer

georgeok picture georgeok · Mar 21, 2016
public static boolean isServiceRunningInForeground(Context context, Class<?> serviceClass) {
      ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
         if (serviceClass.getName().equals(service.service.getClassName())) {
            if (service.foreground) {
               return true;
            }

         }
      }
      return false;
   }