Hello! First time to ask a question here at stackoverflow. Exciting! Haha.
We're developing an Android game and we play some background music for our intro (we have an Intro Activity) but we want it to continue playing to the next Activity, and perhaps be able to stop or play the music again from anywhere within the application.
What we're doing at the moment is play the bgm using MediaPlayer at our Intro Activity. However, we stop the music as soon as the user leaves that Activity. Do we have to use something like Services for this? Or is MediaPlayer/SoundPool enough? If anyone knows the answer, we'd gladly appreciate your sharing it with us. Thanks!
First i used the method where to keep a "keepMusicPlaying" flag provided by Chad. I think its more elegant to just use the onStart and onStop methods of your activitys.
Create an own class "SoundManager" and call some onStart and onStop classes in it from all your activitys onStart and onStop (or use a base activity class). Keep track of the onStart and onStop with a startCounter(startCounter++ in onstart and startCounter-- in onstop). Because the start of a new activity is called before the onStop of the old activity you always know if the onStart is called for the first Time (startCounter == 1) or started from another of your activitys (startCounter == 2). Same with the onStope(startCounter == 0 means the App was closed, startCounter == 1 means its just the stop from an old activity but there is a new).
This way you encapsulate everything into your SoundManager instead of having to call some keepMusicPlaying method/flag on every activity start inside your app.
If I understand your situation correctly, then I have confronted the same problem a few times. I am using a different thread to play music in my applications. This implementation passes a static reference to a Context that I know will be alive for the time that the music will be playing.
You can try using the AsyncPlayer but you should keep a reference to the class in order to stop the sound from playing.
You can create a Uri to a local resource using
Uri uri = Uri.parse("android.resource://com.stackoverlof.android/raw/ beep.mp3");
.Hope this helps.
Create a static SoundManager using either SoundPools or MediaPlayers.
Create a static flag called keepMusicGoing.
Start the music when the first activty is created.
When switching actvities set keepMusicGoing to true.
On the onStop event of your activities check if keepMusicGoing is true,if so leave the music on, then set keepMusicGoing to false.
If they press the home button the keepMusicGoing flag will be false so the music will stop when the activity loses focus.
Email me and I can send you a couple SoundManagers that I wrote one uses MediaPlayers and the other SoundPools
Chad
You can also create a service which play music using mediaplayer as below.