@Override
public void onBackPressed(){
super.onBackPressed();
mp.release();
overridePendingTransition(R.anim.anim, R.anim.anim2);
}
MediaPlayer is released when a sound is being played, however when a sound isn't being played it can't release anything and causes a null pointer. If I don't release it then it continues to play. It's a catch 22. How can I basically stop MediaPlayer regardless without any error?
release the media player in this manner
if(mp!=null && mp.isPlaying()){
mp.release();
}
You can create a flag.Whenever media is playing,make that flag true.
int playingFlag = 0;
//Make this playing flag 1 when media is playing,by making its value 1
playingFlag = 1;
//When media stops,make this flag as 0
playingFlag = 0;
//In your onBackPressed method,check this flag.If it is 1,stop the player,if its 0,do nothing.
@Override
public void onBackPressed(){
super.onBackPressed();
if( playingFlag == 1 ) {
//Do something you want
mp.release();
overridePendingTransition(R.anim.anim, R.anim.anim2);
} else {
//Do nothing
}
}
Try out this
Check whether media player is playing
if(mp !=null && mp.isPlaying())
mp.release();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.