轉自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.