Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

IntentService 全面解析:用法、實作與源碼追蹤

編輯:Android 資訊

一、IntentService 是什麼

三個基本問題:是什麼、怎麼用、如何運作

官方文件的說法:

1、IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand.

2、Clients send requests through startService(Intent) calls;

3、the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

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.

整理成幾個要點:

1、IntentService 是 Service 的子類,專門處理非同步請求。

2、客戶端透過 startService(Intent) 把請求送進來。

3、它在 onCreate() 中透過 HandlerThread 另開一條工作線程,用來處理所有以 startService 送來的請求,避免阻塞主線程。

4、每完成一個請求,若佇列中沒有新的 Intent,Service 會自行停止;否則接著處理下一個。

5、處理機制仍是 Handler 模式:建立一個名為 ServiceHandler 的內部 Handler,並綁定到 HandlerThread 所對應的子線程。每個 Intent 的處理邏輯被封裝在 onHandleIntent 這個抽象方法裡,我們只要覆寫它,就能依 Intent 的 action 分流處理。

最關鍵的方法:onHandleIntent

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 stopSelf().

也就是說:這個方法跑在工作線程上,一次只處理一個 Intent。它執行得久,只會延後同一個 IntentService 的後續請求,不影響 App 其他邏輯;所有請求處理完之後 Service 會自己停下來,所以不需要(也不應該)手動呼叫 stopSelf()。

特點、優點與限制

特點:

  1. 以消息佇列實作,任務本質上是先進先出的 queue;
  2. 只有單一工作線程,所有任務必須排隊執行;
  3. 省下了自己建線程、以及手動管理 Service 生命週期的麻煩。

相較於一般 Service,好處有兩點:一是使用方便、程式碼簡潔,不必自己開線程;二是任務做完不用手動停止 Service。

缺點也很明顯:只有一個工作線程,任務必須排隊,不適合需要併發的多任務場景。

二、動手做個 Demo

場景設計

由 MainActivity 與 MyIntentService 組成:MainActivity 啟動服務並傳入兩個參數 a 與 b,MyIntentService 取參數、求和,透過廣播把結果送回 UI,MainActivity 收到廣播後更新畫面。

MainActivity 做三件事

註冊與取消註冊廣播接收器、建立與更新 UI、傳參數並啟動服務。

public class MainActivity extends AppCompatActivity { private LinearLayout ll_container; private BroadcastReceiver forSumReceiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("TAG","onReceive ()"); if(intent.getAction()==Constans.ACTION_RESULT){ int a=intent.getIntExtra(Constans.A,0); int result=intent.getIntExtra(Constans.RESULT,0); Log.i("TAG","onReceive --result:"+result); handleResult(a,result); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll_container= (LinearLayout)findViewById(R.id.ll_container); Log.i("TEST","MainActivity:"+android.os.Process.myTid()); registerBroadcast(); } private void handleResult(int a,int result){ TextView textView=(TextView)ll_container.findViewWithTag(a); String old=textView.getText().toString(); String newText=old.replaceAll(" 正在計算中...",String.valueOf(result)+" 計算Success"); textView.setText(newText); } private void registerBroadcast(){ IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction(Constans.ACTION_RESULT); registerReceiver(forSumReceiver,intentFilter); } private int a=1; public void addTask(View view){ int b=new Random().nextInt(101)+1; MyIntentService.startMyIntentService(this,a,b); TextView textView=new TextView(this); textView.setText(a+"+"+b+"= "+ " 正在計算中..."); textView.setTag(a); ll_container.addView(textView); a++; } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(forSumReceiver); } }

MyIntentService 負責計算與回報

public class MyIntentService extends IntentService { public MyIntentService() { //必須實現父類的構造方法 super("MyIntentService"); } @Override public void onCreate() { Log.i("TEST","onCreate()"); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { Log.i("TEST","onStart()"); super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("TEST","onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { Log.i("TEST", "onBind()"); return super.onBind(intent); } @Override public void onDestroy() { Log.i("TEST","onDestroy()"); super.onDestroy(); } @Override protected void onHandleIntent(Intent intent) { Log.i("TEST","onHandleIntent():"+android.os.Process.myTid()); if (intent!=null){ String action=intent.getAction(); if(Constans.ACTION_FOR_SUM.equals(action)){ int a=intent.getIntExtra(Constans.A,0); int b=intent.getIntExtra(Constans.B,0); int result=a+b; Log.i("TEST","result: "+result); handleResult(a,result); } } } private void handleResult(int a,int result){ try{ //模擬計算耗時 Thread.sleep(3000); Intent intent=new Intent(Constans.ACTION_RESULT); intent.putExtra(Constans.RESULT,result); intent.putExtra(Constans.A,a); sendBroadcast(intent); }catch (InterruptedException e){ e.printStackTrace();; } } public static void startMyIntentService(Context context,int a,int b){ Intent intent=new Intent(context,MyIntentService.class); intent.setAction(Constans.ACTION_FOR_SUM); intent.putExtra(Constans.A,a); intent.putExtra(Constans.B,b); context.startService(intent); } }

生命週期方法的執行順序

07-08 10:18:51.579 com.troy.intentservicedemo I/TEST: MainActivity:30060 07-08 10:19:26.009 com.troy.intentservicedemo I/TEST: onCreate() 07-08 10:19:26.009 com.troy.intentservicedemo I/TEST: onStartCommand() 07-08 10:19:26.009 com.troy.intentservicedemo I/TEST: onStart() 07-08 10:19:26.039 com.troy.intentservicedemo I/TEST: onHandleIntent():30223 07-08 10:19:26.039 com.troy.intentservicedemo I/TEST: result: 23 07-08 10:19:29.100 com.troy.intentservicedemo I/TEST: onDestroy() 07-08 10:19:31.839 com.troy.intentservicedemo I/TEST: onCreate() 07-08 10:19:31.849 com.troy.intentservicedemo I/TEST: onStartCommand() 07-08 10:19:31.849 com.troy.intentservicedemo I/TEST: onStart() 07-08 10:19:31.869 com.troy.intentservicedemo I/TEST: onHandleIntent():30305 07-08 10:19:31.869 com.troy.intentservicedemo I/TEST: result: 52 07-08 10:19:34.899 com.troy.intentservicedemo I/TEST: onDestroy()

從 log 可以印證三件事

  1. 主線程 ID 是 30060,而 onHandleIntent() 的線程 ID 分別是 30223、30305,可見它確實跑在工作線程上;
  2. 若所有請求落在同一個生命週期內,它們會在同一條工作線程上順序執行,否則會分散到不同線程;
  3. 任務做完而沒有新請求時,Service 會自動停止。

執行結果

三、源碼解析

IntentService 是 Service 的子類,除了繼承所有生命週期方法,還多了一個 ServiceHandler:

public abstract class IntentService extends Service { private volatile Looper mServiceLooper;//volatile關鍵字保證同步,保證可見性 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); } } public IntentService(String name) {//構造方法 super(); mName = name;

一句話概括:IntentService 是 Looper、Handler 與 Service 的集合體,既有服務能力,也有消息循環能力。

onCreate:建立 HandlerThread

@Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }

建立時就開一條 HandlerThread 並啟動,取得它的 Looper 來初始化 mServiceLooper,再用它建立 mServiceHandler。

onStart:把請求包成 Message

@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }

每次啟動服務,就會產生一條帶著 startId 與 Intent 的 Message 放進 MessageQueue,等 Looper 取用。

handleMessage:呼叫我們的實作

@Override public void handleMessage(Message msg) { onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); }

接著呼叫抽象方法 onHandleIntent((Intent)msg.obj),也就是我們實際要覆寫的地方;處理完之後呼叫 stopSelf(msg.arg1) 結束對應的工作。

stopSelf(msg.arg1) 的奧妙

msg.arg1 是一個 int,相當於該請求的唯一標識。每送出一個請求就產生一個標識並排入佇列,只有在「所有請求都已完成」或「目前這個標識正是最後送出的那一個」(也就是 getLastStartId == startId)時,Service 才會銷毀;若傳入 -1 則直接銷毀。這個設計讓「做完最後一筆就收工」得以成立,同時不會誤殺還在排隊的任務。

onDestroy:讓 Looper 停下

@Override public void onDestroy() { mServiceLooper.quit(); }

總結

1、IntentService 是一個基於消息的服務。啟動它不會立刻處理工作,而是先建立 Looper 與 Handler,把帶著 Intent 的 Message 放進佇列,由 Looper 取出後在 onHandleIntent() 中交給你的程式邏輯,全部做完就自我了斷。它的生命週期與任務是一致的,因此特別適合下載這類「做完就该結束」的工作。

2、它不適合以 bindService() 的方式啟動;而透過 startService 多次啟動,就等於往佇列裡塞進多個任務,可以實現依序執行。

3、只有在 onHandleIntent() 中執行的程式碼才真正跑在工作線程上。另外要留意,IntentService 的停止並不是因為 handleMessage() 裡呼叫了 stopSelf,而是系統自己判定的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved