在我的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,但它并没有为我工作,没有运气!
解决方法
在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类简化了很多细节,也是您可以查看的内容.例如,我相信它为您提供了一个线程池,以帮助减轻每次想做背景工作时产生新线程所需的一些成本.