1. 程式人生 > >轉:Android中IntentService與Service的區別

轉:Android中IntentService與Service的區別

https://blog.csdn.net/matrix_xu/article/details/7974393

Android中的Service是用於後臺服務的,當應用程式被掛到後臺的時候,問了保證應用某些元件仍然可以工作而引入了Service這個概念,那麼這裡面要強調的是Service不是獨立的程序,也不是獨立的執行緒,它是依賴於應用程式的主執行緒的,也就是說,在更多時候不建議在Service中編寫耗時的邏輯和操作,否則會引起ANR。

那麼我們當我們編寫的耗時邏輯,不得不被service來管理的時候,就需要引入IntentService,IntentService是繼承Service的,那麼它包含了Service的全部特性,當然也包含service的生命週期,那麼與service不同的是,IntentService在執行onCreate操作的時候,內部開了一個執行緒,去你執行你的耗時操作。

這裡我 需要解釋以下幾個方法,也許大家都已經很清楚了,不過為了拋磚引玉,我還是要提一嘴。

Service中提供了一個方法:

   public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
    }

這個方法的具體含義是,當你的需要這個service啟動的時候,或者呼叫這個servcie的時候,那麼這個方法首先是要被回撥的。

同時IntentService中提供了這麼一個方法:

protected abstract void onHandleIntent(Intent intent);
這是一個抽象方法,也就是說具體的實現需要被延伸到子類。

子類的宣告:

public class ChargeService extends IntentService 
上面提到過IntentService是繼承Service的,那麼這個子類也肯定繼承service,那麼onHandleIntent()方法是什麼時候被呼叫的呢?讓我們具體看IntentService的內部實現:

    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);
    }

在這裡我們可以清楚的看到其實IntentService在執行onCreate的方法的時候,其實開了一個執行緒HandlerThread,並獲得了當前執行緒佇列管理的looper,並且在onStart的時候,把訊息置入了訊息佇列,

 @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
在訊息被handler接受並且回撥的時候,執行了onHandlerIntent方法,該方法的實現是子類去做的。

結論:

IntentService是通過Handler looper message的方式實現了一個多執行緒的操作,同時耗時操作也可以被這個執行緒管理和執行,同時不會產生ANR的情況。
--------------------- 
作者:matrix_xu 
來源:CSDN 
原文:https://blog.csdn.net/matrix_xu/article/details/7974393 
版權宣告:本文為博主原創文章,轉載請附上博文連結!