How does controller listen to service?
-
Polling. The Controller periodically asks the
Servicefor the latest data. IMHO, this option sucks, but it's certainly possible. -
Callbacks. The
Controllerregisters a callback object ("observer") with theService. TheServiceinvokes a method on the callback when the data changes, which in turn updates the UI. You can see an example of using that with aServicehere. -
Broadcast
Intents. TheServicebroadcasts anIntentviasendBroadcast()on a data change. TheControllerregisters aBroadcastReceiverusingregisterReceiver(), and thatBroadcastReceiveris 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.
浙公网安备 33010602011771号