前言
-
多線程的應用在Android開發中是非常常見的,常用方法主要有:
- 繼承Thread類
- 實現Runnable接口
- AsyncTask
- Handler
- HandlerThread
- IntentService
-
今天,我將全面解析多線程其中一種常見用法:IntentService
目錄
1. 定義
IntentService是Android里面的一個封裝類,繼承自四大組件之一的Service。
2. 作用
處理異步請求,實現多線程
3. 工作流程
注意:若啟動IntentService 多次,那么每個耗時操作則以隊列的方式在 IntentService的onHandleIntent回調方法中依次執行,執行完自動結束。
4. 實現步驟
- 步驟1:定義IntentService的子類:傳入線程名稱、復寫onHandleIntent()方法
- 步驟2:在Manifest.xml中注冊服務
- 步驟3:在Activity中開啟Service服務
5. 具體實例
- 步驟1:定義IntentService的子類:傳入線程名稱、復寫onHandleIntent()方法
package com.example.carson_ho.demoforintentservice; import android.app.IntentService; import android.content.Intent; import android.util.Log; /** * Created by Carson_Ho on 16/9/28. */ public class myIntentService extends IntentService { /*構造函數*/ public myIntentService() { //調用父類的構造函數 //構造函數參數=工作線程的名字 super("myIntentService"); } /*復寫onHandleIntent()方法*/ //實現耗時任務的操作 @Override protected void onHandleIntent(Intent intent) { //根據Intent的不同進行不同的事務處理 String taskName = intent.getExtras().getString("taskName"); switch (taskName) { case "task1": Log.i("myIntentService", "do task1"); break; case "task2": Log.i("myIntentService", "do task2"); break; default: break; } } @Override public void onCreate() { Log.i("myIntentService", "onCreate"); super.onCreate(); } /*復寫onStartCommand()方法*/ //默認實現將請求的Intent添加到工作隊列里 @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("myIntentService", "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("myIntentService", "onDestroy"); super.onDestroy(); } }
- 步驟2:在Manifest.xml中注冊服務
<service android:name=".myIntentService"> <intent-filter > <action android:name="cn.scu.finch"/> </intent-filter> </service>
- 步驟3:在Activity中開啟Service服務
package com.example.carson_ho.demoforintentservice; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //同一服務只會開啟一個工作線程 //在onHandleIntent函數里依次處理intent請求。 Intent i = new Intent("cn.scu.finch"); Bundle bundle = new Bundle(); bundle.putString("taskName", "task1"); i.putExtras(bundle); startService(i); Intent i2 = new Intent("cn.scu.finch"); Bundle bundle2 = new Bundle(); bundle2.putString("taskName", "task2"); i2.putExtras(bundle2); startService(i2); startService(i); //多次啟動 } }
- 結果
運行結果
6. 源碼分析
接下來,我們會通過源碼分析解決以下問題:
- IntentService如何單獨開啟一個新的工作線程;
- IntentService如何通過onStartCommand()傳遞給服務intent被依次插入到工作隊列中
問題1:IntentService如何單獨開啟一個新的工作線程
// IntentService源碼中的 onCreate() 方法 @Override public void onCreate() { super.onCreate(); // HandlerThread繼承自Thread,內部封裝了 Looper //通過實例化andlerThread新建線程並啟動 //所以使用IntentService時不需要額外新建線程 HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); //獲得工作線程的 Looper,並維護自己的工作隊列 mServiceLooper = thread.getLooper(); //將上述獲得Looper與新建的mServiceHandler進行綁定 //新建的Handler是屬於工作線程的。 mServiceHandler = new ServiceHandler(mServiceLooper); } private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } //IntentService的handleMessage方法把接收的消息交給onHandleIntent()處理 //onHandleIntent()是一個抽象方法,使用時需要重寫的方法 @Override public void handleMessage(Message msg) { // onHandleIntent 方法在工作線程中執行,執行完調用 stopSelf() 結束服務。 onHandleIntent((Intent)msg.obj); //onHandleIntent 處理完成后 IntentService會調用 stopSelf() 自動停止。 stopSelf(msg.arg1); } } ////onHandleIntent()是一個抽象方法,使用時需要重寫的方法 @WorkerThread protected abstract void onHandleIntent(Intent intent);
問題2:IntentService如何通過onStartCommand()傳遞給服務intent被依次插入到工作隊列中
public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; } public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; //把 intent 參數包裝到 message 的 obj 中,然后發送消息,即添加到消息隊列里 //這里的Intent 就是啟動服務時startService(Intent) 里的 Intent。 msg.obj = intent; mServiceHandler.sendMessage(msg); } //清除消息隊列中的消息 @Override public void onDestroy() { mServiceLooper.quit(); }
- 總結
從上面源碼可以看出,IntentService本質是采用Handler & HandlerThread方式:- 通過HandlerThread單獨開啟一個名為IntentService的線程
- 創建一個名叫ServiceHandler的內部Handler
- 把內部Handler與HandlerThread所對應的子線程進行綁定
- 通過onStartCommand()傳遞給服務intent,依次插入到工作隊列中,並逐個發送給onHandleIntent()
- 通過onHandleIntent()來依次處理所有Intent請求對象所對應的任務
因此我們通過復寫方法onHandleIntent(),再在里面根據Intent的不同進行不同的線程操作就可以了
注意事項1. 工作任務隊列是順序執行的。
如果一個任務正在IntentService中執行,此時你再發送一個新的任務請求,這個新的任務會一直等待直到前面一個任務執行完畢才開始執行
原因:
- 由於onCreate() 方法只會調用一次,所以只會創建一個工作線程;
- 當多次調用 startService(Intent) 時(onStartCommand也會調用多次)其實並不會創建新的工作線程,只是把消息加入消息隊列中等待執行,所以,多次啟動 IntentService 會按順序執行事件
- 如果服務停止,會清除消息隊列中的消息,后續的事件得不到執行。
注意事項2:不建議通過 bindService() 啟動 IntentService
原因:
@Override public IBinder onBind(Intent intent) { return null; }
在IntentService中,onBind()是默認返回null的,而采用bindService() 啟動 IntentService的生命周期是:onCreate() —>onBind()—>onunbind()—>onDestory()
並不會調用onstart()或者onstartcommand()方法,所以不會將消息發送到消息隊列,那么onHandleIntent()將不會回調,即無法實現多線程的操作。
此時,你使用的是Service,而不是IntentService
7. 使用場景
- 線程任務需要按順序、在后台執行的使用場景
最常見的場景:離線下載
- 由於所有的任務都在同一個Thread looper里面來做,所以不符合多個數據同時請求的場景。
8. 對比
8.1 IntentService與Service的區別
-
從屬性 & 作用上來說
Service:依賴於應用程序的主線程(不是獨立的進程 or 線程)不建議在Service中編寫耗時的邏輯和操作,否則會引起ANR;
IntentService:創建一個工作線程來處理多線程任務
- Service需要主動調用stopSelft()來結束服務,而IntentService不需要(在所有intent被處理完后,系統會自動關閉服務)
此外:
- IntentService為Service的onBingd()方式提供了默認實現:返回null
- IntentService為Service的onStartCommand()方法提供了默認實現:將請求的intent添加到隊列中
8.2 IntentService與其他線程的區別
- IntentService內部采用了HandlerThread實現,作用類似於后台線程;
- 與后台線程相比,IntentService是一種后台服務,優勢是:優先級高(不容易被系統殺死),從而保證任務的執行
對於后台線程,若進程中沒有活動的四大組件,則該線程的優先級非常低,容易被系統殺死,無法保證任務的執行
