问题
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?
回答1:
I'd like to get to know if an Activity successfully started an IntentService.
If you don't get an exception in either the activity or the service when you call startService()
, then the IntentService
was started.
As it's possible to bind an IntentService via bindService() to keep it running
Why?
回答2:
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;
}
回答3:
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!";
}
回答4:
Here's the method I use to check if my service is running:
public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return service.started;
}
}
return false;
}
来源:https://stackoverflow.com/questions/7060793/how-to-check-if-an-intentservice-was-started