- Handler、Looper和MessageQueue的關(guān)系
- Handler用來處理事件,和發(fā)送事件
- MessageQueue用來存放Handler發(fā)送的Message,一個(gè)MessageQueue可以包含多個(gè)Massage
- Looper用來取事件,交由Handler處理
- 一個(gè)線程對(duì)應(yīng)一個(gè)Looper
- 一個(gè)Looper對(duì)應(yīng)一個(gè)MessageQueue,Looper內(nèi)置一個(gè)MessageQueue對(duì)象
- 一個(gè)Looper可以和多個(gè)Handler綁定
- HandlerThread的使用
HandlerThread繼承自Thread,會(huì)創(chuàng)建一個(gè)looper做消息循環(huán)。
在使用結(jié)束時(shí)應(yīng)該調(diào)用quit()函數(shù)結(jié)束looper
-
使用示例:
private void initThread() { mHandlerThread = new HandlerThread("HandlerThread"); mHandlerThread.start(); mThreadHandler = new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { update(); if (isUpdateInfo) mThreadHandler.sendEmptyMessage(MSG_UPDATE_INFO); } }; } private void update() { try { //模擬耗時(shí) Thread.sleep(2000); mMainHandler.post(new Runnable() { @Override public void run() { String result = "每隔2秒更新數(shù)據(jù)"; result += Math.random(); tvMain.setText(result); } }); } catch (InterruptedException e) { e.printStackTrace(); } }
-
IntentService的實(shí)踐:
- 眾所周知Service是運(yùn)行在主線程的,而Android sdk 基于HandlerThread實(shí)現(xiàn)了一個(gè)運(yùn)行在異步線程的Service——IntentService。
- 源碼展示:
@Override public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }