简体   繁体   中英

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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