如何让媒体播放器继续播放相同的音轨而不是在 Android 中开始另一个音轨

How to keep the media player keep playing the same sound track and not starting another one in Android

我在主 activity 上有一个操作栏图标,当您单击它时,它会播放配乐,我可以暂停并正常播放。当按下操作栏播放图标时,我在下面调用此代码:

private void play() {
    if (!mp.isPlaying()) {
        mp.start();//play sound
        play=true;
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer arg0) {
                mp.seekTo(0);
            }
        });
    } else {
        mp.pause();
        play=false;
    }
}

onOptionsItemSelected 代码:

if (id == com.app.myapp.R.id.play) {
    play();
    invalidateOptionsMenu();
}

我有另一个 activity 有一个主页按钮操作图标,当我点击它时,它会带我回到主 activity 并且音轨继续播放但是当我点击播放图标,它会播放我不希望它播放的同一曲目的另一个实例。我正在使用以下代码返回主 activity:

if (id == com.app.myapp.R.id.homebutton) {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish(); // Call once you redirect to another activity
}

我需要什么额外的代码来完成我希望我的应用程序执行的操作?

如有任何帮助,我们将不胜感激。

贾弗

每次您从子活动中启动主要 activity 时,您的主要 activity 就会被创建。由于您在 onCreate() 函数中创建了 mediaPlayer 实例,因此创建了新的媒体播放器实例,导致两次播放。

像下面那样修改启动主要 activity 的方式。

if (id == com.app.twelveimams.R.id.homebutton) {
    Log.e("kiran", "clear top from introu");
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    startActivity(intent);
    finish(); // Call once you redirect to another activity