My application has some background music playing on a loop, using a MediaPlayer
. I stop the music in the onPause
of the Activity so it doesn't keep on playing if the user leaves the application by pressing the Home key, or if they receive a phone call, etc.
However, I now need the music to continue playing seamlessly when the user moves to certain other activities. That is, if they press button A then I add activity A to the stack and the music should continue; however if they press button B then I add activity B to the stack and the music should stop. Similarly the music should continue if they press the phone's Back button to return from activity A to the original activity.
I've tried starting the MediaPlayer
again in the onResume
of Activity A, but there's quite a noticeable gap in the music during the transition.
At the moment I've got onPause
triggering a half-second delay before fading the music out over another quarter of a second; this can be cancelled from within another activity's onResume
. This means the music stops just about quickly enough when the user's leaving the app; however when the user switches activities I still get a slight pause in the music on some slower devices. Furthermore it feels like a really dirty hack.
Is there a better way?
[Edit: if it helps, the MediaPlayer
is held in a static class that I can access from anywhere in the application.]
The simplest solution that I can think of offhand if I needed to get this done would be to set a static flag variable in my global Application
object (let's call it sStartingNewActivity
). Wherever I'm starting an intent new activity (or pressing "back" from an activity that isn't the entry point, overriding the onBackPressed
method), I'd set that value to true
, and have onPause
not stop the music if that flag is set. I'd set the value back to false
in every activity's onCreate
. I don't think a 1-2-second-pause-before-fadeout is a bad way to go, though -- that would actually behave pretty similarly to how it works when the user presses the "home" button in an iOS app that has background music.
EDIT: You can also try a service-based solution that "sniffs" for whether your activities are running by having your activities listen for a specific broadcast; there's some sample code online that I haven't tried but it's an interesting approach).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With