Android's services
Android uses services to perform long running jobs, or background tasks (think to a network interaction or an mp3 player). How can we start a service?
We should begin extending the android.app.Service class:
The two most important methods, for the purposes of this post, are onCreate and onStartCommand. Android invokes the first, when the service is created, and the second one, when it is executed. The Toast.makeText(…) command is a nice way to give notifications to the users.
Please note that the onStartCommand callback exists only in the versions 2.0 and later. In older versions you should override the onStart method (now deprecated).
Once you have you service’s skeleton, you can register with the operating system, adding a line to the manifest:
Or in a easier way, using the Eclipse interface:
At the end is time to start our service, using two instructions:
We create an android.content.Intent instance, and then we use it in the startService method. The Intent, ask you for a context (your calling Activity is fine), and the implementation class. He will take care of the instantiation. The startService will call your onStartCommand procedure, passing it also the intent instance. A nice place to do it could be in the onClick method:
This post was originally published on escogitare.blogspot.it. The Android’s guide to services is at the address developer.android.com/guide/components/services.html.