/** * * 判断耳机的种类和状态 */ public class MainActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int i = getheadsetStatsu(); //刚进来获取状态 if(i == 1){ Toast.makeText(this, "有线耳机处于连接状态", Toast.LENGTH_SHORT).show(); }else if(i == 2){ Toast.makeText(this, "蓝牙耳机处于连接状态", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "无耳机正在连接", Toast.LENGTH_SHORT).show(); } registerHeadsetPlugReceiver(); } /** * 获取耳机的连接状态 * @return 根据返回的int值进行自己的逻辑操作 */ public int getheadsetStatsu(){ AudioManager audoManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); //获取声音管理器 if(audoManager.isWiredHeadsetOn()){ //有限耳机是否连接 return 1; } BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); //蓝牙耳机 if (ba == null){ //若蓝牙耳机无连接 return -1; } else if(ba.isEnabled()) { int a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP); //可操控蓝牙设备,如带播放暂停功能的蓝牙耳机 int headset = ba.getProfileConnectionState(BluetoothProfile.HEADSET); //蓝牙头戴式耳机,支持语音输入输出 int health = ba.getProfileConnectionState(BluetoothProfile.HEALTH); //蓝牙穿戴式设备 //查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态 int flag = -1; if (a2dp == BluetoothProfile.STATE_CONNECTED) { flag = a2dp; } else if (headset == BluetoothProfile.STATE_CONNECTED) { flag = headset; } else if (health == BluetoothProfile.STATE_CONNECTED) { flag = health; } //说明连接上了三种设备的一种 if (flag != -1) { return 2; } } return -2; } /** * 注册监听 */ private void registerHeadsetPlugReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); registerReceiver(headsetPlugReceiver, intentFilter); 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)) { Toast.makeText(context, ";蓝牙耳机断开连接了", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "蓝牙耳机连接上了", Toast.LENGTH_SHORT).show(); } } else if ("android.intent.action.HEADSET_PLUG".equals(action)) { if (intent.hasExtra("state")) { if (intent.getIntExtra("state", 0) == 0) { Toast.makeText(context, "有线拔出", Toast.LENGTH_SHORT).show(); }else if(intent.getIntExtra("state", 0) == 1){ Toast.makeText(context, "有线插入", Toast.LENGTH_SHORT).show(); } } } } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(headsetPlugReceiver); } }
亲测,好使