How does controller listen to service?
-
Polling. The Controller periodically asks the
Service
for the latest data. IMHO, this option sucks, but it's certainly possible. -
Callbacks. The
Controller
registers a callback object ("observer") with theService
. TheService
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 aService
here. -
Broadcast
Intents
. TheService
broadcasts anIntent
viasendBroadcast()
on a data change. TheController
registers aBroadcastReceiver
usingregisterReceiver()
, and thatBroadcastReceiver
is notified of an incoming broadcast. This triggers the Controller to load the latest data from theService
, or possibly just to get the latest data out of extras in the broadcastIntent
. You can see an example of using that technique with aService
e.g.
Your onReceive()
method in the BroadcastReceiver
gets a Context
passed, use that.
@Override publicvoid onReceive(Context context,Intent intent){ db = newDatabase(context);//more stuff }
Also be aware that inside a BroadcastReceiver
, you are only guaranteed 10 seconds of execution time, after that, Android may kill your Receiver. So be quick with what you're doing and if the database operation is lengthy, consider using a separate Thread
.