HandlerThread 与 IntentService

HandlerThread

HandlerThread简述

1.HandlerThread本身是个Thread
2.run时会创建Looper,并进行loop
3.一个线程可以执行多个有序的耗时任务

HandlerThread核心代码解析

    @Override
    public void run() {
        mTid = Process.myTid();
        //当前线程绑定了Looper
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        //子线程中一直进行消息队列循环
        Looper.loop();
        mTid = -1;
    }

IntentService

IntentService简述

1.IntentService本身是个Service
2.onHandleIntent执行在子线程
3.任务完成会自动关闭服务

IntentService核心代码解析

@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
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        //启动HandlerThread,这时候回监听消息队列
        thread.start();
        //使用的是HandlerThread的Looper
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    //这里的handleMessage将会在HandlerThread中的run方法中执行,所以IntentService会自动在子线程中执行任务
    //而不用担心ANR
    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);
        }
    }
    //启动服务就是发送一个消息
    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
    //通过Bind方式启动和start方式是一样的
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }
    //自动销毁且退出Looper
    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

你可能感兴趣的:(HandlerThread 与 IntentService)