说实话,android的代码是越来越难以阅读。业务函数里面狗皮膏药似的补丁与日俱增。继上篇简要介绍音频焦点的文章,这篇文章的主要内容是分析audiofocus的实现。看了一下午的相关代码都没找到做audiofocus策略的核心逻辑。目前能看懂的大概包含下面两个逻辑。欢迎评论区沟通。
audiofocus实现的核心代码是在project_dir/frameworks/base/services/core/java/com/android/server/audio/MediaFocusControl.java
project_dir/frameworks/base/services/core/java/com/android/server/audio/FocusRequester.java
project_dir在这里指代android源码的根目录。
1.MediaFocusControl会维护所有audiofocus申请信息的堆栈mFocusStack。
2.android当系统进入铃声或者通话状态,会静音住媒体播放器,代码片段如下,mRingOrCallActive变量会在应用申请焦点时进行判断刷新。
if (mRingOrCallActive) {
mFocusEnforcer.mutePlayersForCall(USAGES_TO_MUTE_IN_RING_OR_CALL);
} else {
mFocusEnforcer.unmutePlayersForCall();
}
3.audiofocus的监听器都是在AudioManager的队列里维护。代码如下:
public void registerAudioFocusRequest(@NonNull AudioFocusRequest afr) {
final Handler h = afr.getOnAudioFocusChangeListenerHandler();
final FocusRequestInfo fri = new FocusRequestInfo(afr, (h == null) ? null :
new ServiceEventHandlerDelegate(h).getHandler());
final String key = getIdForAudioFocusListener(afr.getOnAudioFocusChangeListener());
mAudioFocusIdListenerMap.put(key, fri);
}
4.audiomanager进行焦点变化通知的核心类IAudioFocusDispatcher会调用listener。IAudioFocusDispatcher
自身会被注册给audioservice。
status = service.requestAudioFocus(afr.getAudioAttributes(),
afr.getFocusGain(), mICallBack,
mAudioFocusDispatcher,
clientId,
getContext().getOpPackageName() /* package name */, afr.getFlags(),
ap != null ? ap.cb() : null,
sdk);