Android HandlerThread的使用

来源:互联网 发布:mac克隆失败是什么意思 编辑:程序博客网 时间:2024/06/06 21:38

一,使用HandlerThread

1,创建一个HandlerThread,即创建了一个包含Looper的线程

HandlerThread handlerThread = new HandlerThread("zcn.com");handlerThread.start();     //创建HandlerThread后一定要记得start()

2,获取HandlerThread的Looper

Loopper looper = handlerThread.getLooper();

3,创建Handler,通过Looper初始化

Handler handler = new Handler(looper);

通过以上三步我们就成功创建HandlerThread,通过handler发送消息,就会在子线程中执行。
如果想让HandlerThread退出,则需要调用handlerThread.quit();

二,为什么要用HandlerThread

在我们应用程序当中为了实现同时完成多个任务,所以我们会在应用程序当中创建多个线程,为了让多个线程之间能够方便的通信,我们会用Handler实现线程间的通信。

如何在线程中实例化Handler,在线程中实例化Handler我们需要保证线程中包含Looper
注:UI-Thread默认包含Looper

为线程创建Looper的方法如下:
在线程run()方法中先调用Looper.prepare()初始化Looper,然后再run()方法最后调用Looper.loop(),这样我们就在该线程中创建好Looper(注:Looper.loop()方法默认是死循环)我们实现Looper有没有更加简单的方法呢?
当然有,这就是HandlerThread,我们来看一下Android对HandlerThread的描述。
Handy class for starting a new thread that has a looper,the looper can then be used to create handler classes.Note that start() must still be called.