Handling MediaPlayer exceptions from rolling over endless errors

I've implemented a service for MediaPlayer to keep playing even after minimizing the application. The problem occurs whenever the MediaPlayer does not play the song (for example, the file does not exist or the MediaPlayer source path is wrong), it throws a general error,

Error (-38,0) start called in state 0

      

This one keeps running in an endless loop and ever since it has been running in the background, so it is difficult to prevent this event from happening. In this scenario, I want to force close the MediaPlayer and wait for the MediaPlayer to start playing another song.

I have already tried,

if (mp! = null && mp.isPlaying()) {
        mp.release();
}

      

But this doesn't stop MediaPlayer metadata errors after getting the exception. I would like to know what would be the best practice to prevent such an exception. Any help would be greatly appreciated.

+3


source to share


1 answer


You can handle the error using onErrorListener

on your MediaPlayer like

mp.setOnErrorListener(new OnErrorListener() {

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // handle your error here like exit media player or show message
         or move to next song

        return true;
    }
});

      



The main thing here is return true

that if you are return false

, then the error will not be handled by you.

+2


source







All Articles