I am trying to create a simple Android application that has a ActivityList of information, when the application starts, I plan to start a Service that will be constantly calculating the data (it will be changing) and I want the ActivityList to be in sync with the data that the service is calculating for the life of the app.
How can I set up my Activity to be listening to the Service? Is this the best way to approach this problem?
For example, if you imagine a list of stock prices - the data would be being changed regularly and need to be in sync with the (in my case) Service that is calculating/fetching the data constantly.
Thanks in advance
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.
You can do this by making your own Interface where you declare for example " isServiceRunning() ". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.
How can I set up my Activity to be listening to the Service? Is this the best way to approach this problem?
You have three major options, as I see it:
Polling. The Activity
periodically asks the Service
for the latest data. IMHO, this option sucks, but it's certainly possible.
Callbacks. Per jax's answer, the Activity
registers a callback object ("observer") with the Service
. The Service
invokes a method on the callback when the data changes, which in turn updates the UI. You can see an example of using that with a Service
here.
Broadcast Intents
. The Service
broadcasts an Intent
via sendBroadcast()
on a data change. The Activity
registers a BroadcastReceiver
using registerReceiver()
, and that BroadcastReceiver
is notified of an incoming broadcast. This triggers the Activity
to load the latest data from the Service
, or possibly just to get the latest data out of extras in the broadcast Intent
. You can see an example of using that technique with a Service
here.
This sound like a good candidate for the Observer Pattern. Basically your activity (The Observer) will register itself with the background service (The Observable) and you can push or pull data from your Activity. Your Observer in this case will be your Activity and the Observable will be your Service.
If you know nothing about Design Patterns buy "Head First Design Patterns", it is easy to read and is full of great information.
PS: I am reading it now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With