Search code examples
androidrestintentserviceandroid-internetandroid-async-http

How to wait for an IntentService to finish its task


I'm using an intent service to communicate with a server to get data for an app. I'd like the app to wait until the data it requests has been sent back (hopefully meaning that the IntentService the data has been requested from has finished running) before the app attempts to access or use the variables the data is to be stored in. How would I go about doing this? thanks!


Solution

  • Easiest way is to have your IntentService send a Broadcast once it is done gathering data from the server, which you can listen to in your UI thread (e.g. Activity).

    public final class Constants {
        ...
        // Defines a custom Intent action
        public static final String BROADCAST_ACTION =
            "com.example.yourapp.BROADCAST";
        ...
        // Defines the key for the status "extra" in an Intent
        public static final String EXTENDED_DATA_STATUS =
            "com.example.yourapp.STATUS";
        ...
    }
    
    public class MyIntentService extends IntentService {
        @Override
        protected void onHandleIntent(Intent workIntent) {
            // Gets data from the incoming Intent
            String dataString = workIntent.getDataString();
            ...
            // Do work here, based on the contents of dataString
            // E.g. get data from a server in your case
            ...
    
            // Puts the status into the Intent
            String status = "..."; // any data that you want to send back to receivers
            Intent localIntent =
                new Intent(Constants.BROADCAST_ACTION)
                        .putExtra(Constants.EXTENDED_DATA_STATUS, status);
            // Broadcasts the Intent to receivers in this app.
            LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
        }
    }
    

    Then create your broadcast receiver (either a separate class or inner class within your Activity)

    E.g.

    // Broadcast receiver for receiving status updates from the IntentService
    private class MyResponseReceiver extends BroadcastReceiver {
        // Called when the BroadcastReceiver gets an Intent it's registered to receive
        @
        public void onReceive(Context context, Intent intent) {
            ...
            /*
             * You get notified here when your IntentService is done
             * obtaining data form the server!
             */
            ...
        }
    }
    

    Now the final step is to register the BroadcastReceiver in your Activity:

    IntentFilter statusIntentFilter = new IntentFilter(
          Constants.BROADCAST_ACTION);
    MyResponseReceiver responseReceiver =
          new MyResponseReceiver();
    // Registers the MyResponseReceiver and its intent filters
    LocalBroadcastManager.getInstance(this).registerReceiver(
          responseReceiver, statusIntentFilter );