標籤:intentservice android 後台 handler thread
引言
Service服務是Android四大組件之一,在Android中有著舉足重輕的作用。Service服務是工作的UI線程中,當你的應用需要下載一個檔案或者播放音樂等長期處於後台工作而有沒有UI介面的時候,你肯定要用到Service+Thread來實現。因此你需要自己在Service服務裡面實現一個Thread背景工作執行緒來下載檔案或者播放音樂。然而你每次都需要自己去寫一個Service+Thread來處理長期處於後台而沒有UI介面的任務,這樣顯得很麻煩,沒必要每次都去構建一個Service+Thread架構處理長期處於背景任務。Google工程師給我們構建了一個方便開發人員使用的這麼一個架構—IntentService。
IntentService簡介
IntentService是一個基礎類,用於處理Intent類型的非同步工作要求。當用戶端調用android.content.Context#startService(Intent)發送請求時,Service服務被啟動,且在其內部構建一個背景工作執行緒來處理Intent請求。當背景工作執行緒執行結束,Service服務會自動停止。IntentService是一個抽象類別,使用者必須實現一個子類去繼承它,且必須實現IntentService裡面的抽象方法onHandleIntent來處理非同步工作要求。
IntentServic樣本Client代碼
public class ClientActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //用戶端同時發送兩個任務到IntentService服務端執行 public void send(View view) { Intent intent = new Intent(this, DownLoadService.class); intent.putExtra("key", 1); intent.putExtra("value", "the first task1"); startService(intent); Intent intent1 = new Intent(this, DownLoadService.class); intent1.putExtra("key", 2); intent1.putExtra("value", "the second task2"); startService(intent1); }}
類比兩個非同步任務同時請求,通過Intent執行個體攜帶資料啟動Service服務。
Service用戶端
public class DownLoadService extends IntentService { public static final String TAG = "DownLoadService"; //重寫預設的構造方法 public DownLoadService() { super("DownLoadService"); } //在後台線程執行 @Override protected void onHandleIntent(Intent intent) { int key = intent.getIntExtra("key", 0); String value = intent.getStringExtra("value"); switch (key) { case 1: //類比耗時任務1 try { Thread.sleep(3 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } break; case 2: //類比耗時任務1 try { Thread.sleep(3 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } break; default: break; } Log.e(TAG, "\nthe current time is: " + System.currentTimeMillis()/1000 + "\nthe Thread id is " + Thread.currentThread().getId() + "\nthe current task is " + value); }}
DownLoadService子類繼承IntentService類,然後實現onHandleIntent抽象方法進行處理Intent請求的非同步任務。在服務端DownLoadService類中,我們並沒有建立Thread線程去執行非同步耗時工作要求。所有的非同步耗時任務都是在onHandleIntent抽象方法中實現了。言外之意是IntentService類內部已經幫開發人員搭建好了一個非同步任務處理器,使用者只需實現其中的onHandleIntent抽象方法去處理非同步任務即可,從而讓開發人員更加簡單方便的使用IntentService處理後台非同步工作要求。那麼IntentService內部是怎麼搭建非同步任務處理器的呢?我們不妨查看源碼來窺探個究竟。
IntentService源碼分析IntentService構造方法
/** * Creates an IntentService. Invoked by your subclass‘s constructor. * * @param name Used to name the worker thread, important only for debugging. */ public IntentService(String name) { super(); mName = name; }
分析:該構造方法需在子類中調用,用於建立一個IntentService對象。參數name用於定義背景工作執行緒的名稱,僅僅用於調式作用。我們知道Service服務的生命週期是從onCreate方法開始的。那麼就來看看IntentService#onCreate方法吧。
IntentService#onCreate方法
public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }
分析:該方法首先利用HandlerThread類建立了一個迴圈的背景工作執行緒thread,然後將背景工作執行緒中的Looper對象作為參數來建立ServiceHandler訊息執行者。由另一篇部落格 Android HandlerThread 源碼分析 可知,HandlerThread+Handler構建成了一個帶有訊息迴圈機制的非同步任務處理機制。因此開發人員就可以將非同步任務封裝成訊息的形式發送到背景工作執行緒中去執行了。Service服務生命週期第二步執行IntentService#onStartCommand方法。
IntentService#onStartCommand方法
/** * You should not override this method for your IntentService. Instead, * override {@link #onHandleIntent}, which the system calls when the IntentService * receives a start request. * @see android.app.Service#onStartCommand */ @Override public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; }
分析:在IntentService子類中你無需重寫該方法。然後你需要重寫onHandlerIntent方法,系統會在IntentService接受一個請求開始調用該方法。我們看到在該方法中僅僅是調用了onStart方法而已,跟蹤代碼:
@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
分析:該方法中通過mServiceHandler獲得一個訊息對象msg,然後將startId作為該訊息的訊息碼,將非同步工作要求intent作為訊息內容封裝成一個訊息msg發送到mServiceHandler訊息執行者中去處理,那麼我們來看看mServiceHandler的實現吧!
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); } }
分析:實現也比較簡單,ServiceHandler是IntentService的內部類,在重寫訊息處理方法handlerMessage裡面調用了onHandlerIntent抽象方法去處理非同步任務intent的請求,當非同步工作要求結束之後,調用stopSelf方法自動結束IntentService服務。看過部落格 Android HandlerThread 源碼分析 的人都應該知道,此處handleMessage方法是在背景工作執行緒中調用的,因此我們子類重寫的onHandlerIntent也是在背景工作執行緒中實現的。我們來看看onHandlerIntent方法:
/** * This method is invoked on the worker thread with a request to process. * Only one Intent is processed at a time, but the processing happens on a * worker thread that runs independently from other application logic. * So, if this code takes a long time, it will hold up other requests to * the same IntentService, but it will not hold up anything else. * When all requests have been handled, the IntentService stops itself, * so you should not call {@link #stopSelf}. * * @param intent The value passed to {@link * android.content.Context#startService(Intent)}. */ protected abstract void onHandleIntent(Intent intent);
分析:該方法用於處理intent非同步工作要求,在背景工作執行緒中調用該方法。每一個時刻只能處理一個intent請求,當同時又多個intent請求時,也就是用戶端同時多次調用Content#startService方法啟動同一個服務時,其他的intent請求會暫時被掛起,直到前面的intent非同步工作要求處理完成才會處理下一個intent請求。直到所有的intent請求結束之後,IntentService服務會調用stopSelf停止當前服務。也就是當intent非同步任務處理結束之後,對應的IntentService服務會自動銷毀,進而調用IntentService#onDestroy方法:
@Override public void onDestroy() { mServiceLooper.quit(); }
該方法中調用HandlerThread背景工作執行緒中Looper對象的quit方法讓當前背景工作執行緒HandlerThread退出當前Looper迴圈,進而結束線程。進而結束當前IntentService服務。到此,整個IntentService服務結束,現在可以用一張流程圖來描述整個過程如下:
IntentService總結
- 子類需繼承IntentService並且實現裡面的onHandlerIntent抽象方法來處理intent類型的工作要求。
- 子類需要重寫預設的構造方法,且在構造方法中調用父類帶參數的構造方法。
- IntentService類內部利用HandlerThread+Handler構建了一個帶有訊息迴圈處理機制的後台背景工作執行緒,用戶端只需調用Content#startService(Intent)將Intent工作要求放入後台工作隊列中,且用戶端無需關注服務是否結束,非常適合一次性的背景工作。比如瀏覽器下載檔案,退出當前瀏覽器之後,下載任務依然存在後台,直到下載檔案結束,服務自動銷毀。
- 只要當前IntentService服務沒有被銷毀,用戶端就可以同時投放多個Intent非同步工作要求,IntentService服務端這邊是順序執行當前後台工作隊列中的Intent請求的,也就是每一時刻只能執行一個Intent請求,直到該Intent處理結束才處理下一個Intent。因為IntentService類內部利用HandlerThread+Handler構建的是一個單線程來處理非同步任務。
【轉載請註明出處:http://blog.csdn.net/feiduclear_up CSDN 廢墟的樹】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android IntentService的使用和源碼分析