如何检测耳机的插入状态

时间:2022-09-22 17:01:17

1.原理:

其实android系统在耳机插入和拔出的时候都会发送广播,所以我们要想检测耳机的状态只需要注册响应的BroadCastReceiver,对状态进行响应的判断就ok了。

这个广播的名字叫做:android.intent.action.HEADSET_PLUG

注意,在manifest.xml里面要添加响应的权限:

1)...<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

注意,广播要在java文件中动态注册。

2)...注册广播 onCreate() | | onResume()

  //给广播绑定响应的过滤器  
        IntentFilter intentFilter = new IntentFilter(); 
        intentFilter.addAction("android.intent.action.HEADSET_PLUG"); 
        HeadsetReceiver headsetReceiver = new HeadsetReceiver(); 

        registerReceiver(headsetReceiver, intentFilter);


3)....处理广播  public class HeadsetReceiver extends BroadcastReceiver {

        @Override 

        public void onReceive(Context context, Intent intent) { 
            if (intent.hasExtra("state")) { 
                if (0 == intent.getIntExtra("state", 0)) { 
                    Toast.makeText(context, "耳机未插入", Toast.LENGTH_SHORT).show(); 
                } else if (1 == intent.getIntExtra("state", 0)) { 
                    Toast.makeText(context, "耳机已插入", Toast.LENGTH_SHORT).show(); 
                } 
            } 
 
        } 

    }