Search code examples
androidandroid-mediaplayerbackground-service

play music with background service


I'm trying to play music with a background service. Firstly, I have a toggle button in MainActivity for playing and pausing music. I also created BackgroundSoundService just for playing music in all activities and not to play in the background:

public class BackgroundSoundService extends Service {

private static final String TAG = "BackgroundSoundService";
MediaPlayer player;

public IBinder onBind(Intent arg0) {
    Log.i(TAG, "onBind()" );
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    player = MediaPlayer.create(this, R.raw.vaporv2);
    player.setLooping(true); // Set looping
    player.setVolume(100,100);
    Log.i(TAG, "onCreate() , service started...");

}
public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return Service.START_STICKY;
}

public IBinder onUnBind(Intent arg0) {
    Log.i(TAG, "onUnBind()");
    return null;
}
public void onStop() {
    Log.i(TAG, "onStop()");
}
public void onPause() {
    if(player!=null && player.isPlaying()){
        player.pause();
    }
    Log.i(TAG, "onPause()");
}
@Override
public void onDestroy() {
    player.stop();
    player.release();
    Log.i(TAG, "onCreate() , service stopped...");
}

@Override
public void onLowMemory() {
    Log.i(TAG, "onLowMemory()");
}
  }

and MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     MusicButton = (ToggleButton) findViewById(R.id.toggleButton);

    MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (MusicButton.isChecked()) {
                //mediaPlayer.pause();
                Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
                startService(myService);
            } else {
                //mediaPlayer.start();
                Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
                stopService(myService);
            }
        }
    });

My problem happens when I pause the music and play it again. The music starts from the beginning when I want it to continue from where it left off. My second problem is that I don't want to play music in the background, I want stop music when the app is in background.


Solution

  • I'm not sure what your onPause() and onStop() are meant to do. However when you start a service for the first time using Context.startService() the onCreate() method of the service is called and then onStartCommand() is called and later when you call startService() again only the onStartCommand() is called. So for whatever reason if you want to play the sound in a service and pause that in the very same service, you need to provide the service an Action that specifies the action you want to do.

    So in your activity when you want to tell the service to play the sound:

    String action = "PLAY";
    Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
    myService.setAction(action);
    startService(myService);
    

    and to pause the sound:

    String action = "PAUSE";
    Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
    myService.setAction(action);
    startService(myService);  
    

    and in the onStartCommand() method in your service:

    if (intent.getAction().equals("PLAY")) {
        // resume the sound
    }
    if (intent.getAction().equals("PAUSE")) {
        // pause the sound
    }
    

    and when you really need to stop the service meaning Destroy the service, call context.stopService() and only then onDestroy() method is called and the service is really destroyed.