Android HandlerThread 的使用及其Demo


今天我們一起來學習下一個Android中比較簡單的類HandlerThread,雖然它的初始化有點小麻煩。

介紹

首先我們來看看為什么我們要使用HandlerThread?在我們的應用程序當中為了實現同時完成多個任務,所以我們會在應用程序當中創建多個線程。為了讓多個線程之間能夠方便的通信,我們會使用Handler實現線程間的通信。

下面我們看看如何在線程當中實例化Handler。在線程中實例化Handler我們需要保證線程當中包含Looper(注意UI-Thread默認包含Looper)。

為線程創建Looper的方法如下:在線程run()方法當中先調用Looper.prepare()初始化Looper,然后再run()方法最后調用Looper.loop(),這樣我們就在該線程當中創建好Looper。(注意Looper.loop()方法默認是死循環)

我們實現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.


使用步驟

盡管HandlerThread的文檔比較簡單,但是它的使用並沒有想象的那么easy。

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

    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


引用:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM