HandlerThread的使用方法和原理

来源:互联网 发布:网络侵犯名誉权起诉状 编辑:程序博客网 时间:2024/04/28 03:53

我们如果想要在子线程中使用Handler,必须要手动创建一个Looper(原理已经在前面关于Handler和Looper的博客中介绍过:http://blog.csdn.net/whsdu929/article/details/52487605):

new Thread(){    @Override    public void run() {        Looper.prepare();        Handler handler = new Handler();        Looper.loop();    }}.start();

Android提供了一个HandlerThread类,它继承了Thread,并直接创建好了Looper,因此我们可以直接使用Handler:

HandlerThread handlerThread = new HandlerThread("...");handlerThread.start();//注意使用Handler前必须先调用HandlerThread#start()Handler handler = new Handler(handlerThread.getLooper());

HandlerThread的run()方法源码如下:

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

由于Handler在创建时要使用当前线程的Looper来构建内部的消息处理系统,所以如果当前线程没有Looper,就会报错。而HandlerThread在run方法内部才会创建Looper,因此使用Handler前必须先调用HandlerThread的start()方法


HandlerThread与普通Thread的区别:

普通Thread是在run方法中执行耗时任务,而HandlerThread已经创建好了Looper,即在内部创建了消息队列,需通过Handler发消息来通知HandlerThread去执行一个具体任务,最终的任务处理在Handler的handleMessage方法里。

IntentService的内部实现就是采用了HandlerThread+Handler,详见博客
http://blog.csdn.net/whsdu929/article/details/52514183

1 0