I have a service which is checking for new task all the time. If there is new task, I want to refresh the activity UI to show that info.
I did find https://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/ this example. Is that a good approch ? Any other examples?
Thanks.
See below for my original answer – that pattern has worked well, but recently I’ve started using a different approach to Service/Activity communication:
reference to the Service, thus allowing direct calls on it, rather
than using Intents.
Use RxJava to execute asynchronous operations.
If the Service needs to continue background operations even when no
Activity is running, also start the service from the Application
class so that it does not get stopped when unbound.
The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are
Some example code. First the service:
And an Activity that binds to the service and receives pressure altitude updates:
The layout for this Activity is:
If the service needs to run in the background without a bound Activity it can be started from the Application class as well in
OnCreate()usingContext#startService().My Original Answer (from 2013):
In your service: (using COPA as service in example below).
Use a LocalBroadCastManager. In your service’s onCreate, set up the broadcaster:
When you want to notify the UI of something:
In your Activity:
Create a listener on onCreate:
and register it in onStart: