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

后端 未结 6 939
眼角桃花
眼角桃花 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:09

    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;
    }
    

提交回复
热议问题