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.
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()的源碼:
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
當所有的工作執行完後:就會執行onDestroy方法,源碼如下:
public void onDestroy() {
mServiceLooper.quit();
}
通過對源碼的分析得出:
這是一個基於消息的服務,每次啓動該服務並不是馬上處理你的工作,而是首先會創建對應的Looper,Handler並且在MessageQueue中添加的附帶客戶Intent的Message對象,當Looper發現有Message的時候接着得到Intent對象通過在onHandleIntent((Intent)msg.obj)中調用你的處理程序.處理完後即會停止自己的服務.意思是Intent的生命週期跟你的處理的任務是一致的.所以這個類用下載任務中非常好,下載任務結束後服務自身就會結束退出.