Thursday, April 14, 2011

Android: accessing radio button values from a service

In my Android app, a Service runs in the background and 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?

From stackoverflow
  • 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.

0 comments:

Post a Comment