Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Audio Focus ChangeListener in Android API O?

Tags:

java

android

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

like image 605
Xera12 Avatar asked Jul 02 '17 16:07

Xera12


1 Answers

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);
    }
like image 58
Mukul Pathak Avatar answered Oct 22 '22 22:10

Mukul Pathak