我正在开发一个聊天 Android 应用程序,我可以在其中与另一台设备进行视频通话。现在我希望用户能够使用蓝牙设备,例如耳塞等。
我能够检测到蓝牙设备何时连接以及蓝牙设备的连接状态,但是连接后我在蓝牙设备上听不到任何声音。代码如下
这是连接蓝牙设备时通知我的 BlutootheProfile.ServiceListener
var mBluetoothA2dp: BluetoothA2dp? = null
private val mProfileListener: BluetoothProfile.ServiceListener =
object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothA2dp = proxy as BluetoothA2dp
mBluetoothA2dp?.let {
val connectedDevices: List<BluetoothDevice> = it.connectedDevices
val statesToCheck = intArrayOf(BluetoothA2dp.STATE_DISCONNECTED)
val disconnectedDevices: List<BluetoothDevice> = it.getDevicesMatchingConnectionStates(statesToCheck)
// Should i do something here...????
} ?: run {
// no devices are connected
}
}
}
override fun onServiceDisconnected(profile: Int) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothA2dp = null
}
}
}
这是通知我移动设备蓝牙连接状态的蓝牙广播接收器
var mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val action = intent.action
var state = BluetoothHeadset.STATE_DISCONNECTED
val previousState = intent.getIntExtra(BluetoothHeadset.EXTRA_PREVIOUS_STATE, BluetoothHeadset.STATE_DISCONNECTED)
if (action == BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) {
state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED)
if (state == BluetoothHeadset.STATE_CONNECTED) {
val mConnectedHeadset =
intent.getParcelableExtra<Parcelable>(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
println("## Device name ${mConnectedHeadset.name}")
// What should i do here...???
} else if (state == BluetoothHeadset.STATE_DISCONNECTED) {
println("## BluetoothHeadset.STATE_DISCONNECTED")
}
} else if (action == BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED) {
}
}
}
在 VideoActivity 的 onCreate 方法中,我有
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
audioManager = SystemServiceUtils.getAudioManager(this)
// Get the default adapter
val mBluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP)
registerReceiver(mReceiver, IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED))
registerReceiver(mReceiver, IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED))
audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
和 onDestroy
...
unregisterReceiver(mReceiver)
视频通话开始后,我无法从蓝牙设备听到其他参与者的声音。我到底应该做什么?