Android多線程全面解析:IntentService用法&源碼



前言

  • 多線程的應用在Android開發中是非常常見的,常用方法主要有:

    1. 繼承Thread類
    2. 實現Runnable接口
    3. AsyncTask
    4. Handler
    5. HandlerThread
    6. 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 {

<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">protected</span> void onCreate(<span class="hljs-type">Bundle</span> savedInstanceState) {
    <span class="hljs-keyword">super</span>.onCreate(savedInstanceState);
    setContentView(<span class="hljs-type">R</span>.layout.activity_main);

        <span class="hljs-comment">//同一服務只會開啟一個工作線程</span>
        <span class="hljs-comment">//在onHandleIntent函數裡依次處理intent請求。</span>

        <span class="hljs-type">Intent</span> i = <span class="hljs-keyword">new</span> <span class="hljs-type">Intent</span>(<span class="hljs-string">"cn.scu.finch"</span>);
        <span class="hljs-type">Bundle</span> bundle = <span class="hljs-keyword">new</span> <span class="hljs-type">Bundle</span>();
        bundle.putString(<span class="hljs-string">"taskName"</span>, <span class="hljs-string">"task1"</span>);
        i.putExtras(bundle);
        startService(i);

        <span class="hljs-type">Intent</span> i2 = <span class="hljs-keyword">new</span> <span class="hljs-type">Intent</span>(<span class="hljs-string">"cn.scu.finch"</span>);
        <span class="hljs-type">Bundle</span> bundle2 = <span class="hljs-keyword">new</span> <span class="hljs-type">Bundle</span>();
        bundle2.putString(<span class="hljs-string">"taskName"</span>, <span class="hljs-string">"task2"</span>);
        i2.putExtras(bundle2);
        startService(i2);

        startService(i);  <span class="hljs-comment">//多次啟動</span>
    }
}</code></pre>
  • 結果

    運行結果

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();
<span class="hljs-comment">//獲得工作線程的 Looper,並維護自己的工作隊列</span>
mServiceLooper = thread.getLooper();
<span class="hljs-comment">//將上述獲得Looper與新建的mServiceHandler進行綁定</span>
<span class="hljs-comment">//新建的Handler是屬於工作線程的。</span>
mServiceHandler = <span class="hljs-keyword">new</span> 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方式:
    1. 通過HandlerThread單獨開啟一個名為IntentService的線程
    2. 創建一個名叫ServiceHandler的內部Handler
    3. 把內部Handler與HandlerThread所對應的子線程進行綁定
    4. 通過onStartCommand()傳遞給服務intent,依次插入到工作隊列中,並逐個發送給onHandleIntent()
    5. 通過onHandleIntent()來依次處理所有Intent請求對象所對應的任務

因此我們通過複寫方法onHandleIntent(),再在裡面根據Intent的不同進行不同的線程操作就可以了

注意事項1. 工作任務隊列是順序執行的。

如果一個任務正在IntentService中執行,此時你再發送一個新的任務請求,這個新的任務會一直等待直到前面一個任務執行完畢才開始執行

原因:

  1. 由於onCreate() 方法只會調用一次,所以只會創建一個工作線程;
  2. 當多次調用 startService(Intent) 時(onStartCommand也會調用多次)其實並不會創建新的工作線程,只是把消息加入消息隊列中等待執行,所以,多次啟動 IntentService 會按順序執行事件
  3. 如果服務停止,會清除消息隊列中的消息,後續的事件得不到執行。

注意事項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被處理完後,系統會自動關閉服務)

    此外:

    1. IntentService為Service的onBingd()方式提供了默認實現:返回null
    2. IntentService為Service的onStartCommand()方法提供了默認實現:將請求的intent添加到隊列中

8.2 IntentService與其他線程的區別

  • IntentService內部採用了HandlerThread實現,作用類似於後臺線程;
  • 與後臺線程相比,IntentService是一種後臺服務,優勢是:優先級高(不容易被系統殺死),從而保證任務的執行

    對於後臺線程,若進程中沒有活動的四大組件,則該線程的優先級非常低,容易被系統殺死,無法保證任務的執行

9. 總結

  • 本文主要對多線程IntentService用法&源碼進行了全面介紹
  • 接下來,我會繼續講解Android開發中關於多線程的知識,包括繼承Thread類、實現Runnable接口、Handler等等,有興趣可以繼續關注Carson_Ho的安卓開發筆記

請點贊!因為你的鼓勵是我寫作的最大動力!

相關文章閱讀
1分鐘全面瞭解“設計模式”
Android開發:最全面、最易懂的Android屏幕適配解決方案
Android開發:Handler異步通信機制全面解析(包含Looper、Message Queue)
Android開發:頂部Tab導航欄實現(TabLayout+ViewPager+Fragment)
Android開發:底部Tab菜單欄實現(FragmentTabHost+ViewPager)
Android開發:JSON簡介及最全面解析方法!
Android開發:XML簡介及DOM、SAX、PULL解析對比


歡迎關注Carson_Ho的簡書!

不定期分享關於安卓開發的乾貨,追求短、平、快,但卻不缺深度


    </div>

书籍推荐