从线程更新的TextView!请帮忙! [英] Update textView from thread! Please help!
问题描述
在我的OnCreate方法,我创建了一个线程监听传入的消息! 主线程发送出去......。(无意义的讨论)
In my OnCreate method I have created a thread that listens to incoming message! Main thread is for sending out….(meaningless for this discussion)
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?
}
我检查了这一点, <一href="http://www.helloandroid.com/tutorials/using-threads-and-progressdialog">http://www.helloandroid.com/tutorials/using-threads-and-progressdialog 但是,并没有为我工作,没有运气!
I checked this, http://www.helloandroid.com/tutorials/using-threads-and-progressdialog But, did not work for me, no luck!
如果你愿意回答,请更多的话回答,或明显的例子,我是新的!
If you are willing to reply, please reply in more words, or clear example, I am new!
推荐答案
任何更新UI的Android应用程序必须发生在UI线程。如果你产生一个线程做的工作在后台,你必须元帅的结果返回给UI线程,你倒好查看之前。您可以使用处理程序
类来执行编组:
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屋!