user2892437
user2892437

Reputation: 1251

Android -- AudioManager.onAudioFocusChange() fires randomly

I'm building a media player and implementing onAudioFocusChange() in a way similar to the docs:

OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
        // Pause playback
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        // Resume playback 
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
        am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
        am.abandonAudioFocus(afChangeListener);
        // Stop playback
    }
  }
};

The only weird issue: when leaving my phone sitting with the app in the background and the mediaplayer paused, the service will randomly start playing. When I remove the above code, it doesn't happen. So, onAudioFocusChange() is being called with AUDIO_FOCUS_GAIN as the argument seemingly randomly. Has anyone else dealt with this issue?

Upvotes: 6

Views: 4535

Answers (1)

Distwo
Distwo

Reputation: 11749

onAudioFocusChange() will be called everytime an app request or release the audio focus. This can come from any app, not just yours. In fact, every notification that plays a sound (eq. Text/mail/...) will gain the focus and then release it. Once another app release the audio focus, your app will gain the focus again thus your resume playback will be called.

To avoid playing when you dont want to, you can keep a boolean that indicates if your app should play:

boolean wantsMusic = true;
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
        // Pause playback
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN && wantsMusic) {
        // Resume playback 
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
        am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
        am.abandonAudioFocus(afChangeListener);
        // Stop playback
    }
  }
};

Upvotes: 7

Related Questions