HandlerThread和IntentService

HandlerThread异步


为何要使用HandlerThread?ide

咱们常常使用的Handler来处理消息,其中使用Looper来对消息队列进行轮询,而且默认是发生在主线程中,这可能会引发UI线程的卡顿,因此咱们用HandlerThread来替代。。。oop

 

HanderThread实际上就是一个线程this

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

 

获取Looper的时候,若是还没建立好,会进行等待。。。spa

 public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

使用方法:线程

      HandlerThread thread=new HandlerThread("hello");
        thread.start();//必须得先start
        Handler handler=new Handler(thread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //发生hello线程中。。。。
               
                return false;
            }
        });

        handler.sendEmptyMessage(0);

 

为何须要使用IntentService?code


Service里面咱们确定不能直接进行耗时操做,通常都须要去开启子线程去作一些事情,本身去管理Service的生命周期以及子线程并不是是个优雅的作法;好在Android给咱们提供了一个类,叫作IntentServiceblog

意思说IntentService是一个基于Service的一个类,用来处理异步的请求。你能够经过startService(Intent)来提交请求,该Service会在须要的时候建立,当完成全部的任务之后本身关闭,且请求是在工做线程处理的。生命周期

这么说,咱们使用了IntentService最起码有两个好处,一方面不须要本身去new Thread了;另外一方面不须要考虑在何时关闭该Service了。队列

内部实现仍是使用的HandlerThread

    @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);
    }
    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(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
相关文章
相关标签/搜索