从线程更新 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?
}
我检查了 这篇文章 但它对我不起作用,不走运!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Android 应用程序中对 UI 的任何更新都必须在 UI 线程中进行。如果您生成一个线程在后台工作,则必须在触摸视图之前将结果封送回 UI 线程。您可以使用 Handler 类来执行封送处理:
AsyncTask 类为您简化了许多细节,也是您可以研究的内容。例如,我相信它为您提供了一个线程池,以帮助减轻每次您想要执行后台工作时生成新线程相关的一些成本。
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: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.Android 使用处理程序和 sendMessage(msg) 支持消息传递并发。 (也可以使用共享内存并发处理程序。)如果您希望线程在应用程序终止时终止,则一个技巧是调用 thread.setDaemon(true)。另一个技巧是只有一个处理程序,并在消息处理程序中使用 message.what 和 switch 语句来路由消息。
代码和代码
Android supports message-passing concurrency using handlers and sendMessage(msg). (It is also possible to use handlers for shared-memory concurrency.) One tip is to call thread.setDaemon(true) if you wish the thread to die when the app dies. The other tip is to have only one handler and use message.what and a switch statement in the message handler to route messages.
Code and Code