Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an IntentService was started

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?

like image 845
cody Avatar asked Dec 10 '22 06:12

cody


2 Answers

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;
}
like image 195
Carlos Silva Avatar answered Dec 27 '22 08:12

Carlos Silva


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!";
}
like image 39
MohammadReza Avatar answered Dec 27 '22 09:12

MohammadReza