How to determine if an Android Service is running

2019-01-11 04:11发布

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

3条回答
姐就是有狂的资本
2楼-- · 2019-01-11 04:12
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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-11 04:14
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;
   }
查看更多
贪生不怕死
4楼-- · 2019-01-11 04:23

A more efficient variation of answer: https://stackoverflow.com/a/36127260/1275265

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())) {
         return service.foreground;
      }
   }
   return false;
}
查看更多
登录 后发表回答