从服务中的线程更改主活动 UI

发布于 2024-12-02 23:14:51 字数 174 浏览 0 评论 0原文

我一直在寻找一些好的文档或一个很好的例子。我需要从后台运行的服务中的工作线程更改我的主要活动 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小耗子 2024-12-09 23:14:51

您所要做的就是在 UI 线程上创建一个 Handler

private Handler serviceHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        someFunctionInTheUIThread();
    }
};

然后将其传递给您的服务。您可以在服务中拥有这样的函数:

public void registerHandler(Handler serviceHandler) {
    handler = serviceHandler;
}

然后像这样传递处理程序:

theService = ((LocalBinder) service).getService();
theService.registerHandler(serviceHandler);

然后发回消息:

Message msg = handler.obtainMessage(IDENTIFIER, "Message or data");
handler.sendMessage(msg);

All you have to do is to create a Handler on the UI thread:

private Handler serviceHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        someFunctionInTheUIThread();
    }
};

And then pass this through to your service. You could have a function in the Service like this:

public void registerHandler(Handler serviceHandler) {
    handler = serviceHandler;
}

and then pass the handler through like this:

theService = ((LocalBinder) service).getService();
theService.registerHandler(serviceHandler);

then to send a message back:

Message msg = handler.obtainMessage(IDENTIFIER, "Message or data");
handler.sendMessage(msg);
×纯※雪 2024-12-09 23:14:51

查看服务绑定。或者您可以在主要活动中使用 BroadcastReceiver 来接收来自 Service 的广播。

Look into Service Binding. Or you could use BroadcastReceiver in your main activity to receive broadcasts from Service.

一笔一画续写前缘 2024-12-09 23:14:51

您必须使用 sendBroadcast(intent) 从您的服务发送意图,并在您的活动中设置 BroadcastReceiver

You have to send an intent from your service with sendBroadcast(intent) and set a BroadcastReceiver in your activity

╰沐子 2024-12-09 23:14:51

在主活动的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文