标题所描述的场景大家都遇到过,有线耳机或者蓝牙耳机断开,此时音乐就自动暂停,那这块代码逻辑在哪呢?
这里我们使用Android 13的代码看下:http://aospxref.com/android-13.0.0_r3/
看下这样的一个广播:android.media.AUDIO_BECOMING_NOISY
http://aospxref.com/android-13.0.0_r3/xref/frameworks/base/media/java/android/media/AudioManager.java#123
/**
* Broadcast intent, a hint for applications that audio is about to become
* 'noisy' due to a change in audio outputs. For example, this intent may
* be sent when a wired headset is unplugged, or when an A2DP audio
* sink is disconnected, and the audio system is about to automatically
* switch audio route to the speaker. Applications that are controlling
* audio streams may consider pausing, reducing volume or some other action
* on receipt of this intent so as not to surprise the user with audio
* from the speaker.
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
看下什么地方发送这个广播的 (ACTION_AUDIO_BECOMING_NOISY ),先看下这里:
http://aospxref.com/android-13.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/audio/AudioService.java#8471
http://aospxref.com/android-13.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/audio/
AudioDeviceBroker.java#postBroadcastBecomingNoisy
/*package*/ void postBroadcastBecomingNoisy() {
sendMsgNoDelay(MSG_BROADCAST_AUDIO_BECOMING_NOISY, SENDMSG_REPLACE);
}
// 处理这个消息然后调用
private void onSendBecomingNoisyIntent() {
AudioService.sDeviceLogger.log((new AudioEventLogger.StringEvent(
"broadcast ACTION_AUDIO_BECOMING_NOISY")).printLog(TAG));
mSystemServer.sendDeviceBecomingNoisyIntent(); ---> 看这个函数,发送ACTION_AUDIO_BECOMING_NOISY
}
// http://aospxref.com/android-13.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/audio/
// SystemServerAdapter.java#80
78 * Broadcast ACTION_AUDIO_BECOMING_NOISY
79 */
80 public void sendDeviceBecomingNoisyIntent() {
81 if (mContext == null) {
82 return;
83 }
84 final Intent intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
85 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
86 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
87 final long ident = Binder.clearCallingIdentity();
88 try {
89 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
90 } finally {
91 Binder.restoreCallingIdentity(ident);
92 }
93 }
至此,可以看到 ACTION_AUDIO_BECOMING_NOISY 广播发出,监听此广播的地方就可以暂停音乐的播放,代码里可以搜下,哪里有监听的地方,比如这个地方:
当然,也可以不暂停,这个处理逻辑自己可以更改。