I am trying to pause media player when I click home button or recent apps to exit app but that's not happening. Below is my code for the same:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
MainActivity.mediaPlayer.pause();
}
else if(keyCode==KeyEvent.KEYCODE_HOME )
{
MainActivity.mediaPlayer.pause();
}
else if(keyCode==KeyEvent.KEYCODE_ALL_APPS) {
MainActivity.mediaPlayer.pause();
}
else if(keyCode == KeyEvent.KEYCODE_APP_SWITCH)
{
MainActivity.mediaPlayer.pause();
}
return super.onKeyDown(keyCode, event);
}
This will help
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume()
if the activity returns back to the front, or onStop()
if it becomes invisible to the user.
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by onPause()
.
@Override
protected void onPause() {
super.onPause();
if(mediaPlayer!=null)
{
//pause
mediaPlayer.pause();
}
}
//resume activity
@Override
protected void onResume() {
super.onResume();
if(mediaPlayer!=null)
{
//resume
mediaPlayer.start();
}
}