Search code examples
androidandroid-mediaplayeronresumeonpause

onPause onResume alternative?


I've got a bit of a dilemma and not quite sure how to solve it. Here's the scenario...

I have a multi activity application which plays music from the time it starts to the time the application exits.

However, if I use onPause / onResume to detect when the activity is sent to the background and pause the music in onPause and resume play in onResume, the music "skips" briefly when I start the next activity as the calling activity is finished once the startActivity() is called.

If I don't pause / resume the music in onPause / onResume the music plays smoothly but does NOT stop if the home key is pressed and the activity is sent to the back.

Is there a way to detect an activity is sent to the background (using, say a timer and application flag) without having to use onPause / onResume?

If this is not possible or too hard to implement (I'm still learning as we all are), is there a way to create an "invisible" launcher activity which runs in the background to handle such things but never seen?

As always, thanks in advance.


Solution

  • OK, here's the solution and it's fairly straightforward once I thought about it in a more logical way.

    What I have done is:-

    1. Create a public static int called activityCount.
    2. In the onCreate function of each activity I increment activityCount by 1.
    3. I @Override public void finish() and decrement activityCount by one and call super.finish().
    4. In onPause if activityCount == 1, pause the music.
    5. In onResume if activityCount == 1, play the music.

    This is giving me the desired effect by continuously playing the music but when the home button is clicked the music stops and resumes when the activity is resumed.

    Thanks for all the suggestions as it helped me think more logically.