IntentService 和ResultReceiver

转自[url] http://javatechig.com/android/creating-a-background-service-in-android[/url]


1. What is IntentService?

IntentService is a subclass of android.app.Service class. A stated intent service allows to handle long running tasks without effecting the application UI thread. This is not bound to any activity so, it is not getting effected for any change in activity lifecycle. Once IntentService is started, it handles each Intent using a worker thread and stops itself when it runs out of work.

IntentService would be an best solution, If you have an work queue to process. For example, if your application using analytics you will likely to send event name and related parameter to your tracking server for each user generated event. Although each event means a tiny piece of data, creating networking request on each click will result an overhead to your application. Instead, you can use work queue processor design pattern and process the events in a batch.
2. IntentService Limitations

    No easy or direct way to interact with user interface directly from IntentService. Later in this example, we will explain to pass result back from IntentService to
    With IntentService, there can only be one request processed at any single point of time. If you request for another task, then the new job will wait until the previous one is completed. This means that IntentService process the request
    An tasks stated using IntentService cannot be interrupted

3. Why do we need IntentService?

Android design guidelines strongly suggests to perform all the long running tasks off the UI thread. For example, if you have to periodically download the largest chunk of data from server, you must use IntentService to avoid ANR. ANR (Application not responding) message often occurs, if your main thread is doing too much of work. In this course of this tutorial, we will learn the below concepts

    How to create and use IntentService
    How to pass data from activity to service as parameter
    How to pass result back to activity
    Update activity based on the result

Case Study

To make this tutorial easy to understand we will extend our previous tutorial (Android Networking Tutorial) to use Intent Service for downloading the data from server. We suggest you to checkout Android Networking Example to get familiar with downloading data from server using different http clients available in Android.

Feed Url : http://javatechig.com/api/get_category_posts/?dev=1&slug=android

Expected Result Start service to download the data when application is started. Once download is complete, update ListView present in your activity.

猜你喜欢

转载自aijiawang-126-com.iteye.com/blog/2229465
今日推荐