简体   繁体   English

如何让媒体播放器继续播放相同的音轨,而不在Android中启动另一个音轨

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

I have an action bar icon on the main activity where when you click on it plays a soundtrack and I can pause and play it properly. 我在主要活动上有一个操作栏图标,当您单击它时会播放一个配乐,并且我可以暂停并正确播放它。 I call this code below when the action bar play icon is pressed: 当按下操作栏播放图标时,我将以下代码称为:

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 code: onOptionsItemSelected代码:

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

I have another activity that has a home button action icon where when I click it, it takes me back to the main activity and the sound track keeps playing but when I click the play icon again, it plays another instance of the same track which I don't want it to do. 我有另一个活动带有“主页”按钮动作图标,单击该图标时,它带我回到主要活动,并且音轨继续播放,但是当我再次单击“播放”图标时,它将播放与我相同的音轨的另一个实例不想做。 I'm use the following code to go back to the main 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
}

What extra piece of code do I need to do what I want my app to do? 我需要什么额外的代码来执行我想让我的应用程序执行的操作?

Any help would be greatly appreciated. 任何帮助将不胜感激。

Jaffer 贾弗

Every time you launch the main activity from sub activities your main activity is getting created. 每次从子活动启动主要活动时,都会创建主要活动。 Since you are creating mediaPlayer instance in onCreate() function new media player instance is created causing two playbacks. 由于要在onCreate()函数中创建mediaPlayer实例,因此将创建新的媒体播放器实例,从而导致两次播放。

Modify how you launch the main activity like below. 修改您启动主要活动的方式,如下所示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM