【问题标题】:Cant reach on completion listener for the second time, android studio第二次无法到达完成监听器,android studio
【发布时间】:2019-02-25 11:49:14
【问题描述】:

我们正在开发一个应用程序,我们可以在其中播放数组列表中的 3 首歌曲。在第一首歌曲之后,再次按下播放后应该播放下一首歌曲(这是有效的)。但是在第二首歌结束后,我们想要一个开始游戏按钮出现。我们在 OnCompletion 方法中实现了这一点,这适用于第一首歌曲,但不适用于第二首歌曲。 这是代码的一部分:

@Override public void onCompletion(MediaPlayer mediaPlayer) {

            //adding the start game button after song finishes for the first time
           // Button start_button = findViewById(R.id.startGame);
           // start_button.setVisibility(View.VISIBLE);

            Button start_button = findViewById(R.id.startGame);
            start_button.setText(getString(R.string.START));
            start_button.setVisibility(View.VISIBLE);

            //changing the play button to replay after song finishes
            ImageButton imgButton = findViewById(R.id.imageButton);
            imgButton.setImageResource(R.drawable.replay);

        }

    });

public void NextSong(View view) {

    // Logic following
    if (songs.size() == 3) {
        songs.get(0).stop();
        songs.get(0).release();
        mediaPlayer.release();
       mediaPlayer=null;
        //songs.get(0).reset();
        songs.remove(0);
        Button NextSong = findViewById(R.id.NextSong);
        NextSong.setVisibility(View.INVISIBLE);
        final TextView result_display = findViewById(R.id.result_view);
        result_display.setVisibility(View.INVISIBLE);
    } else if (songs.size() == 2) {
        songs.get(0).release();
        songs.remove(0);
        Button NextSong = findViewById(R.id.NextSong);
        NextSong.setVisibility(View.INVISIBLE);
        final TextView result_display = findViewById(R.id.result_view);
        result_display.setVisibility(View.INVISIBLE);
    } else {
        songs.get(0).release();
        songs.remove(0);
        // CONGRATS
        final TextView result_display = findViewById(R.id.result_view);
        result_display.setVisibility(View.VISIBLE);
        result_display.setText(getString(R.string.Congrats));
    }

能否请您帮助我们第二次达到 OnCompletion。

【问题讨论】:

  • 你能发布你设置的监听器代码吗?你也注册 OnErrorListner 吗?如果媒体播放器抛出错误,那么你可以到达那里。

标签: android android-mediaplayer


【解决方案1】:

我认为您对songs.size 的问题,看起来您在arraylist 中有3 个媒体播放器并且您的if else condtion 检查

songs.size == 2 songs.size == 3

这不正确,你应该检查

songs.size() - 1 这将获得第二首歌曲或媒体播放器

songs.size() - 2 这将获得第三首歌曲/媒体播放器

因为arraylist的索引是从0开始的。

并且您在每种情况下都只删除第 0 个索引元素 songs.remove(0);。我不知道为什么,因为根据你的逻辑,它应该删除已经完成的歌曲,如

songs.remove(songs.size() - 1) songs.remove(songs.size() - 2)

这可能也是一个问题。我不知道整个逻辑,所以我无法评论。

【讨论】:

  • 谢谢,已经试过了,没用。第 1 首歌曲和第 2 首歌曲一样播放,但是当第 2 首歌曲结束时,它没有到达 onCompletion 方法和里面的内容
  • 可能还有一个原因 onCompletion 没有调用,因为在调用 onCompletion songs.remove 之前调用了方法。要检查这种情况,只需评论所有 songs.remove 代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 2016-04-19
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多