如何在Mediaplayer中修复IllegalStateException

时间:2018-06-18 16:09:28

标签: android android-mediaplayer illegalstateexception

我在OnItemClick中创建了一个listview和MediaPlayer。

        listSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Song song = mAdapter.getItem(position);
            mPlayer = MediaPlayer.create(MainActivity.this, song.getmSongResourceId());
            if (mPlayer != null) {
                mPlayer.release();
            }
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener () {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mPlayer.start();
                    mPlayer.pause();
                    controller.show(0);
                }
            });

            mPlayer.start(); //error here
            controller.show(0);
        }
    });


@Override
public void start() {
    mPlayer.start();
}

@Override
protected void onStop() {
    super.onStop();
    mPlayer.pause();
    controller.hide();
}

关于项目活动的ckick关闭。这是logcat:

java.lang.IllegalStateException
    at android.media.MediaPlayer._start(Native Method)
    at android.media.MediaPlayer.start(MediaPlayer.java:1228)
    at com.....MainActivity$2.onItemClick(MainActivity.java:432)
    at android.widget.AdapterView.performItemClick(AdapterView.java:314)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1162)
    at java.lang.reflect.Method.invoke(Native Method)

MainActivity.java:432是mPlayer.start();。 什么是IllegalStateException,以及如何修复它?您可能会说我的帖子this发布重复,但我不确定如何将其应用于我的代码。

1 个答案:

答案 0 :(得分:0)

尝试

mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener () {
    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.start();
        mp.pause();
        controller.show(0);
    }
});