IntentService是一種用於處理異步請求(表現爲Intent)的服務基類。客戶經過調用Context.startService(Intent)發送請求;根據須要啓動服務,依次使用工做者線程處理每個Intent,而且在工做完成後終止自身。 java
這種「工做隊列處理器」模式一般被用來從一個應用程序的主線程卸載任務。IntentService類的存在是爲了簡化這種模式,而且照顧了技術性的部分。要使用它,須要繼承IntentService類而且實現onHandleIntent(Intent)方法。IntentService將會接收到這些Intent,運行一條工做者線程,而且在適當的時候中止服務。 異步
全部的請求都是在一個單一的工做者線程中處理的,儘管處理過程可能須要很長時間(不會阻塞應用程序的主線程),可是每次只能有一個請求會被處理。 ide
首先,看它提供的一個構造方法: oop
public IntentService(String name) { super(); mName = name; }
參數name被用於命名即將用到的工做者線程,它的重要性僅用於調試。這裏須要注意的一點是,Service的實例化是系統來完成的,而且系統是用無參的構造方法來實例化Service的。因此,你的子類必須是無參的,而後在無參構造方法裏調用super("name")。 線程
再看onCreate方法: 調試
@Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }
其中的ServiceHandler是IntentService類的內部類: code
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); } }
在onCreate方法裏,建立並啓動了一條工做線程。而後使用工做線程的Looper構造了一個Handler,這個Handler將循環處理請求。 繼承
根據Service的生命週期,咱們再看onStartCommand方法: 生命週期
@Override public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; }
後面的返回值,能夠看看Service類的相關內容。onStartCommand方法調用了onStart方法。再跟到onStart方法: 隊列
@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
每次調用Context.startService(Intent intent),都會將一個請求(Message,包含一個Intent,並有一個id)添加到消息隊列(工做線程的循環隊列,相關內容能夠看Handler源碼)。處理完全部請求後,就會中止服務。
對於onHandleIntent(Intent intent)方法,官方註釋是這樣說的:
這個方法運行在工做線程,用於處理一個請求。同一時間只有一個Intent被處理,可是處理過程發生在一個獨立於其它應用邏輯的工做線程。所以,若是這個代碼塊要執行很長時間,它將阻塞其它在同一個IntentService上的請求,除此以外,它不會阻塞其它任何東西。
另外,IntentService實現了一個默認的onBind方法,默認返回null。