问题
I am using Java and xml to create an application for the summer. This app has music in the background, that I would like to pause and then play depending on the state it is in. When i lock my screen the music does not pause it keeps playing. How would i fix this, I have tried to use the method on this site:
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents
I have not been able to successfully get a working prototype, and I am working in android studio.
myPlayer = MediaPlayer.create(c(this is the context), myField(This is the raw file));
myPlayer.start();
myPlayer.setLooping(true);
myPlayer.setVolume(0.7f,0.7f);
What could I add to pause the mediaplayer when the lock button is pressed or the phone goes to sleep and then play it when the phone is unlocked?
回答1:
@Override
protected void onPause() {
super.onPause();
if (myPlayer != null) {
myPlayer.pause();
}
}
@Override
protected void onResume() {
super.onResume();
if (myPlayer != null) {
myPlayer.start();
}
}
来源:https://stackoverflow.com/questions/44264994/how-to-pause-and-play-media-player-when-screen-is-locked-or-sleeps