从服务中的线程更改主活动 UI
我一直在寻找一些好的文档或一个很好的例子。我需要从后台运行的服务中的工作线程更改我的主要活动 UI。据我了解,我知道我应该使用某种处理程序,但我不确定如何处理这个问题。
有没有人有任何想法或好的例子可以指导我?我正在更改的 UI 元素是一个 TextView,它只是通知用户线程的状态。
感谢您的帮助。
I've been looking for quite some time for some good documentation or a good example of this. I need to make changes to my main activity UI from the worker thread in my service which is running in the background. As far as I understand I know that I am suppose to work with some sort of Handler but I am not sure exactly how to approach this.
Does anyone have any ideas or good examples that they could direct me to? The UI element I am changing is a TextView that is simply informing the user of the status of the thread.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您所要做的就是在 UI 线程上创建一个
Handler
:然后将其传递给您的服务。您可以在服务中拥有这样的函数:
然后像这样传递处理程序:
然后发回消息:
All you have to do is to create a
Handler
on the UI thread:And then pass this through to your service. You could have a function in the Service like this:
and then pass the handler through like this:
then to send a message back:
查看服务绑定。或者您可以在主要活动中使用 BroadcastReceiver 来接收来自 Service 的广播。
Look into Service Binding. Or you could use BroadcastReceiver in your main activity to receive broadcasts from Service.
您必须使用 sendBroadcast(intent) 从您的服务发送意图,并在您的活动中设置 BroadcastReceiver
You have to send an intent from your service with sendBroadcast(intent) and set a BroadcastReceiver in your activity
在主活动的 onCreate() 方法中创建一个处理程序。这将在 UI 线程中创建一个处理程序。然后从工作线程使用此处理程序,调用您需要的任何内容来更新 TextView。
Create a handler in onCreate() method in your main activity. This will create a handler in the UI thread. Then using this handler from the worker thread, call whatever you need to to get the TextView updated.