how to resgister my MusicPlayer App to OnAudioFocu

2019-07-26 06:27发布

I am creating a music player app.

I want:

  1. When the user plays a song using my app, then the default music player should get stopped(is playing)
  2. And if some other application starts playing when my app is already playing then mine should get stopped.

I am able to work out with the 1st point using Audio Focus. But for the 2nd point, i.e. Handling AUDIOFOCUS_LOSS, i'm facing some issues.

Problem: I've followed the documentation but how should I register my music player service to detect that AudioFocus has been lost.

For 1st Point, here is the code:

if (reqAudioFocus()) {
    mPlayer.start();
}

private boolean reqAudioFocus() {
    boolean gotFocus = false;
    int audioFocus = am.requestAudioFocus(null, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (audioFocus == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        gotFocus = true;
    } else {
        gotFocus = false;
    }
    return gotFocus;
}

For 2nd point my code so far:

//Class implements OnAudioFocusChangeListener

@Override
public void onAudioFocusChange(int focusChange) {
    /*
     * TODO : Call stopService/onDestroy() method. Pause the track; Change
     * the Play/Pause icon; save the track postion for seekTo() method.
     */
    if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
        // TODO: Pause playback
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
        }
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        // TODO: Resume Playback
        if (!mPlayer.isPlaying()) {
            mPlayer.start();
        }
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
        // TODO: stop playback.
        // am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
        am.abandonAudioFocus(afChangeListener);
    }

}

Now how to make my application call onAudioFocusChange() when app loses audio focus.

Thanks

1条回答
Explosion°爆炸
2楼-- · 2019-07-26 07:05

The first argument to requestAudioFocus is an OnAudioFocusChangeListener instance. You're passing null at the moment. Assuming you've implemented reqAudioFocus and onAudioFocusChanged on the same class, passing this instead of null should be enough.

查看更多
登录 后发表回答