从线程更新textView

时间:2011-03-23 02:42:08

标签: android multithreading 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,但它对我不起作用,没有运气!

2 个答案:

答案 0 :(得分: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);
            }
        });
}

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

答案 1 :(得分:0)

Android支持使用处理程序和sendMessage(msg)进行消息传递并发。 (也可以使用处理程序进行共享内存并发。)如果您希望线程在应用程序死亡时死亡,则可以调用thread.setDaemon(true)。另一个提示是只有一个处理程序,并使用message.what和消息处理程序中的switch语句来路由消息。

CodeCode