Android: How to determine if IntentService is running?

11,530

Solution 1

IntentService needs to implement onHandleIntent() This method is invoked on the worker thread with a request to process Intent request and IntentService will be "alive" as long as it is processing a intent request (am not considering low memory and other corener cases here, but just thinking in terms of logic),

And When all requests have been handled, the IntentService stops itself, (and hence you should not call stopSelf() explicitly)

With this theory in place, You may try below logic:
Declare a class variable inside your IntentService class.
public static boolean isIntentServiceRunning = false;

@Override    
     protected void onHandleIntent(Intent workIntent) { 
        if(!isIntentServiceRunning) {
         isIntentServiceRunning = true;
       }
      //Your other code here for processing request
 }

And in onDestroy() of IntentService class if you may choose, set isIntentServiceRunning = false;

And use isIntentServiceRunning to check if IntentService is Running!

Solution 2

In your code you are trying to get the status of service from Activity. The correct way is that status should be given by the service.

There are several possibilities for an activity to communicate with a service and vice versa. As you are using Broadcast receiver so you can broadcast a message in onHandleIntent() method when the service started.

and then when your task completes or in case of any error, again you can call the broadcast receiver for service finished event.

here is a link for a nice tutorial.

Share:
11,530
Ruchit Shah
Author by

Ruchit Shah

Updated on June 09, 2022

Comments

  • Ruchit Shah
    Ruchit Shah almost 2 years

    I have an activity for upload from which I am calling Intent service. In there I am handling the API request call.

    I want an activity to know whether the service is running or not, to show an uploading tag.

    I tried following to determine if the service is running:

    public void startUploadServiceTask() {
        if (Util.isNetworkAvailable(mContext)) {
    
            if (!isMyServiceRunning(UploadDriveService.class)) {
    
                    startService(new Intent(mContext,
                            UploadService.class));
    
                }
            } else {
                Toast.makeText(mContext,
                        "Service is already running.", Toast.LENGTH_SHORT)
                        .show();
            }
        } else {
            Toast.makeText(mContext,
                    getString(R.string.please_check_internet_connection),
                    Toast.LENGTH_SHORT).show();
        }
    }
    
    
    
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager
                .getRunningServices(Integer.MAX_VALUE)) {
            Log.e("ALL SERVICE", service.service.getClassName().toString());
            if (serviceClass.getName().equals(service.service.getClassName())) {
    
                return true;
            }
        }
        return false;
    }
    

    But in Activity Manager Running Service Info, I am not getting the class of intent service that I am running, so this always stands false.

    I have used Broadcast for API calls response.

    I have even checked this code.

    if(startService(someIntent) != null) { 
     Toast.makeText(getBaseContext(), "Service is already running",     Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(getBaseContext(), "There is no service running, starting     service..", Toast.LENGTH_SHORT).show();
    } 
    

    But in this code, on checking the service it also starts the service again, so service is called twice.

    Please help me out with this.

  • Ruchit Shah
    Ruchit Shah about 9 years
    What if service is already started and i go to another activity and come back to Upload activity and that time service is running but i cant get any response and in question i have written about the code which i used the same code in example.
  • Sandeep Solanki
    Sandeep Solanki about 9 years
    In that case you can use a status field in broadcast receiver and change it's value according to service status. Whenever your activity gets focus you can check for this value.
  • Tejas Sherdiwala
    Tejas Sherdiwala almost 9 years
    @SandeepSolanki: Can you please elaborate your solution in response to Ruchit Shah's reply. Generally the broadcast receiver is registered in the onResume() method of the Activity and unregistered in the onPause() method of the Activity. On the broadcast receiver is unregistered, how can the status field(that you described) of the BroadcastReceiver be assigned a value and the same can be fetched in the Activity?
  • howettl
    howettl about 7 years
    This will not be thread-safe, since onDestroy() is called in a different thread than onHandleIntent(). You should surround the extra code with a synchronized() block.
  • sergiomse
    sergiomse over 6 years
    How do you get the service instance from an Activity? The question is using ActivityManager, but the android docs says that is only for testing and debugging, so this solution is not good enough. developer.android.com/reference/android/app/…