How does controller listen to service?

  1. Polling. The Controller periodically asks the Service for the latest data. IMHO, this option sucks, but it's certainly possible.

  2. Callbacks. The Controller registers a callback object ("observer") with theService. 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.

  3. Broadcast Intents. The Service broadcasts an Intent via sendBroadcast() on a data change. The Controller registers a BroadcastReceiver using registerReceiver(), and that BroadcastReceiver is notified of an incoming broadcast. This triggers the Controller 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

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.

posted @ 2013-10-25 11:17  MinieGoGo  阅读(134)  评论(0编辑  收藏  举报