How to set Audio Focus ChangeListener in Android API O?

前端 未结 5 2050
暗喜
暗喜 2021-02-15 20:29

Since requestAudioFocus(AudioManager.OnAudioFocusChangeListener l, int streamType, int durationHint) is deprecated in API O , how do you set audio focus change list

5条回答
  •  情书的邮戳
    2021-02-15 21:09

    https://developer.android.com/guide/topics/media-apps/audio-focusOfficial Link for the resource

     AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mAudioManager.requestAudioFocus(new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                    .setAudioAttributes(
                            new AudioAttributes.Builder()
                                    .setUsage(AudioAttributes.USAGE_GAME)
                                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                                    .build()
                    )
                    .setAcceptsDelayedFocusGain(true)
                    .setOnAudioFocusChangeListener(new AudioManager.OnAudioFocusChangeListener() {
                        @Override
                        public void onAudioFocusChange(int focusChange) {
                           //Handle Focus Change 
                        }
                    }).build()
            );
        } else {
    
            mAudioManager.requestAudioFocus(focusChange -> {
    
                       //Handle Focus Change for earliest version of oreo
                    },
                    AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN);
        }
    

提交回复
热议问题