android 管理音频焦点
1.AudioFocusUtils 工具类
package com.example.goldreward.util;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
public class AudioFocusUtils {
private static AudioManager audioManager;
public static void initAudioFocus(Context context) {
if (audioManager == null) {
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
AudioFocusRequest audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(audioAttributes)
.setAcceptsDelayedFocusGain(true)
.setWillPauseWhenDucked(true)
.setOnAudioFocusChangeListener(onAudioFocusChangeListener)
.build();
audioManager.requestAudioFocus(audioFocusRequest);
} else {
audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
}
}
public static void abandonAudioFocus() {
if (audioManager != null) {
audioManager.abandonAudioFocus(onAudioFocusChangeListener);
audioManager = null;
}
}
private static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
if (onAudioFocusListener != null) {
onAudioFocusListener.onLossAudioFocus();
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
if (onAudioFocusListener != null) {
onAudioFocusListener.onGainAudioFocus();
}
break;
}
}
};
private static OnAudioFocusListener onAudioFocusListener;
public static void setOnAudioFocusListener(OnAudioFocusListener onAudioFocusListener) {
AudioFocusUtils.onAudioFocusListener = onAudioFocusListener;
}
public interface OnAudioFocusListener {
void onLossAudioFocus();
void onGainAudioFocus();
}
}
2.在activity使用AudioFocusUtils
package com.example.goldreward.activity;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.example.goldreward.util.AudioFocusUtils;
public class AudioFocusActivity extends Activity implements AudioFocusUtils.OnAudioFocusListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AudioFocusUtils.initAudioFocus(this);
}
@Override
public void onLossAudioFocus() {
}
@Override
public void onGainAudioFocus() {
}
@Override
protected void onDestroy() {
super.onDestroy();
AudioFocusUtils.abandonAudioFocus();
}
}
3.有兴趣可以去看看谷歌官方的管理音频焦点文档
谷歌官方文档:管理音频焦点
|