Is there a way that a Service can report back to the calling activity when the Service has reac开发者_如何学Gohed a particular stage of processing?
For eg: Consider a music player activity that initiates the actual music playing in the background as an Android Service. I want to detect and inform the Activity when the Service has reached the Mediaplayer's onPrepared. Is there a way that the Service can tell the calling Activity when the MediaPlayer's onPrepared is called, to let the Activity know that the audio is prepared and ready to play?
I am basically looking to see if there is work around, rather than having a thread in the activity, pinging constantly to check if the Service has reached onPrepared.
Thanks Chris
The easiest way I found is to use a LocalBroadcast, which is available in the support library. Here is an example:
In your service:
String action = "status"; // arbitrary string
private void updateStatus(){
Intent intent = new Intent(action);
// fill the intent with other variables you want to pass
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
In your activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager.getInstance(context).registerReceiver(receiver,new IntentFilter(action));
}
@Override
protected void onResume() {
LocalBroadcastManager.getInstance(context).registerReceiver(receiver,new IntentFilter(action));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
}
String action = "status";
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if(intentAction.equals(action){
// Process the status from the service
}
}
};
You can always use interfaces to communicate between activitie(s) and service. Right after you have connected to the service you set your interface to it and if service gets to some state that you want it to communicate back to the activity you just call out the appropriate method for it.
You can pass interfaces as parceables in your launch Intent. Check the source for Google I/O 2010 app like this question.
精彩评论