I'd like to get to know if an Activity successfully started an IntentService
.
As it's possible to bind an IntentService
via bindService()
to keep it running, perhaps an approach would be to check if invoking startService(intent)
results in a call of onStartCommand(..)
or onHandleIntent(..)
in the service object.
But how can I check that in the Activity?
Here's the method I use to check if my service is running. The Sercive class is DroidUptimeService.
private boolean isServiceRunning() {
ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);
if (serviceList.size() <= 0) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName serviceName = serviceInfo.service;
if (serviceName.getClassName().equals(DroidUptimeService.class.getName())) {
return true;
}
}
return false;
}
You can add a flag when constructing the PendingIntent
, if the returned value was null
, your service is not started. The mentioned flag is PendingIntent.FLAG_NO_CREATE
.
Intent intent = new Intent(yourContext,YourService.class);
PendingIntent pendingIntent = PendingIntent.getService(yourContext,0,intent,PendingIntent.FLAG_NO_CREATE);
if (pendingIntent == null){
return "service is not created yet";
} else {
return "service is already running!";
}
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