致命异常:android.media.MediaPlayer上的java.lang.IllegalStateException

时间:2017-06-24 19:19:01

标签: java android android-mediaplayer android-videoview

当我调用Mediaplayer时,我在一些较新的Android模型上遇到IllegalStateException。它主要是Android 6.和7手机。我似乎无法弄清楚如何解决这个问题,而其他问题"问题"这里dosn似乎适用于我的问题。

得到这个堆栈跟踪:

public class IntroVideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

private MediaPlayer mp;
private boolean has_started = false;

@TargetApi(Build.VERSION_CODES.LOLLIPOP) public IntroVideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}

public IntroVideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

public IntroVideoSurfaceView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public IntroVideoSurfaceView(Context context) {
    super(context);
    init();
}

private void init() {
    mp = new MediaPlayer();
    getHolder().addCallback(this);
}

@Override public void surfaceCreated(SurfaceHolder holder) {
    AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.onboarding);
    try {
        if (!has_started) {
            has_started = true;
            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
        }


      mp.prepare();


        android.view.ViewGroup.LayoutParams lp = getLayoutParams();
        lp.height = getHeight();
        lp.width = getWidth();

        setLayoutParams(lp);
        mp.setDisplay(getHolder());
        mp.setLooping(true);
        mp.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}

@Override public void surfaceDestroyed(SurfaceHolder holder) {
    mp.stop();
  }
}

这是我的班级:

      <org.my.app.IntroVideoSurfaceView
       android:id="@+id/surface"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

这是我在活动中调用的xml文件,用于显示视频:

{{1}}

1 个答案:

答案 0 :(得分:1)

在try循环结束时,您start()媒体播放器(Started状态)。如果您稍后致电prepare(),则会引发IllegalStateException,因为您只能从prepare()州(您提出的Initialized州调用Stopped使用surfaceDestroyed()的媒体播放器是从中调用prepare()的有效状态。请参阅state diagram here,并注意根据the surface life-cyclesurfaceCreated()可能会被多次调用。因此,您应该至少将mp.prepare()放在if块中。

相关问题