0

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);
Zookey
  • 2,637
  • 13
  • 46
  • 80

2 Answers2

0

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

Community
  • 1
  • 1
Pete Houston
  • 14,931
  • 6
  • 47
  • 60
  • Thanks but I have tried with this code, but it dosent play music. Here is code: http://pastebin.com/Aej7DL9d of Service class, and on main activity I wrote : Intent svc=new Intent(this, BackgroundSoundService.class); startService(svc); – Zookey Oct 26 '11 at 10:42
  • I was pretty stupid, I didnt put under Android Manifest file. I have tried in service with onPause(), but it still plays. – Zookey Oct 26 '11 at 11:06
  • if `onPause()` not working for you, override this one `onNewIntent()` which is to handle the press event to `HOME` key and it must work definitely, if still not working again, check your implementation, your code. – Pete Houston Oct 26 '11 at 15:03
0

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.

Raz
  • 8,918
  • 3
  • 27
  • 40