Working With Services In Android – IntentService

A service is an application component that can perform long-running operations in the background and it does not provide an user interface. For example, a service might handle network transactions, play music, perform file I/O, etc., all from the background.

Usually, there are two classes you can extend to create a service: you extend the Service class and override some callback methods, or extend the IntentService class and all you need to do is implement the onHandleIntent() method where you put all the code that should run in the background.

Extending the IntentService class is the simplest way to create a service. If you don’t need to handle multiple requests simultaneously, then this probably is the best option to choose.

 

In this post we will create a service using the IntentService class.

Well, our service won’t do much. This would be a proof-of-concept application, showing the creation process of a service. The mission of our service would be just to print a message in the LogCat, (pretty simple for a service :)), but in a real application you would write of course more advanced code, like playing music, or performing some I/O operations for example.

1. Create a new project in Eclipse:
Project: ServiceTest
Activity: ServiceTestActivity

2. Create a new class, say MyService, and do as follows:
– Extend the IntentService
– Provide a constructor with no arguments that calls the super constructor, with a name as an argument.
– Override the onHandleIntent(Intent intent); method.


public class MyService extends IntentService{

// No-arg constructor is required
public MyService() {
   super("MyService");
}

@Override
protected void onHandleIntent(Intent intent) {
   Log.d("TAG", "Service started");

   //....
   // The rest of the code that needs to run in the background
   //....

}
}

Note that it’s important that you provide a no-arg constructor, otherwise you may get an exception: InstantiationException

 

3. Register your service

Open the AndroidManifest file and add the following line as a child of <application> tag:


<application ......
   <service android:name=".MyService" />
</application>

 

4. Start the service

To start a service the startService(intent) method is used, which takes as an argument an intent with the specified service.


@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   // Starting the service
   Intent intent =new Intent(this, MyService.class);
   startService(intent);
}
Advertisement