蓝牙耳机判断问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/myfather103/article/details/80319771

调试程序的时候一直很疑惑,为什么蓝牙耳机不走蓝牙耳机的判断流程,却偏偏走了耳机的流程。打断点反复尝试才发现,安卓认为蓝牙耳机是耳机,所以要单独判断蓝牙耳机,也就是说需要把耳机的判断往后延迟。

private void detectAudioOutputDevice(){
	if(isBluetoothEarphoneAvailable()){
			//这个函数会导致mAudioManager.isBluetoothScoOn()为true,要加强判断,使用其他的API。
			mAudioManager.setBluetoothScoOn(true);
			// 判断蓝牙音频设备是否链接 在程序启动执行一次
			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()){
			//判断耳机是否连接
			setAudioManagerInCallMode();
		}else {
			// 打开扬声器
			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);              //可操控蓝牙设备,如带播放暂停功能的蓝牙耳机

        //查看是否蓝牙是否连接到耳机设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态
        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);
		}

	}

问题是因为最后一个函数在判断声音模式时, 如果为AudioManager.MODE_IN_COMMUNICATION居然直接返回不再处理,这个判断应该删除。

当广播知道连接了以后,要等一秒才能发Handler消息,否则切换失败。

猜你喜欢

转载自blog.csdn.net/myfather103/article/details/80319771
今日推荐