IntentService簡介:
IntentService是一個通過Context.startService(Intent)啟動可以處理異步請求的Service,使用時你隻需要繼承IntentService和重寫其中的onHandleIntent(Intent)方法接收一個Intent對象,該服務會在異步任務完成時自動停止服務. 所有的請求的處理都在IntentService內部工作線程中完成,它們會順序執行任務(但不會阻塞主線程的執行),某一時刻隻能執行一個異步請求。
IntnetService特點:
1.無需自己在Service中開啟一個線程去處理耗時任務。 2.無需自己手動的去停止Service。
IntentService使用示例:
服務端代碼如下:
package com.xjp.broadcast; import android.app.IntentService; import android.content.Intent; import android.util.Log; /** * Description: * User: xjp * Date: 2015/5/4 * Time: 15:47 */ public class MyIntentService extends IntentService { private static final String TAG = "MyIntentService"; /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ public MyIntentService() { super("TEST"); } @Override public void onCreate() { Log.e(TAG, "====onCreate=="); super.onCreate(); } @Override public void onDestroy() { Log.e(TAG, "====onDestroy=="); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "====onStartCommand=="); Log.e(TAG, "====Current Thread Id==" + Thread.currentThread().getId()); return super.onStartCommand(intent, flags, startId); } @Override protected void onHandleIntent(Intent intent) { Log.e(TAG, "====onHandleIntent=="); Log.e(TAG, "====Current Thread Id==" + Thread.currentThread().getId()); /** * 此處模擬耗時任務執行 */ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } int key = intent.getIntExtra("key", 0); Log.e(TAG, "====the key is ==" + key); } }
客戶端代碼如下:
package com.xjp.broadcast; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private Button startService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.startService); startService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent service2 = new Intent(MainActivity.this, MyIntentService.class); service2.putExtra("key", 3); startService(service2); } }); } @Override protected void onResume() { super.onResume(); Intent service = new Intent(this, MyIntentService.class); service.putExtra("key", 1); startService(service); Intent service1 = new Intent(this, MyIntentService.class); service1.putExtra("key", 2); startService(service1); } @Override protected void onDestroy() { super.onDestroy(); } }
啟動應用程序之後,打印如下:
我們發現:啟動瞭兩次服務,執行瞭一次onCreate, 兩次 onStartCommand 且Thread id=1,說明服務是在UI線程執行, 執行瞭兩次 onHandleIntent 且Thread id = 234,說明抽象方法 onHandleIntent 在子線程中執行,因此耗時任務可以在這裡方法裡去執行。且你會發現,當第二個任務執行完之後,打印輸出 onDestory 說明該服務自動停止,無需人為去停止。
為什麼 onHandleIntent 是在子線程中執行呢?什麼時候創建瞭子線程? 為什麼IntentService 可以在 onHandleIntent 執行異步耗時任務?還有任務執行完之後為什麼會自動停止Service??接下來我們從源碼角度解開神秘面紗吧!!!
IntentService 源碼分析:
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.app; import android.content.Intent; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; /** * IntentService is a base class for {@link Service}s that handle asynchronous * requests (expressed as {@link Intent}s) on demand. Clients send requests * through {@link android.content.Context#startService(Intent)} calls; 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 {@link #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. * *
*
Developer Guides
*
For a detailed discussion about how to create services, read the * Services developer guide.
*
* * @see android.os.AsyncTask */ public abstract class IntentService extends Service { private volatile Looper mServiceLooper; 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); } } /** * 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; } /** * Sets intent redelivery preferences. Usually called from the constructor * with your preferred semantics. * *
If enabled is true, * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_REDELIVER_INTENT}, so if this process dies before * {@link #onHandleIntent(Intent)} returns, the process will be restarted * and the intent redelivered. If multiple Intents have been sent, only * the most recent one is guaranteed to be redelivered. * *
If enabled is false (the default), * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent * dies along with it. */ public void setIntentRedelivery(boolean enabled) { mRedelivery = enabled; } @Override 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); } @Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); } /** * 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; } @Override public void onDestroy() { mServiceLooper.quit(); } /** * Unless you provide binding for your service, you don't need to implement this * method, because the default implementation returns null. * @see android.app.Service#onBind */ @Override public IBinder onBind(Intent intent) { return null; } /** * 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); }
我們看源碼的第 107–111行: IntentService內部實現瞭一個 HandlerThread 帶有循環消息處理機制的線程。關於 HandlerThread 的原理和使用方法,請參考Android HandlerThread 源碼分析 。因此,IntentService 內部其實也實現瞭一個帶有循環消息處理機制的線程。看看我們客戶端的耗時任務是怎麼傳給 IntentService 的內部 HandlerThread 線程執行的呢? 我們每啟動一次服務就執行一次 onStartCommand。
我們看源碼的130行: 調用瞭 onStart方法。
我們看源碼的115–120行: onStart方法的實現, 在這個方法中,我們封裝客戶端傳遞過來的 Intent,將之通過 Handler + Message 消息處理機制 mServiceHandler.sendMessage(msg); 傳遞給 HandlerThread子線程去執行客戶端的耗時任務。 我們看看 mServiceHandler 的實現
源碼第58–68行: 實現瞭 mServiceHandler,構成瞭一個 Handler + Message + Looper 循環消息處理機制。
源碼第65行: 調用瞭 帶客戶端的Intent消息參數的 onHandlerIntent 抽象方法,該抽象方法留給子類去實現相應的 異步耗時任務。因此,我們繼承的IntentService 子類 必須實現 onHandlerIntent抽象方法。
源碼第 66 行: 調用瞭stopSelf()方法,當異步任務執行完之後,自動停止Servvice。因此,我們客戶端無需自己去手動停止Service。
IntentService 總結:
IntentService 分析完畢, 1.其實內部就是實現瞭一個 HandlerThread+Handler 帶有循環消息處理機制的線程去處理後臺的耗時任務,無需用戶去實現一個線程執行耗時任務。 2.並且任務執行之後 會自動 調用stopSelf停止服務,無需客戶端去手動管理服務,客戶端隻需在需要執行異步後臺耗時任務時,再次啟動任務即可。 3.如果對 HandlerThread有所瞭解的童鞋就會知道,為什麼 IntentService 執行異步任務都是順序的,且一個時刻隻能執行一個任務。因為HandlerThread + Handler 是一個單一的工作線程,也就是說,當客戶端同時投放倆個異步任務時,隻有前一個任務完成之後才能執行下一次任務,第二個任務是會阻塞等待的。不過是在子線程中執行,不會影響UI線程,也就不會出現ANR.