我将AudioFocus用于音乐播放器。它完美适用于华为P9 Lite(Android N)和华为P20 Lite(Android O)。但在三星Galaxy J3(2016)(Android L)上无法正常工作,似乎我没有请求音频焦点。
这就是我设置监听器的方式
mAudioFocusListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.i("AUDIOFOCUS", "AUDIOFOCUS_GAIN");
play();
break;
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
Log.i(TAG, "AUDIOFOCUS_GAIN_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
Log.i(TAG, "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK");
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.e(TAG, "AUDIOFOCUS_LOSS");
stop();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.e(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
stop();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.e(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
break;
case AudioManager.AUDIOFOCUS_REQUEST_FAILED:
Log.e(TAG, "AUDIOFOCUS_REQUEST_FAILED");
break;
default:
}
}
};
这是请求方法
private boolean requestAudioFocus() {
if (!mAudioFocusGranted) {
AudioManager am = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
if(am != null) {
int result = am.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mAudioFocusGranted = true;
Log.i("AUDIOFOCUS", "AUDIOFOCUS_GAIN");
} else {
// failed
Log.e(TAG, "Failed to get audio focus."); //todo
}
}else{
//TODO
}
}
return mAudioFocusGranted;
}
有没有人有任何想法?
编辑:我解决了将音频焦点请求放在主线程上的问题。