Search code examples
javaandroidaudioandroid-music-player

Media Player help Android


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);

Solution

  • 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