Android Stop background music when Home key presse

2019-06-27 04:00发布

问题:

I am developing an app which has multiple activities. User can navigate to any activity. I start background music from first main activity and it keeps playing throughout the application. Now I want that whenever user presses HOME key, the media player should pause playing and when user comes back to app, it starts playing again. First I made media player static and was pausing music in onPause() and playing in onResume() but it creates a jerk while switching between activities. I hope you got my point. Any idea how to pause playing when HOME key pressed and play it again when user comes back?

回答1:

Take a look at Activity.onUserLeaveHint() http://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()

Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback.



回答2:

I had the same issue and solved it in an ugly way: there is a global static player. in the onPause of an activity it calls the player to stop (but it does not actually stop), and in onResume call to start. In the player onStart I mark the music as playing. In onStop, I mark the music as stopped but not actually stop it. I wake up 1 second after stop was called , and if there was no "startPlaying" in the last second, I stop the music.

I hope there is a better way.