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 essentiall开发者_运维知识库y 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?
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.
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.
精彩评论