private void init(){
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
private void requestAudioFocus(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//申请延迟焦点
AudioFocusRequest.Builder builder = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_REQUEST_DELAYED);
builder.setAcceptsDelayedFocusGain(true);
builder.setOnAudioFocusChangeListener(focusChangeListener);
int currentAudioFocus = mAudioManager.requestAudioFocus(builder.build());
//表示因为某些原因不能马上获得焦点,获得之后会在AudioManager.OnAudioFocusChangeListener回调
if(currentAudioFocus == AudioManager.AUDIOFOCUS_REQUEST_DELAYED);
}
}
//释放焦点
private void abandonAudioFocus(){
if (mAudioManager != null) {
mAudioManager.abandonAudioFocus(focusChangeListener);
}
}
private AudioManager.OnAudioFocusChangeListener focusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
//长久失去AUDIOFOCUS_LOSS长焦点
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
}
//短暂失去AUDIOFOCUS_LOSS_TRANSIENT短焦点
else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
}
//获取焦点
else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
}
}
};
Android申请延迟音频焦点
最新推荐文章于 2024-05-26 23:28:18 发布