主线程消息队列提供的方法
基本上只要继承自View的控件,都具有消息队列或者handler的一些处理方法,下面是一些handler方法以及被View封装了的方法,其底层用的基本都是handler的api。
举例:查看postDelay的定义
android.view.View
public boolean postDelayed(Runnable action, long delayMillis) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.postDelayed(action, delayMillis); } // Assume that post will succeed later ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); return true; }
通常消息更新的用法如下
方法一
//如果需要延迟更新new Handler().postDelay(new Runnable(){ public void run() { //在主线程更新数据和UI } },2*1000);
方法二
//方案二TextView testTv = (TextView)findViewById(R.id.test_view_handler_tv);testTv.postDelay(new Runnable(){ public void run() { //在主线程更新数据和UI } },2*1000);
两种方案比较,显然第二种更加经济环保。
关于runOnUIThread
Activity中也有一个方法,这个方法发送消息到UI线程,runOnUIThread(Runnable action);
先来看看他的源码实现
java.app.Activity
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
很显然,当方法运行在UI线程上时立即执行,否则发送消息到UI线程之后再执行。
runOnUIThread又为我们省却了创建Handler的异步,比如在多线程中,在子线程中再也不用使用handler发送消息了,完全可以在子线程中调用这个方法来“更新”UI了(注意哦,这里实际上会发送消息和执行代码段到UI线程,并不是在子线程上更新)
Activity.runOnUiThread不可以发送延迟执行的方法,为此我们需要定制可以延迟的runOnUiThread方法
Activity运行时会依附于Window之上,并且在Activity中默认具有根DecorView存在,这个默认根视图无法被覆盖,但他永远存在,座位一个View,为了“多快好省”的原则,我们应该充分利用这个DecorView
如下就是自定义的runOnUiThread:
public void runOnUiThread(Runnable action,int delayMillis) { getWindow().getDecorView().postDelayed(action, delayMillis);}
try doing it!