Alberto
Alberto

Reputation: 377

Dealing with Android's MediaPlayer while rotating screen, pressing Home Button or App is interrupted

I'm in a tricky part of the workflow/design on my app.

I have a MediaPlayer that runs into a Service. I want the music to stop when user leaves (BUT NOT CLOSES) the App. That is, the Home Button.

So I implemented MediaPlayer's pause() and start() methods into Activity's onStop() and onResume(), respectively. That is working fine when testing with the button and relauching the App, but it also happens when the screen is rotated due to the Activity's lifecycle.

So, how can I avoid this in a efficient / elegant way? The music mustn't be interrupted when device is rotated. I thought in overriding Home Button's click method, pause there the MediaPlayer and setting a global boolean flag to check in onResume() if MediaPlayer must be resumed. But this seems to me like a hack or so, not a good practice.

I'm wrong with this? Is there a better way?

Any advice is appreciated.

Upvotes: 0

Views: 1074

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134714

There are a few options here:

If your minSdkVersion is at least 14, you can check the isChangingConfigurations() flag before stopping the media player:

@Override
protected void onStop() {
    if (!isChangingConfigurations()) {
        // Stop the Media Player
    }
}

Otherwise, you could watch for onUserLeaveHint():

@Override
protected void onUserLeaveHint() {
    // Stop the Media Player
}

Although that won't be called if another application is forcibly drawn to the foreground (e.g. a phone call comes in).

EDIT: As an alternative you might be able to rely on onWindowFocusChanged(). It is called with false when leaving the activity with Home or Back, but not on a configuration change. It should also be called when another activity is brought to front.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // Stop the MediaPlayer
}

As a side note, you should typically use symmetric lifecycle methods (e.g. instead of onPause(), onStart() use either onPause()/onResume() or onStop()/onStart())

Upvotes: 3

Related Questions