private static int changedFocus;
private static boolean focusGranted;
private static AudioManager audioManager;
public static int getChangedFocus() {
return changedFocus;
}
public static boolean isFocusGranted() {
return focusGranted;
}
public static void requestFocus(final Context context) {
if (audioManager == null) {
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
switch (audioManager.requestAudioFocus(OnFocusChangeListener.getInstance(),
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)) {
case AudioManager.AUDIOFOCUS_REQUEST_GRANTED:
focusGranted = true;
break;
case AudioManager.AUDIOFOCUS_REQUEST_FAILED:
focusGranted = false;
break;
}
}
private static final class OnFocusChangeListener implements AudioManager.OnAudioFocusChangeListener {
private static OnFocusChangeListener instance;
protected static OnFocusChangeListener getInstance() {
if (instance == null) {
instance = new OnFocusChangeListener();
}
return instance;
}
@Override
public void onAudioFocusChange(final int focusChange) {
changedFocus = focusChange;
System.out.println("on focus change: " + focusChange);
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
GlobalMusicPlayer.onFocusGained();
break;
case AudioManager.AUDIOFOCUS_LOSS:
GlobalMusicPlayer.onFocusLoss();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
GlobalMusicPlayer.onFocusLossTransient();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
GlobalMusicPlayer.onFocusLossTransientCanDuck();
break;
}
}
}
我调用 requestFocus(context) 并获取 AudioManager.AUDIOFOCUS_REQUEST_GRANTED 作为返回值。
之后,onAudioFocusChange从未调用过,因此changedFocus始终为 0。
isFocusGranted() // true
getChangedFocus() // 0
设备:Nexus 10、摩托罗拉 Xoom。