从线程更新textView

Dro*_*ird 9 multithreading 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?
}
Run Code Online (Sandbox Code Playgroud)

我检查了这篇文章,但它对我不起作用,没有运气!

Cal*_*ico 19

在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);
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

AsyncTask课程为您简化了很多细节,也是您可以研究的内容.例如,我相信它为您提供了一个线程池,以帮助减轻每次要执行后台工作时生成新线程所需的一些成本.