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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With