捕获Android MediaPlayer错误

Lea*_*ros 1 android media-player

我想抓住像这样的MediaPlayer错误:

01-03 21:03:08.797: E/MediaPlayer(9470): error (1, -2147483648)
Run Code Online (Sandbox Code Playgroud)

或这个

01-03 20:52:48.859: E/MediaPlayer(8674): error (1, -1004)
Run Code Online (Sandbox Code Playgroud)

我需要捕获哪个例外?我试过了

    try {
        mp.start();
    }

    catch (IllegalArgumentException e){Log.d(TAG, "error1");}
    catch (IllegalStateException e) {Log.d(TAG, "error2");}
    catch (Exception e){Log.d(TAG, "error2");}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.谁能告诉我哪个例外我必须抓到?

Dam*_*ian 8

您需要在Fragment或Activity中实现android.media.MediaPlayer.OnErrorListener.

/*
     * 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;
    }
Run Code Online (Sandbox Code Playgroud)

创建MediaPlayer时,请确保拨打电话

mediaPlayer.setOnErrorListener(this);
Run Code Online (Sandbox Code Playgroud)