[英]Service v/w Gatt connection in Android BLE API
I am noticing in the adb logs that the services are discovered first and then the (gatt) connection is made with the device . 我在adb日志中注意到,首先发现了服务,然后与设备建立了(gatt)连接。 Is it true?
是真的吗 Isn't the gatt connection is made first and then the services are discovered from the slave device.
不是先建立gatt连接,然后从从设备中发现服务。
Explanation: 说明:
First you can get device connection state in onConnectionStateChange
, Then if your device is connected state, you can Discover your device using gatt.discoverServices()
. 首先,您可以在
onConnectionStateChange
获得设备连接状态,然后,如果设备处于连接状态,则可以使用gatt.discoverServices()
发现设备。 Then you can get service discovered response in onServicesDiscovered
as state BluetoothGatt.GATT_SUCCESS
. 然后,您可以在
onServicesDiscovered
获取服务发现的响应,状态为BluetoothGatt.GATT_SUCCESS
。 Now You can write on your device. 现在您可以在设备上书写。
Code example: 代码示例:
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
// Device Connected, Now Discover your service
gatt.discoverServices(); // You need to Discovered your gatt Service first
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// You can get discovered gatt service here. Now you can WRITE on your gatt service
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
//You can get WRITE characteristic response here
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
//You can get READ characteristic response here
}
}
};
I hope it's helps you. 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.