views:

267

answers:

2

My application uses a remote service to play audio. I do this so that no activity owns the playback of the audio - the user can trigger some audio to be played from one Activity, and the audio will continue to play as they navigate around the app. I do, however, want to tell the service to pause or stop playing audio when the user "unloads" the app either by backing out, locking the display, or hitting Home. When the app was a single activity, I was doing this in onPause. So, I guess I'm essentially looking for "onPause" at the application/task level. Does such thing exist? If not, what is the "best practice" way of getting notified that the task has been put on hold by the user either backing all the way out or hitting Home?

+2  A: 

Hmmmm...unfortunately, I suspect there's no easy answer there. I think that's why the built-in media player and Pandora use a notification, to easily let the user get back to the app to make it shut up.

If your activity flow is fairly linear, then backing out of the application is the same as backing out of the initial activity.

A trick I used in one scenario was to have each activity notify the service in onPause() and onResume(). The service would monitor these, and if it got an onPause() without a subsequent onResume() in some period of time, it was assumed the user was gone (HOME, incoming phone call, incoming text message, responding to some app via a notification, etc.).

You can also watch for ACTION_SCREEN_OFF broadcast Intents, to handle that scenario.

I am sorry that I don't have a better silver bullet answer -- perhaps somebody else will have a better idea.

CommonsWare
Those are some creative solutions. I have a similar issue, that if answered could combine with your solution to be perfect for me. I might just go with the ACTION_SCREEN_OFF as well...great suggestion.Please let me know what you think of the following:http://stackoverflow.com/questions/1735245/overriding-the-activity-task-behavior-in-androidThanks!
Rich
Sorry, I don't mess with activity stacks.
CommonsWare
No worries. My solution will end up being one or the other of what you suggested (notification like Pandora or maintain activity state in the service and listen for the appropriate broadcast(s)).
Rich
+1  A: 

I have been in a somewhat similar situation, and essentially I did what Mark suggested; Rather than a separate notification, I simply had the service count the calls to my registerCallback() and unregisterCallback() APIs, which each activity needed to do anyway.

miracle2k