Android View.post(Runnable )



http://www.cnblogs.com/qingblog/archive/2012/08/08/2628245.html

http://www.cnblogs.com/qingblog/archive/2012/08/08/2628245.html

http://www.cnblogs.com/qingblog/archive/2012/08/08/2628245.html

http://www.cnblogs.com/qingblog/archive/2012/08/08/2628245.html


Runnable 并不一定是新开一个线程,比如下面的调用方法就是运行在UI主线程中的:

     Handler mHandler=new Handler(); 
     mHandler.post(new Runnable(){ 
        @Override public void run() 
        { // TODO Auto-generated method stub 
         } 
     });

官方对这个方法的解释如下,注意其中的:“The runnable will be run on the user interface thread. ”

boolean android.view.View .post(Runnable action)

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.

Parameters:

action The Runnable that will be executed.

Returns:

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

我们可以通过调用handler的post方法,把Runnable对象(一般是Runnable的子类)传过去;handler会在looper中调用这个Runnable的Run方法执行。

Runnable是一个接口,不是一个线程,一般线程会实现Runnable。所以如果我们使用匿名内部类是运行在UI主线程的,如果我们使用实现这个Runnable接口的线程类,则是运行在对应线程的。

具体来说,这个函数的工作原理如下:

View.post(Runnable)方法。在post(Runnable action)方法里,View获得当前线程(即UI线程)的Handler,然后将action对象post到Handler里。在Handler里,它将传递过来的action对象包装成一个Message(Message的callback为action),然后将其投入UI线程的消息循环中。在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnable的run方法。而此时,已经路由到UI线程里,因此,我们可以毫无顾虑的来更新UI。

如下图,前面看到的代码,我们这里Message的callback为一个Runnable的匿名内部类

这种情况下,由于不是在新的线程中使用,所以千万别做复杂的计算逻辑。

image






android中handler.post();和view.post();有经验的开发者受累解答下~~~

2012-11-22 21:29  提问者悬赏: 10分  | 匿名  |  分类:网站使用  |  浏览1867次
android中handler.post();和view.post();方法可以用来刷新ui线程
我看了下源码,发现view.post()方法内会创建一个handler,并调用handler.post(),感觉要是这样的话,用view.post在代码编写上会省事,不用自己去new handler,但是感觉平常用的最多的是handler,我想问下这两个在用法上有什么区别?什么情况下只能用handler而不能用view.post
另外,handler和AsyncTask分别在哪种情况下用?用哪个好?
麻烦有经验的朋友详细解释下,谢谢!
2012-11-23 13:27 网友采纳
核心原理一致的

前面是你自己创建、后面是view的内部帮你完成






 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值