实时监听耳机拔除

当用户正在使用咱们产品里提供的音乐播放器播放音乐时,用户把耳机或者蓝牙耳机接入后,过一下子,用户又把耳机给拔除,或者断开蓝牙耳机的链接,咱们须要暂停播放音乐,定义一个BroadcastReceiver对象,  对于有线耳机,监听Intent.ACTION_HEADSET_PLUG系统广播,对于蓝牙耳机,监听BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED系统广播android

1ide

2spa

3.net

4code

5对象

6事件

7ci

8get

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(); 

            

        

           

    };

相关文章
相关标签/搜索