0

I have an android application in which am try to play a background sound for an particular activity(sound will play on single activity not for an whole application). Am using this code to start the MediaPlayer

MediaPlayer backMP = MediaPlayer.create(this, R.raw.theme_loop);
backMP.setLooping(true);
backMP.start(); 

It is working fine but I just want to stop the music on home button press for this I have try backMP.release(), backMp.stop() in onPause() method nothing is work for me.

Kara
  • 6,115
  • 16
  • 50
  • 57
rkgarg
  • 167
  • 1
  • 1
  • 7

2 Answers2

0

use backMP.stop in both onDestroy,onStop,and onPause it will solve your problem

rahultheOne
  • 154
  • 1
  • 8
0

use this way

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
        Log.d("Test", "Home button pressed!");
        backMP.stop(); 
    }
    return super.onKeyDown(keyCode, event);
}

or you can use like that start playing in onResume()

@Override
    protected void onResume() {
        super.onResume();
                   backMP.start(); 
                    }

and stop in onpouse() like that

  @Override
      protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
        backMP.stop(); 
     }
Sunil Kumar
  • 7,086
  • 4
  • 32
  • 50
  • 3
    I don't think that is going to work, Android doesn't allow you to capture the Home key event. Something about malicious content... – ThaMe90 Jun 20 '13 at 13:35
  • It would be better to use OnPause. And OnResume to start playing again when the application is re-opened. – ThaMe90 Jun 20 '13 at 13:35
  • if i'll comment this then it will automatically stop after finish the sound. It is just for repeat the sound. – rkgarg Jun 20 '13 at 13:51