从线程更新textView [英] Update textView from thread
问题描述
在我的OnCreate方法中,我创建了一个侦听传入消息的线程!
In my OnCreate method I have created a thread that listens to incoming message!
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?
}
我查看了这篇文章,但是它对我不起作用,没有运气!
I checked this article but it did not work for me, no luck!
推荐答案
在Android应用程序中对UI进行的任何更新都必须在UI线程中进行.如果您在后台生成线程以进行工作,则必须在触摸视图之前将结果编组回UI线程.您可以使用Handler
类执行封送处理:
Any updates to the UI in an Android application must happen in the UI thread. If you spawn a thread to do work in the background you must marshal the results back to the UI thread before you touch a View. You can use the Handler
class to perform the marshaling:
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
类为您简化了许多细节,这也是您可以研究的内容.例如,我相信它为您提供了一个线程池,以帮助减轻每次您要进行后台工作时产生新线程所带来的一些成本.
The AsyncTask
class simplifies a lot of the details for you and is also something you could look into. For example, I believe it provides you with a thread pool to help mitigate some of the cost associated with spawning a new thread each time you want to do background work.
这篇关于从线程更新textView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!