Android MediaPlayer not playing when switching from Activity to Fragment

I have a problem with the MediaPlayer on android, im starting a service that uses a custom implementer where I have all methods to use the media player, pause, play, etc

Player working fine in activity, but it has a button to minimize it because you can keep listening to the audio on every activity so I have to start or resume the audio on a BaseFragment that I create on BaseActivity, but its not resuming the audio.

when I close the activity of the media player I pause the player and I unregister the player service like this

AudioPlayerService.unRegister(this);

this is how im connecting on the BaseFragment to the service

//Connection with a service
private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

        Log.d(">>>>>", "Service starts on fragment");
        AudioPlayerService.LocalBinder mLocalBinder = (AudioPlayerService.LocalBinder) service;
        audioServiceObject = mLocalBinder.getService();
        mBounded = true;

        if (audioServiceObject != null) {
            audioServiceObject.startAudioPlayer(audio_path, media_length);
            AudioPlayerService.register(this);
            audioServiceObject.pauseAudioPlayer();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(">>>>>", "Service end");
        mBounded = false;
        audioServiceObject = null;
    }
}; 

I call the bottom player on BaseActivity

PlayerBottom newAudioPlayer = new PlayerBottom();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.audioPlayerFrame, newAudioPlayer);
    transaction.commit();

and im sending to the bottom player the position where it was left of when the activity was minimized, so I call the MediaPlayer.seekto and pass where it was left of so it can start there.

Upvotes: 0

Views: 363

Answers (1)

Distwo
Distwo

Reputation: 11749

Not sure how you start your service but I think you are starting it by binding it to your activity. When you remove your activity, it unbinds from the service, thus terminate it.

You might need to start you service by calling startService() instead of bindService().

If this is the case, you might want to read more about services here:Services Documentation

Good video explaining the difference: Perf matters video

Upvotes: 1

Related Questions