Android:从服务访问单选按钮值

发布于 2024-07-15 20:00:11 字数 177 浏览 7 评论 0原文

在我的 Android 应用程序中,服务在后台运行,并将GPS 读数记录到数据库。 用户会看到一个带有单选按钮的 Activity。 我还想将他们当前选择的单选按钮记录到数据库中。

如何从服务访问单选按钮对象?

In my Android app, a service runs in the background and it logs GPS readings to a database. The user sees an Activity that presents them with radio buttons. I'd like to also log their currently selected radio button to the database.

How can I access the radio button object from the Service?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

梓梦 2024-07-22 20:00:11

执行此操作的一种简单方法(假设您的服务与活动在同一进程中运行)是使用共享首选项文件。 每当单选按钮发生更改时,活动就可以写入首选项文件,并且服务可以在首选项上注册侦听器,或者在写入数据库时​​检查状态。

避免首选项的更复杂的方法是使用 Context.startService() 启动服务(这样即使 Activity 不在身边,它仍然保持运行),然后让 Activity 调用 Context.bindService() (启动服务(如果它没有运行)返回一个可以与之通信的 IBinder 存根。 对于这种方法,我建议您查看 服务 API 演示

One easy method of doing this (assuming your Service runs in the same process as the Activity) is to use a shared preferences file. The activity can write to the preferences file whenever a radio button is changed, and the Service can either register a listener on the preferences or check the state whenever writing to the database.

The more complicated way which avoids preferences would be for the service to be started with Context.startService() (so that it remains running even if the Activity is not around) and then for the Activity to call Context.bindService() (starting the service if it is not running) to return an IBinder stub it can communicate with. For this approach, I recommend you look at the Service API Demos.

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