mPlayer.setOnCompletionListener


#1

I have the following code in AudioPlayer

mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        stop();
    }
});

How do I make it tell the fragment to run updateButtons() when the audio completes, so that it re-enables the play button.

Cheers


#2

Okay I came up with a solution.

Please let me know if this solution is the best way to do it.

Inside AudioPlayer, I created a constructor which takes a fragment as the argument and assigns it to mFragment. Then in the listener, I check if the fragment is an instance of HelloMoonFragment and if so, I run the updatebuttons() function (hence preserving AudioPlayer’s independence from a particular fragment).

    private Fragment mFragment;
    
    public AudioPlayer(Fragment fragment) {
		mFragment = fragment;
	}

...

    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            stop();
            if(mFragment instanceof HelloMoonFragment) {
            	((HelloMoonFragment) mFragment).updateButtons();
            }
        }
    });