2018.03.16、Android-IntentService學習筆記

Traning發表於2018-03-15

1、IntentService 是什麼?

IntentService是繼承service的一個非同步類,裡面封裝了Handler和HandlerThread,總共也就100多行程式碼。

2、原始碼分析工作原理

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;//訊息傳送的looper
    private volatile ServiceHandler mServiceHandler;// handler
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            //1、接收ServiceHandle發過來的訊息
            //2、通過onHandlerIntent()將訊息發出
            onHandleIntent((Intent)msg.obj);
            //3、服務自己停止
            stopSelf(msg.arg1);
        }
    }


    public IntentService(String name) {
        super();
        mName = name;
    }
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //1、建立子執行緒handlerThread
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();
        //2、獲得 handlerThread裡面的Looper();--->子執行緒
        mServiceLooper = thread.getLooper();
        //3、根據子執行緒提供的looper ,建立Handler
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

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


    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }
    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        //通過bind的方式開啟IntentService,onHandleIntent無法接受訊息。
        return null;
    }
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);
}
    
複製程式碼