转自http://www.cnblogs.com/hnrainll/p/3597246.htmlhtml
介绍android
首先咱们来看看为何咱们要使用HandlerThread
?在咱们的应用程序当中为了实现同时完成多个任务,因此咱们会在应用程序当中建立多个线程。为了让多个线程之间可以方便的通讯,咱们会使用Handler
实现线程间的通讯。git
下面咱们看看如何在线程当中实例化Handler
。在线程中实例化Handler
咱们须要保证线程当中包含Looper(注意:UI-Thread默认包含Looper)。oop
为线程建立Looper的方法以下:在线程run()方法当中先调用Looper.prepare()初始化Looper,而后再run()方法最后调用Looper.loop(),这样咱们就在该线程当中建立好Looper。(注意:Looper.loop()方法默认是死循环)post
咱们实现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.ui
尽管HandlerThread
的文档比较简单,可是它的使用并无想象的那么easy。spa
建立一个HandlerThread
,即建立了一个包含Looper的线程。.net
HandlerThread handlerThread = new HandlerThread("leochin.com");线程
handlerThread.start(); //建立HandlerThread后必定要记得start()
获取HandlerThread
的Looper
Looper looper = handlerThread.getLooper();
建立Handler,经过Looper初始化
Handler handler = new Handler(looper);
经过以上三步咱们就成功建立HandlerThread
。经过handler发送消息,就会在子线程中执行。
若是想让HandlerThread
退出,则须要调用handlerThread.quit();
。
Written with LeoChin.