Android App开发中界面显示正常情况下要么时获取网络数据或者数据库之后再显示界面,要么时等Ui绘制完成之后再渲染展示数据。这两种情况下UI 控件初始化必须先行,然后再异步获取数据,获取成功之后,再Ui渲染数据。这是一个串行的流程,如果可以把UI控件初始化和异步获取数据并行,甚至先行获取,等Ui控件完成之后再通知UI渲染数据,那就会在不修改业务代码的前提下得到大大的提升界面展示速度。下面介绍如何得到UI渲染结束时机,如何利用MessageQueue的同步障碍机制来实现通知消息机制中断和继续执行。
UI渲染时机回调,没有系统的生命周期回调,在前面的文章中又提到分析源码了解View.post机制实现获取View的尺寸。
1、IdleHandler
可以用来再UI线程Looper空闲的时候,进行任务,避免阻塞UI绘制,以及在单独的消息循环机制中来实现空闲时机回调。
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();
}