Pause music player on a phone call and again resume it after phone call in android

前端 未结 5 818
暗喜
暗喜 2020-12-11 18:25

I am using android.media.MediaPlayer object to play audio files in my app. Everything works fine but when a phone call comes while a song is playing the app doe

5条回答
  •  悲&欢浪女
    2020-12-11 19:06

    here is the permanent solution. Use audiomanager for getting audio focus. When call comes it calls AUDIOFOCUS_LOSS_TRANSIENT and you can pause the media player in that method. After call it calls AUDIOFOCUS_GAIN method so just call mediaplayer.start method .

    private AudioManager.OnAudioFocusChangeListener  afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
    
                @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                mMediaPlayer.start();}
    
    else if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT){
    
                    mMediaPlayer.pause();
     }
    

提交回复
热议问题