我的游戏中有一个典型的onAudioFocusChange
代码。
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.i(TAG,"AUDIOFOCUS_GAIN");
mHasAudioFocus = requestAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.i(TAG,"AUDIOFOCUS_LOSS");
abandonAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.i(TAG,"AUDIOFOCUS_LOSS_TRANSIENT");
abandonAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.i(TAG,"AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
abandonAudioFocus();
break;
default:
Log.i(TAG,"Unrecognized audiofocus change");
}
问题是,当 Samsung 手机上出现浮动窗口时,应用程序会收到AUDIOFOCUS_LOSS_TRANSIENT
消息,但是当此窗口关闭时,应用程序不会收到任何消息。
以下是相关的日志行:
13:20:53.253 770 7745 I MediaFocusControl: AudioFocus requestAudioFocus() from AudioFocus_For_Phone_Ring_And_Calls
13:20:53.253 14499 14499 I com.js.helpers.JSNativeActivity: AUDIOFOCUS_LOSS_TRANSIENT
13:20:53.253 14499 14499 I com.js.helpers.JSNativeActivity: abandonAudioFocus()
13:20:53.253 14499 14499 I JSNativeActivity: onAbandonAudioFocus
13:20:53.253 770 1508 I MediaFocusControl: AudioFocus abandonAudioFocus() from android.media.AudioManager$42599770com.js.helpers.JSNativeActivity$4252c788
13:20:53.253 770 1508 I MediaFocusControl: AudioFocus removeFocusStackEntry(): removing entry for android.media.AudioManager$42599770com.js.helpers.JSNativeActivity$4252c788
13:21:01.383 770 1220 I MediaFocusControl: AudioFocus abandonAudioFocus() from AudioFocus_For_Phone_Ring_And_Calls
如何抓住这个窗口的关闭?
答案 0 :(得分:0)
关键句是here 注意:如果当前正在进行电话呼叫,系统将不会授予音频焦点(AUDIOFOCUS_REQUEST_FAILED),并且在呼叫结束后应用程序将不会收到AUDIOFOCUS_GAIN。
所以,这是一种预期的行为,我决定创建一个计时器,并在结束时请求音频焦点。
我目前的代码是:
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.d(TAG, "AUDIOFOCUS_GAIN");
mHasAudioFocus = requestAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.d(TAG, "AUDIOFOCUS_LOSS");
abandonAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
abandonAudioFocus();
startAudioFocusCountdownTimer();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
abandonAudioFocus();
startAudioFocusCountdownTimer();
break;
default:
Log.d(TAG, "Unrecognized audiofocus change");
}
}
private void startAudioFocusCountdownTimer() {
new CountDownTimer(2000, 2000) {
public void onTick(long millisUntilFinished) {
// do nothing
}
public void onFinish() {
mHasAudioFocus = requestAudioFocus();
if (!mHasAudioFocus)
startAudioFocusCountdownTimer();
}
}.start();
}