Communication between BLE device and different android apps on same device

可紊 提交于 2019-11-30 21:39:27

The Bluetooth standard itself doesn't define anything how multiple apps would behave if both have a GATT connection to the same device. In the standard there is just one "GATT client".

Now both iOS and Android have taken one step further in a way that might seem unintuitive. Instead of only allowing one app at a time to communicate, multiple apps can be connected over the same GATT client to a device. The OS "multiplexes" the communication from/to the apps. The behaviour is that responses to read and write requests can only be seen by the app that made the request. So if you do readCharacteristic only that app will get the onCharacteristicRead callback. Notifications however will be delivered to both apps to the onCharacteristicChanged callback, since it wouldn't make any sense to send the notification to only one.

When you say that the "response" to a write request is the notification, that's not correct in terms of GATT terminology. The response to a write request is always empty per specification (or an error). If your peripheral emits a notification, then in your case that might be the "answer" according to your own logic, but it's not a response or any way related to your write request per the GATT specification. That's why Android can't (and shouldn't) send the notification to only one device.

I suggest that you simply ignore notifications you are not expecting. If you want to associate an "answer" to a write request, you can change your protocol to include a transaction id in both packets so they can be matched.

When I write "app" above, I really mean BluetoothGatt objects. You can call connectGatt twice with the same remote device in the same app, which will behave the same as if you connected from two different apps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!