public class SimpleAudioFocusHelper {
private AudioManager mAudioManager;
private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = focusChange -> {
};
public SimpleAudioFocusHelper() {
mAudioManager =
(AudioManager) KwaiApp.getAppContext().getSystemService(Context.AUDIO_SERVICE);
}
public boolean requestAudioFocus() {
if (mAudioFocusChangeListener == null || mAudioManager == null) {
return false;
}
final int granted = AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return granted == mAudioManager.requestAudioFocus(buildFocusRequest());
} else {
return granted == mAudioManager.requestAudioFocus(mAudioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
}
public boolean abandonFocus() {
if (mAudioFocusChangeListener == null || mAudioManager == null) {
return false;
}
final int granted = AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return granted == mAudioManager.abandonAudioFocusRequest(buildFocusRequest());
} else {
return granted == mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
}
}
@TargetApi(Build.VERSION_CODES.O)
private AudioFocusRequest buildFocusRequest() {
AudioAttributes attributes = new AudioAttributes.Builder()
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
return new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(attributes)
.setAcceptsDelayedFocusGain(false)
.setOnAudioFocusChangeListener(mAudioFocusChangeListener)
.build();
}
}