Domanda

Application has 7-8 activities, so I have create an application with some background music on all of these activities.

    private void playAudio() {
        mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
        mMediaPlayer.start();
        mMediaPlayer.setLooping(true);
    }

Anyway I want on other activity to stop this background music and start new one. So here we are talking about different classes.

How to do that?

Anyway when I press home, or back button music still plays? How to solve that problem?

Thanks in advance. :)

EDIT:

With these code I managed to stop music, when I press BACK button.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
    moveTaskToBack(true);
    finish(); 
    Music.stop(this);
    return true; 
    }
return super.onKeyDown(keyCode, event);
È stato utile?

Soluzione

Anyway when I press home, or back button music still plays? How to solve that problem?

Handle the media player instance when onPause() is called

protected void onPause() {
    mMediaPlayer.pause();
}

To your main problem: background music in application, across Activities, create a Service, it will do the job.

or refer some already-existed discussion: Playing BG Music Across Activities in Android

Altri suggerimenti

Make a static singelton class that control your media player and you can stop and start it in each activity. For stopping the music you can stop it on onPause and restart in onResume.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top