0
votes

I am creating an android application (like: KBC - Kaun Banega Carorpati), in which i want to add background music and sound file.

I was used shared preference for saving the user's choice whether he/she want to play music or not.

I added sound files for different events and it works fine.

And now i want to add some background music that can play throughout the application (in all activities) and also in some activities i want to pause the background music.

How i can achieve this ?

3
How about using the same snippet you used to play music on events to play at the beginning of the application? A class Application is persistent through it, or you can just play it on a background service, even just on a busy background thread. - MLProgrammer-CiM
@EfEs but when the activity switche to another activity it stops the background music. - Gaurav Mahajan
Read my edit, background service should do the trick. - MLProgrammer-CiM
Thanks I got the answer, i used background thread as a service which runs forever. - Gaurav Mahajan

3 Answers

1
votes

How about using the same snippet you used to play music on events to play at the beginning of the application? A class Application is persistent through it, or you can just play it on a background service, even on a busy background thread.

0
votes

Simply start the MediaPlayer and don't stop it when the activity is paused. And on those activities where you would like the sound to be played - stop the MediaPlayer in onCreate and then start it again in onResume. That's the whole magic.

  • MediaPlayer.start() when activity is created (onCreate)
  • MediaPlayer.pause() when activity that shouldn't have any music is opened (onCreate)
  • MediaPlayer.start() when the activity that should be playing is opened AGAIN (onResume)

Check activity life cycle to understand my concept better

0
votes

create a common activity and extend all activities to it. start the player in the oncreate, but before that check if the player already exists if its playing. if not, start it, else dont do anything to it. And create a method that stops the player and call it when needed.