Basic IntentService Example

suggest change

The abstract class IntentService is a base class for services, which run in the background without any user interface. Therefore, in order to update the UI, we have to make use of a receiver, which may be either a BroadcastReceiver or a ResultReceiver:

Within the IntentService, we have one key method, onHandleIntent(), in which we will do all actions, for example, preparing notifications, creating alarms, etc.

To use your own IntentService, extend it as follows. Also declare the service in the manifest.

public class YourIntentService extends IntentService {
    public YourIntentService() {
        super("YourIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO: Write your own code here.
    }
}

Start the service as follows:

Intent i = new Intent(this, YourIntentService.class);
startService(i);

As with an activity, you can pass extras to the service:

Intent passDataIntent = new Intent(this, YourIntentService.class);
passDataIntent.putExtra("foo", "bar");
startService(passDataIntent);

Now assume that we passed some data to the YourIntentService class. Based on this data, an action can be performed as follows:

public class YourIntentService extends IntentService {
    public YourIntentService() {
        super("YourIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String activityValue = "bar";
        String retrievedValue = intent.getStringExtra("foo");
        if (activityValue.equals(retrievedValue)) {
            // Send the notification to foo.
        } else {
            // Retrieving data failed.
        }
    }
}

The code above shows how to branch on that extra inside onHandleIntent(). Read the extra there. A field initializer cannot see the Intent.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents