I have a bluetooth device which has a single button to take a photo using connected android device.
In my application, I can control which device has been connected. But, I need more.
I just wonder that Is it possible to listen click of bluetooth device button from my android application? If it is, at that case, I can use this bluetooth device to my purpose.
Do I need some hack for my bluetooth device ?
答案 0 :(得分:0)
您的蓝牙设备需要有一个 API 规范 - 它可以发送的信号列表。它可以像服务器或客户端一样工作,我们可以通过 BluetoothSocket
类连接到它并监听它的事件。 Here 对其进行了更详细的描述。
不过还有第二种选择。如果这是一些便宜的中国点击器,可以从远处拍摄照片,它将以相对简单的方式工作。通常,这些设备被识别为远程键盘。这意味着您可以覆盖 onKeyDown(int keyCode, KeyEvent event)
/View
的 Activity
方法,检查从设备发送的 keyCode
,并相应地处理它。
在第二种情况下,建立连接后,您不需要任何额外的蓝牙相关代码更改即可使其工作。
答案 1 :(得分:0)
这取决于 BT 设备的通信方式。但是许多设备使用 Gatt 通信。因此,您可以执行以下操作来侦听事件:
val btManager = view.getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
val connectedDevices = btManager.getConnectedDevices(GATT)
connectedDevices.forEach {
listen(it)
}
private fun listen(dev: BluetoothDevice) {
gatt_l = dev.connectGatt(view, false, object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
if (newState == BluetoothProfile.STATE_CONNECTED)
gatt?.discoverServices() //on connection, discover services of the BT device that it is offering.
super.onConnectionStateChange(gatt, status, newState)
}
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
super.onServicesDiscovered(gatt, status)
gatt?.services?.forEach { service ->
if (service.uuid.toString() == DESIRED_SERVICE) // DESIRED_SERVICE that u r interested in. Initially u will have to go through every service to get ur event.
service.characteristics.forEach { // each service has characterstics, u need to listen to all of these to find ur event.
if (it.uuid.toString() == DESIRED_CHARAC_UUID) {
gatt.readCharacteristic(it)
gatt.setCharacteristicNotification(it, true)
return@forEach
}
}
}
}
override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
//When the button on device is tapped, u should get the event here.
characteristic?.value?.let { data ->
//this "data" should be the event u want to listen. YOUR LOGIC.
}
super.onCharacteristicChanged(gatt, characteristic)
}
}
override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
super.onCharacteristicRead(gatt, characteristic, status)
}
}, BluetoothDevice.TRANSPORT_LE)
}