在我的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,但它对我不起作用,没有运气!
答案 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)