Android HandlerThread 的使用及其Demo (轉)

轉自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。咱們來看下AndroidHandlerThread的描述:測試

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

  1. 建立一個HandlerThread,即建立了一個包含Looper的線程。.net

    HandlerThread handlerThread = new HandlerThread("leochin.com");線程

    handlerThread.start(); //建立HandlerThread後必定要記得start()

  2. 獲取HandlerThread的Looper

    Looper looper = handlerThread.getLooper();

  3. 建立Handler,經過Looper初始化

    Handler handler = new Handler(looper);

經過以上三步咱們就成功建立HandlerThread。經過handler發送消息,就會在子線程中執行。

若是想讓HandlerThread退出,則須要調用handlerThread.quit();


測試代碼

HandlerThreadDemo


引用:

相關文章
相關標籤/搜索