page.title=Sending Work Requests to the Background Service trainingnavtop=true @jd:body
The previous lesson showed you how to create an {@link android.app.IntentService} class. This lesson shows you how to trigger the {@link android.app.IntentService} to run an operation by sending it an {@link android.content.Intent}. This {@link android.content.Intent} can optionally contain data for the {@link android.app.IntentService} to process. You can send an {@link android.content.Intent} to an {@link android.app.IntentService} from any point in an {@link android.app.Activity} or {@link android.app.Fragment}
To create a work request and send it to an {@link android.app.IntentService}, create an explicit {@link android.content.Intent}, add work request data to it, and send it to {@link android.app.IntentService} by calling {@link android.content.Context#startService startService()}.
The next snippets demonstrate this:
RSSPullService
.
/* * Creates a new Intent to start the RSSPullService * IntentService. Passes a URI in the * Intent's "data" field. */ mServiceIntent = new Intent(getActivity(), RSSPullService.class); mServiceIntent.setData(Uri.parse(dataUrl));
// Starts the IntentService getActivity().startService(mServiceIntent);
Notice that you can send the work request from anywhere in an Activity or Fragment. For example, if you need to get user input first, you can send the request from a callback that responds to a button click or similar gesture.
Once you call {@link android.content.Context#startService startService()}, the {@link android.app.IntentService} does the work defined in its {@link android.app.IntentService#onHandleIntent onHandleIntent()} method, and then stops itself.
The next step is to report the results of the work request back to the originating Activity or Fragment. The next lesson shows you how to do this with a {@link android.content.BroadcastReceiver}.