Continuing from
Part 1 about the UI thread, today, I would like to discuss the IntentService class.
Concept:
In simple terms, IntentService provides a mechanism to run a long task
in the background. We need not worry of any thread creation and
management. It is all done behind the scene. We just extend our class
from the IntentService class, and implement our long task in the
overridden onHandleIntent() method.
On the specified trigger (which is an Intent), the platform will spawn a
worker thread for our extended class and then call the onHandleIntent
method on this thread. I like to visualize this as follows:
So,
all the long running code can be executed in the onHandleIntent()
method. We can be sure that this will not block the main (UI) thread.
It is worth noting here that if there are
multiple intents that are received, they all will
NOT execute in parallel. The IntentService class spawn a
SINGLE worker thread. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
So, the obvious question is : What if I want to execute multiple tasks in parallel ?
I will defer to answer this till the end of this article series. We will
first go through AsyncTask in the next article and then the concluding
post I will try to consider various use cases, limitations and
comparisons.
Implementation details:
Now for some implementation details. Extend your class (say MyIntentService) as follows:
class MyIntentService extends IntentService {
public MyIntentService() {
super ("com.foo.MyIntentService");
}
protected void onHandleIntent(Intent intent) {
// call to any long running task !
}
}
Thats it. You are all set ! Now, you can trigger this by calling the
startService(Intent) method. We need not worry about stopping the
service.
Once the long running task is done and if there are no
intents lined up in the message queue, the platform will automatically
stop the IntentService.
I have stated again and again, IntentService is very useful when you
need to perform a long task in the background. The interesting part here
is that the trigger for starting the task is an Intent ! Now that opens
a lot of opportunities. Don't get it ? Here is hint : Your application
need not be running at the time you want to start a background task !
All you need to do is have a PendingIntent for your IntentService. Now
you can register this PendingIntent with many of the available callbacks
in the Android APIs. So, now, even if your application is not running,
and the PendingIntent is fired ! Wolaa - your background task is started
:)
Coming up next is AsyncTask.
阅读(584) | 评论(0) | 转发(0) |