When I press back or home in my application, it hides, but the MediaPlayer keeps going. Is there a way to know when these buttons have been pressed and stop playback before closing?
Asked
Active
Viewed 3,999 times
3 Answers
3
just implement this method in your class where media player is calling...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{ //Back key pressed
//Things to Do
if(mediaPlayer!= null)
{
mediaPlayer.stop();
mediaPlayer=null;
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}

Akash Singh
- 5,171
- 2
- 26
- 55

akashgupta
- 51
- 1
2
You should be able to override the onPause()
function in your Activity
. onPause()
will be called when you Activity
is hidden and you can pause the MediaPlayer
there.
For example,
@Override
protected void onPause() {
super.onPause(); // Don't forget this line
myMediaPlayer.pause() // Or whatever the function is to pause it
}

Computerish
- 9,590
- 7
- 38
- 49
-
@Joel Can you provide more details, such as a stack trace? – Tyler Sep 12 '10 at 20:12
-
I'm now not totally sure that this was what was causing the crash. Let me get back to you... – Joel Auterson Sep 12 '10 at 21:25