我在使用 AudioFocusChangeListener 时遇到了问题,但仍然无法收听音频焦点的变化。有人可以帮我找出原因吗?这是我所做的:
在我的 FM 应用程序中,当 FM 在 startFM 中启动时,我放置
requestAudioFocus()
以获取资源:int result = mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_FM,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { Log.d(LOGTAG, "Successfull to request audioFocus listener"); } else { Log.d(LOGTAG, "Failure to request focus listener"); }
在退出应用程序时
onDestroy()
,我曾经abandonAudioFocus()
释放资源。成员变量
mAudioFocusListener
如下:private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() { public void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS, turning FM off"); if (isFmOn()) { fmOff(); } break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK"); if (isFmOn()) { Log.d(LOGTAG, "AudioFocus: FM is on, turning off"); mute(); stopFM(); } break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT"); if (isFmOn()) { Log.d(LOGTAG, "AudioFocus: FM is on, turning off"); mute(); stopFM(); } break; case AudioManager.AUDIOFOCUS_GAIN: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN"); if (isFmOn()) { Log.d(LOGTAG, "AudioFocus: FM is off, turning back on"); unMute(); startFM(); } break; default: Log.e(LOGTAG, "Unknown audio focus change code " + focusChange); } } };
AudioForcus
根据日志,它打印“Successfull to request audioFocus listener”,但在警报开启或其他音频更改事件时不打印任何更改日志。谁能弄清楚它有什么问题?另一方面,我将日志放入 AudioService.java 和 AudioManger.java,在 AudioService.java 中,requestAudioFocus(): if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
try { mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( -1 * focusChangeHint, // loss and gain codes are inverse of each other mFocusStack.peek().mClientId); // This doesn't excute } catch (RemoteException e) { Log.e(TAG, " Failure to signal loss of focus due to "+ e); e.printStackTrace(); } }
在 AudioManager.java 中,这里也不执行: private IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
public void dispatchAudioFocusChange(int focusChange, String id) { Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id); mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m); }
这就是我的全部问题。谁能告诉我为什么这个听众不能听警报事件和其他音频焦点改变的事件?顺便说一句,我怎样才能成功收听这些事件?也许我错过了一些步骤或使用了不正确的方式?非常感谢。