how to resgister my MusicPlayer App to OnAudioFocusChangeListener

大城市里の小女人 提交于 2019-12-11 04:55:23

问题


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:


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.



来源:https://stackoverflow.com/questions/11839742/how-to-resgister-my-musicplayer-app-to-onaudiofocuschangelistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!