When debugging the program, I always wonder why the Bluetooth headset does not follow the judgment process of the Bluetooth headset, but only the headset process. After repeated attempts at the interruption point, it was found that Android thought that the Bluetooth headset was a headset, so it was necessary to judge the Bluetooth headset independently, that is to say, it was necessary to delay the judgment of the headset.
private void detectAudioOutputDevice(){ if(isBluetoothEarphoneAvailable()){ //This function will cause mmaudiomanager. Isbluetoothscoon() to be true. To enhance judgment, use other API s. mAudioManager.setBluetoothScoOn(true); // Judge whether the Bluetooth audio device is linked once when the program is started if (mAudioManager.isBluetoothA2dpOn() || mAudioManager.isBluetoothScoOn()) { setAudioManagerInCallMode(); // audioManager.startBluetoothSco(); // if(audioManager.isWiredHeadsetOn()) // audioManager.startBluetoothSco(); verifyBluetoothSupport(); try { mAudioManager.startBluetoothSco(); } catch (NullPointerException e) { // TODO This is a temp workaround for // Lollipop Log.d(mAudioManager, "startBluetoothSco() failed. no bluetooth device connected."); } } }else if(mAudioManager.isWiredHeadsetOn()){ //Determine whether the headset is connected setAudioManagerInCallMode(); }else { // Turn on the speakers mAudioManager.setSpeakerphoneOn(true); } } } private boolean isBluetoothEarphoneAvailable(){ BluetoothAdapter mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter==null){ return false; }else if(mBluetoothAdapter.isEnabled()){ int a2dp = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP); //Control Bluetooth devices, such as Bluetooth headset with pause function //Check whether Bluetooth is connected to the headset device to determine whether it is connected or not if (a2dp == BluetoothProfile.STATE_CONNECTED || a2dp==BluetoothProfile.STATE_CONNECTING) { return true; } } return false; } public void setAudioManagerInCallMode() { Log.d("[AudioManager] Mode: MODE_IN_COMMUNICATION"); if(mAudioManager.isWiredHeadsetOn()||isBluetoothEarphoneAvailable()){ mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); }else{ mAudioManager.setMode(AudioManager.MODE_NORMAL); } }
The problem is that when the last function judges the sound mode, if audiomanager.mode "in" communication returns directly and doesn't handle it anymore, the judgment should be deleted.
When the broadcast knows that it is connected, it needs to wait a second to send the Handler message, otherwise the handover fails.