Android IntentService 源碼分析

來源:互聯網
上載者:User

標籤:intentservice   handlerthread   源碼   

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. * * <p>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. * * <p>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. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For a detailed discussion about how to create services, read the * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p> * </div> * * @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.     *     * <p>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.     *     * <p>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.

Android IntentService 源碼分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.