2

I have a music service that plays music in the background of the app. I want the music to keep playing through all activities of the application but to stop when the app is running in the background (ie when the user goes to another app or presses the home button without removing the app from the running applications)

This is my MusicService code:

public class MusicService extends Service {
public static MediaPlayer player;

public IBinder onBind(Intent arg0) {
    return null;
}

public int onStartCommand(Intent intent, int flags, int startId) {


    player= MediaPlayer.create(this,R.raw.music1);
    player.start();
    player.setLooping(true);

    return super.onStartCommand(intent,flags,startId);

}

}

and this is the part of my manifest related to the music service:

<service android:name=".MusicService" android:stopWithTask="true" />

Edit: If anyone knows how to play background music without service also that would be okay as long as the music plays during the whole time the app is open and closes when the home button is pressed.

unknown_111
  • 111
  • 1
  • 3
  • 12

2 Answers2

0

Basicaly you have to define witch activity is your exit point and then edit your onStartCommand like this

private boolean playing; // use this var to determine if the service is playing
public int onStartCommand(Intent intent, int flags, int startId) {

  String action = intent.getAction();
  if(action == ACTION_PLAY) {
    // No each time your start an activity start the service with ACTION_PLAY but in ACTION_PLAY process check if the player if not already runing
      if(!playing) {
         player= MediaPlayer.create(this,R.raw.music1);
         player.start();
         player.setLooping(true);
         // here you set playing to true
         playing = true;
     }
 } else if(action.equals(ACTION_STOP) {
        // Set playing to false
        playing = false;
       // This is just an exemple : Now here increase a delay little bit so that the player will not stop automaticaly after leaving activity
        new Handler().postDelayed(new Runnable(){
               @override
               public void run() {
                // No before stoping the play service
                // check playing if playing dont go further 
                 if(playing) return;
                if(player!=null && player.isPlaying()) {
                    player.stop();
                    player.release();
                    player.reset(); // To avoid mediaPlayer has went away with unhandled error warning
                    player = null;
                    // And stop the service 
                    stopSelf();
                 }    
              }
      },2500);
 }
return START_STICKY;}

Now if you want to start playing use

Intent intent = new Intent(context,YourService.class);
intent.setAction(YourService.ACTION_PLAY);

And for stopping

Intent intent = new Intent(context,YourService.class);
intent.setAction(YourService.ACTION_STOP);

And dont forget to define the two action contants fields

If you dont want to define your exit point you can define a boolean that determine that your service is in use and therefore wont be stopped by the delayed handler Now each time one of activity start, start the service with action ACTION_PLAY and once it stop start the service with ACTION_STOP that will ensure that each activity have the ability to start and stop player also dont forget to tweak the delay
Hope it help

thunder413
  • 585
  • 3
  • 10
0

I think the best solution to this problem is to stop the music in onPause() of each Activity and start the music in onResume() of each Activity. The problem you will run into is that your music will stutter when your application switches from one Activity to another. To combat that problem, you should post a Runnable (that stops the music) to a Handler in onPause(), but post it so that it doesn't run immediately. It should be delayed for about 200 milliseconds. In onResume(), cancel the Runnable so that it does not run. This will prevent the stuttering, but stop the music 200 milliseconds after the user has pressed the HOME button.


Another option is not to use a Service, but just keep the MediaPlayer instance in your Application class. You'll still want to stop and start the music in onPause() and onResume(), but you can do it more directly by just calling some methods on your Application class. You will need to create a custom Application class that extends Application and add that to your manifest.

David Wasser
  • 93,459
  • 16
  • 209
  • 274