当用户正在使用我们产品里提供的音乐播放器播放音乐时,用户把耳机或者蓝牙耳机接入后,过一会儿,用户又把耳机给拔除,或者断开蓝牙耳机的连接,我们需要暂停播放音乐,定义一个BroadcastReceiver对象, 对于有线耳机,监听Intent.ACTION_HEADSET_PLUG系统广播,对于蓝牙耳机,监听BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED系统广播
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | private void registerHeadsetPlugReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction( "android.intent.action.HEADSET_PLUG" ); registerReceiver(headsetPlugReceiver, intentFilter); // for bluetooth headset connection receiver IntentFilter bluetoothFilter = new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); registerReceiver(headsetPlugReceiver, bluetoothFilter); } private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (BluetoothProfile.STATE_DISCONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) { //Bluetooth headset is now disconnected handleHeadsetDisconnected(); } } else if ( "android.intent.action.HEADSET_PLUG" .equals(action)) { if (intent.hasExtra( "state" )) { if (intent.getIntExtra( "state" , 0 ) == 0 ) { handleHeadsetDisconnected(); } } } } }; |
这样做可以基本满足需求,但不完美,因为当拔出有线耳机时,播放器不会马上暂停,要等上一秒钟,才会收到Android的系统广播,
1 | android.intent.action.HEADSET_PLUG,他说其他音乐播放器没有这个延迟,经过调查发现,QQ音乐确实没有这个延迟,耳机一拔,播放器立刻暂停, |
相关资料:从硬件层面来看,直接监听耳机拔出事件不难,耳机的拔出和插入,会引起手机电平的变化,然后触发什么什么中断,
最终在stack overflow找到答案,监听Android的系统广播AudioManager.ACTION_AUDIO_BECOMING_NOISY, 但是这个广播只是针对有线耳机,或者无线耳机的手机断开连接的事件,监听不到有线耳机和蓝牙耳机的接入,但对于我的需求来说足够了,监听这个广播就没有延迟了,UI可以立即响应
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private void registerHeadsetPlugReceiver() { IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); registerReceiver(headsetPlugReceiver, intentFilter); } private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) { handleHeadsetDisconnected(); } } }; |