什麼是IntentService?android
官方的解釋是:
IntentService is a base class for
Services that handle asynchronous requests (expressed as
Intents) on demand. Clients send requests through
android.content.Context.startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement
onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
意思是說:IntentService是一個經過
Context.startService(Intent)啓動能夠處理異步請求的Service,使用時你只須要繼承IntentService和重寫其中的
onHandleIntent(Intent)方法接收一個Intent對象,在適當的時候會中止本身(通常在工做完成的時候). 全部的請求的處理都在一個工做線程中完成,它們會交替執行(但不會阻塞主線程的執行),一次只能執行一個請求.(**本人修改了原文的一些翻譯)
下面是要分析的源碼:
public
abstract
class IntentService
extends Service {
private
volatile Looper mServiceLooper;
private
volatile ServiceHandler mServiceHandler;
private String mName;
private
boolean mRedelivery;
private
final
class ServiceHandler
extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public
void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
從源碼能夠分析出:
IntentService 其實是Looper,Handler,Service 的集合體,他不只有服務的功能,還有處理和循環消息的功能.
下面是onCreate()的源碼:
@Override
public
void onCreate() {
super.onCreate();
HandlerThread thread =
new HandlerThread(
"IntentService[" + mName +
"]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler =
new ServiceHandler(mServiceLooper);
}
分析:IntentService建立時就會建立Handler線程(HandlerThread)而且啓動,而後再獲得當前線程的Looper對象來初始化IntentService的mServiceLooper,接着建立mServicehandler對象.
下面是onStart()的源碼:
@Override
public
void onStart(Intent intent,
int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
分析:當你啓動IntentService的時候,就會產生一條附帶startId和Intent的Message併發送到MessageQueue中,接下來Looper發現MessageQueue中有Message的時候,就會中止Handler處理消息,接下來處理的代碼以下:
@Override
public
void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
接着調用 onHandleIntent((Intent)msg.obj),這是一個抽象的方法,其實就是咱們要重寫實現的方法,咱們能夠在這個方法裏面處理咱們的工做.當任務完成時就會調用stopSelf(msg.arg1)這個方法來結束指定的工做.
當全部的工做執行完後:就會執行onDestroy方法,源碼以下:
@Override
public
void onDestroy() { mServiceLooper.quit(); }
服務結束後調用這個方法 mServiceLooper.quit()使looper停下來. 經過對源碼的分析得出: 這是一個基於消息的服務,每次啓動該服務並非立刻處理你的工做,而是首先會建立對應的Looper,Handler而且在MessageQueue中添加的附帶客戶Intent的Message對象,當Looper發現有Message的時候接着獲得Intent對象經過在onHandleIntent((Intent)msg.obj)中調用你的處理程序.處理完後即會中止本身的服務.意思是Intent的生命週期跟你的處理的任務是一致的.因此這個類用下載任務中很是好,下載任務結束後服務自身就會結束退出