Android:从服务访问单选按钮值
在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行此操作的一种简单方法(假设您的服务与活动在同一进程中运行)是使用共享首选项文件。 每当单选按钮发生更改时,活动就可以写入首选项文件,并且服务可以在首选项上注册侦听器,或者在写入数据库时检查状态。
避免首选项的更复杂的方法是使用 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.