Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
user2892437 Avatar asked Aug 31 '15 22:08

user2892437


1 Answers

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
    }
  }
};
like image 95
Distwo Avatar answered Sep 21 '22 06:09

Distwo