idleHandler
什麼是idleHandler
Android是基於Looper消息循環的系統,我們通過Handler向Looper包含的MessageQueue投遞Message,在MessageQueue中我們可以看到這樣的一個接口
/** * Callback interface for discovering when a thread is going to block * waiting for more messages. */ public static interface IdleHandler { /** * Called when the message queue has run out of messages and will now * wait for more. Return true to keep your idle handler active, false * to have it removed. This may be called if there are still messages * pending in the queue, but they are all scheduled to be dispatched * after the current time. */ boolean queueIdle(); }
從信息描述可以看到在Looper裏面的Messsage暫時處理完了,這個時候會回調這個接口,即 ”idle“,
返回值
如果返回false用完就會移除這個接口,相當於使用一次,後面這個消息就從隊列移除了
返回true就會保留,在下次Looper空閒時繼續處理。比如在主線程return true,就會出現一直輪詢
作用
從上面可以看出,這個僅僅是在消息隊列暫時處理完會調用這個回調,那麼就有下面兩種場景可以使用
UI線程 即主線程
用法
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() { @Override public boolean queueIdle() { /*dosometing*/ return false; } });
actvity中UI繪製完全結束時機
onStart是用戶可見,onResume是用戶可交互,此時繪製不一定完成了,而idler等到這些都完成了,再去執行自己,因此 我們獲取一些寬高可以在這裏做。
提升性能
在做性能優化時候,可以錯開執行消息隊列,將一些耗時操作放到這裏執行,比如我們國際化司機端,首頁有個Google地圖,還有一些出車文字滾動和波紋動畫之類的,此時就可以將出車動畫放在idleHanlder中,讓底圖先渲染。
自定義Looper 如HandlerThread
除了主線程之外,我們也可以自定義自己的Looper去處理,這時候可以讓自己Looper關聯上idlerHandler在Looper消息處理完時再去處理其他的東西,
MessageQueue messageQueue = handlerThread.getLooper().getQueue(); messageQueue.addIdleHandler(new MessageQueue.IdleHandler() { @Override public boolean queueIdle() { return true; } });
比如在單線程異步場景中,多次快速數據,但是隻需要顯示一次,就可以使用這種方式
注意點
要是有強時序性的操作最好不好放到這裏處理,容易出問題
參考