今天我們一起來學習下一個Android中比較簡單的類HandlerThread
,雖然它的初始化有點小麻煩。
介紹
首先我們來看看為什么我們要使用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.
使用步驟
盡管HandlerThread
的文檔比較簡單,但是它的使用並沒有想象的那么easy。
創建一個
HandlerThread
,即創建了一個包含Looper的線程。HandlerThread handlerThread = new HandlerThread("leochin.com");
handlerThread.start(); //創建HandlerThread后一定要記得start()
獲取
HandlerThread
的LooperLooper looper = handlerThread.getLooper();
創建Handler,通過Looper初始化
Handler handler = new Handler(looper);
通過以上三步我們就成功創建HandlerThread
。通過handler發送消息,就會在子線程中執行。
如果想讓HandlerThread
退出,則需要調用handlerThread.quit();
。
測試代碼
引用:
- HandlerThread
- Android HandlerThread
Written with LeoChin.