How can I save background music when Activity changes?

There is some background music in my application playing in a loop using MediaPlayer . I stop the music in onPause Activity, so it does not continue to play if the user leaves the application by pressing the "Home" key, or if they receive a phone call, etc.

However, now I need the music to continue to play unhindered when the user proceeds to some other actions. That is, if they press button A, I add activity A to the stack, and the music should continue; however, if they press button B, I add activity B to the stack, and the music should stop. Similarly, music should continue if they press the back button to return from activity A to their original activity.

I tried to launch MediaPlayer again in onResume Activity A, but there was a rather noticeable gap during the transition in music.

onPause I have onPause , which starts half a second of delay before fading music for more than a quarter of a second; this can be undone from another onResume action. This means that the music stops quickly enough when the user leaves the application; however, when the user switches actions, I still get a slight pause in the music on some slower devices. Also, it looks like a really dirty hack.

Is there a better way?

[Edit: if this helps, MediaPlayer is stored in a static class, which I can access from anywhere in the application.]

+4
source share
1 answer

The simplest solution I could think of if I needed to do this would be to set a static flag variable in my global Application object (let me call it sStartingNewActivity ). Wherever I start a new activity (or by clicking "back" from an action that is not an entry point, overriding the onBackPressed method), I would set this value to true and have onPause do not stop the music if this flag is set. I returned false in every onCreate action. I don’t think that a 1-2 second pause-to-fadeout is a bad way to go, though - it will actually behave the same way it works when a user presses the home button in an iOS app that has a background to the music.

EDIT: you can also try a service-oriented solution that "sniffs" for whether your actions work when your actions are tapped for a specific broadcast; there is an example of code online that I have not tried, but this is an interesting approach).

+3
source

Source: https://habr.com/ru/post/1342306/


All Articles