android – 从线程更新textView

在我的OnCreate方法中,我创建了一个线程来监听收到的消息!
In OnCreate() {

//Some code

myThread = new Thread() {

            @Override

            public void run() {

                receiveMyMessages();

            }
        };
myThread.start();

// Some code related to sending out by pressing button etc.

}

Then,receiveMyMessage() functions…

Public void receiveMyMessage()
{

//Receive the message and put it in String str;

str = receivedAllTheMessage();

// <<    here I want to be able to update this str to a textView. But,How?
}

我检查了this article,但它并没有为我工作,没有运气!

解决方法

在Android应用程序中对UI的任何更新都必须在UI线程中进行.如果您在后台生成线程来进行工作,则必须在触摸视图之前将结果编组回UI线程.您可以使用Handler类执行编组:
public class TestActivity extends Activity {
    // Handler gets created on the UI-thread
    private Handler mHandler = new Handler();

    // This gets executed in a non-UI thread:
    public void receiveMyMessage() {
        final String str = receivedAllTheMessage();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // This gets executed on the UI thread so it can safely modify Views
                mTextView.setText(str);
            }
        });
}

AsyncTask类简化了很多细节,也是您可以查看的内容.例如,我相信它为您提供了一个线程池,以帮助减轻每次想做背景工作时产生新线程所需的一些成本.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...