zoukankan      html  css  js  c++  java
  • 转:Android View.post(Runnable )

    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

  • 相关阅读:
    从图片中提取html格式的布局
    javascript语法
    2015 9月2日 工作计划与执行
    2015 9月1日 工作计划与执行
    支付模块结构设计
    ubuntu下的pycharm4中文路径乱码
    2015 8月31 工作计划与执行
    25个git进阶技巧 2015-05-12 16:04 34人阅读 评论(0) 收藏
    Model/View框架总体架构 分类: QT学习实践 2015-05-11 22:05 34人阅读 评论(0) 收藏
    用Dom处理XML文件 分类: QT学习实践 2015-05-11 21:16 30人阅读 评论(0) 收藏
  • 原文地址:https://www.cnblogs.com/qingblog/p/2628245.html
Copyright © 2011-2022 走看看