阻止媒体播放器调用onCompletionListener

时间:2016-09-27 10:02:36

标签: android

当用户从listview中选择一首歌时,我正在使用以下代码播放音乐。

 if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.reset();
            try {
                mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaPlayer.prepareAsync();

        } else {
            mMediaPlayer = new MediaPlayer();
            try {
                mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaPlayer.prepareAsync();
        }

mMediaPlayer.reset();正在调用onCompletionListener。在我的oncompletionListener中,我正在播放下一首歌曲,因此它不是播放所选歌曲,而是播放listview中的下一首歌曲。是否可以通过任何方式阻止调用onCompletionListener并仅播放从listview中选择的歌曲?

1 个答案:

答案 0 :(得分:2)

你可以这样做。

 boolean isMediaPlayerReset = false;
 MediaPlayer mMediaPlayer = null;



    //on list item click
    if(mMediaPlayer.isPlaying()){
        isMediaPlayerReset = true;
        mMediaPlayer.reset();
        try {
            mMediaPlayer.setDataSource("/path");
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaPlayer.prepareAsync();
    }

    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if(isMediaPlayerReset){
                isMediaPlayerReset = false;
                return;
            }
            //play next song
        }
    });