Android Stop background music when you press the Home key

I am developing an application that has several actions. The user can go to any activity. I start background music with the first main activity and continue to play throughout the application. Now I want that whenever the user presses the HOME button, the media player must pause playback, and when the user returns to the application, it will start playing again. At first I made a static media player and paused music in onPause () and played onResume (), but it creates a jerk when switching between actions. I hope you understand. Any idea how to pause playback when the HOME key is pressed and play it again when the user returns?

+4
source share
2 answers

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

Called as part of the life cycle of an activity when activity exits in the background as a result of a user’s choice. For example, when a user presses the Home key, onUserLeaveHint () is called, but when an incoming phone call calls activity, the call is automatically brought to the forefront, onUserLeaveHint () will not cause an interruption in activity. In cases where it is called, this method is called right before the onPause () callback activity.

+2
source

I had the same problem and decided ugly: there is a global static player. in onPause activity, it calls the player to stop (but it does not actually stop), and in onResume call to start. In onStart Player, I mark music as a game. In onStop, I mark music as stopped, but I don't actually stop it. I wake up 1 second after the stop was called, and if there was no “startPlaying” at the last second, I stop the music.

I hope there is a better way.

0
source

All Articles