Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Android MediaPlayer errors

I want to catch MediaPlayer errors like this:

01-03 21:03:08.797: E/MediaPlayer(9470): error (1, -2147483648)

or this

01-03 20:52:48.859: E/MediaPlayer(8674): error (1, -1004)

Which exception do I need to catch? I tried it with

    try {
        mp.start();
    }

    catch (IllegalArgumentException e){Log.d(TAG, "error1");}
    catch (IllegalStateException e) {Log.d(TAG, "error2");}
    catch (Exception e){Log.d(TAG, "error2");}

But it doesn't work. Can anyone tell me which exception I have to catch?

like image 703
Leandros Avatar asked Jun 03 '26 20:06

Leandros


1 Answers

You need to implement android.media.MediaPlayer.OnErrorListener in your Fragment or Activity.

/*
     * Called to indicate an error. Parameters
     * 
     * mp the MediaPlayer the error pertains to what the type of error that has
     * occurred: MEDIA_ERROR_UNKNOWN MEDIA_ERROR_SERVER_DIED extra an extra
     * code, specific to the error. Typically implementation dependant. Returns 
     * True if the method handled the error, false if it didn't. Returning
     * false, or not having an OnErrorListener at all, will cause the
     * OnCompletionListener to be called.
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extras) {

        return true;
    }

When you create your MediaPlayer make sure you call

mediaPlayer.setOnErrorListener(this);
like image 93
Damian Avatar answered Jun 07 '26 22:06

Damian