Check if Service is running from a Broadcast Recei

2019-02-16 23:10发布

问题:

I'll like to ask if it's possible to check a service is running from Broadcast receiver.

I know that it's possible in Activity.

Thanks for your precious help

回答1:

yes' it's possible to detect if service is running from anywhere you have available Context object:

private boolean isMyServiceRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
    if (MyService.class.getName().equals(service.service.getClassName())) {
        return true;
    }
}

return false;
}

MyService is your service class.