Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Service is running from a Broadcast Receiver

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

like image 438
user3274646 Avatar asked Mar 19 '14 15:03

user3274646


People also ask

How do you check if a service is running or not?

You can do this by making your own Interface where you declare for example " isServiceRunning() ". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.

What is difference between service and broadcast receiver?

A Service receives intents that were sent specifically to your application, just like an Activity. A Broadcast Receiver receives intents that were broadcast system-wide to all apps installed on the device.

Does broadcast receiver run on main thread?

This method is always called within the main thread of its process, unless you explicitly asked for it to be scheduled on a different thread using Context. registerReceiver(BroadcastReceiver, IntentFilter, String, android.

Can broadcast receiver run in background?

The alternative is to register the receiver in the AndroidManifest. This ensures that the BroadcastReceiver runs all the time, even when the app is backgrounded. I chose this option because I want my application to receive Bluetooth events even when the app isn't in use (i.e. backgrounded). In my AndroidManifest.


1 Answers

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.

like image 118
Tal Kanel Avatar answered Sep 21 '22 18:09

Tal Kanel