首页 > 移动平台 > 详细

Android线程间通信

时间:2014-04-02 19:41:31      阅读:565      评论:0      收藏:0      [点我收藏+]

Android采用UI单线程模型,所以工作线程(非UI线程)与UI线程的通信是不可避免的。工作线程与UI主线程通信(进行更新UI等操作)主要有以下三种方式。

First :

Looper.getMainLooper()


    Runnable task = getTask();

    new Handler(Looper.getMainLooper()).post(task);


Second :

Activity#runOnUiThread()


    Runnable task = getTask();

    runOnUiThread(task);


The implements of runOnUiThread is shown as bellow :

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}
It will check if the current Thread is already the UI thread and then execute it directly. Posting it as a message will delay the execution until you return from the current UI-thread method.


Third:

There is also a third way to execute a Runnable on the UI thread which would be View#post(Runnable) - this one will always post the message even when called from the UI thread. That is useful since that will ensure that the View has been properly constructed and has a layout before the code is executed.

Android线程间通信,布布扣,bubuko.com

Android线程间通信

原文:http://blog.csdn.net/handsome3/article/details/22807125

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!