安卓BLE编程 服务端与客户端通讯 BluetoothGattCallback 与 BluetoothGattServerCallback
低功耗蓝牙 BLE 通讯篇
继续研究安卓上面蓝牙BLE编程,一部安卓设备模拟服务端,一部安卓手机模拟客户端,看着官方文档摸索如何用BLE在两部安卓设备之间交换数据。
0.客户端与服务端连接
在客户端通过扫描得到了服务端的BluetoothDevice对象之后,在BluetoothGattCallback对象里面定义以下回调:
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (status == BluetoothGatt.GATT_SUCCESS
&& newState == BluetoothGatt.STATE_CONNECTED){
//通知服务端准备服务
gatt.discoverServices();
}
}
即连接上之后立即扫描服务端服务,服务端准备就绪之后,会在客户端触发以下回调:
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//这里可以通过gatt获取到BluetoothGattService对象
//通过BluetoothGattService可以获取BluetoothGattCharacteristic对象
}
至此,客户端与服务端的通讯必要对象就准备完毕了。
1.客户端向服务端发送数据
- writeCharacteristic向服务端发送数据
客户端:
//data为byte[]数组,大小不能超过512Byte
characteristic.setValue(data);
//characteristic为要更新的BluetoothGattCharacteristic对象
writeCharacteristic(BluetoothGattCharacteristic)
方法来发送一个更新Characteristic的请求。
服务端会触发
onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value){
//characteristic为要更新的BluetoothGattCharacteristic,但是其中的value并不是要更新的value
//value才是新的值,客户端发送的数值
characteristic.setValue(value);//服务端和客户端同步
//要告诉客户端数据已经更新了
//server是BluetoothGattServer实例
server.sendResponse(device,requestId, BluetoothGatt.GATT_SUCCESS,offset,value);
}
接着,会在客户端触发
onCharacteristicWrite (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){
//如果在writeCharacteristic方法之前调用了
//BluetoothGatt对象的beginReliableWrite()方法
//此时服务端不会触发上述方法,但是会返回收到的数据
//可以用之前的value在这里和characteristic的value比较,相同则数据完整
//调用executeReliableWrite()才会触发服务端的回调
//do Something...
}
至此,客户端向服务端发送数据的流程结束。
2.服务端向客户端发送数据
- notifyCharacteristicChanged向客户端发送数据
首先在客户端注册characteristic的变化监听
gatt.setCharacteristicNotification(characteristic,true);
之后实现回调:
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.d("WDS","Notify");
//characteristic已经是更改后的了,直接读取value即可
Log.d("WDS",new String(characteristic.getValue()));
//doSomething...
}
客户端即可收到服务端的特性改变通知。
服务端要通知的时候:
characteristic.setValue("2256".getBytes());
//server是BluetoothGattServer实例,device为客户端对象
server.notifyCharacteristicChanged(device,characteristic,true);
客户端获取到通知之后,会触发服务端的回调:
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
if (status == BluetoothGatt.GATT_SUCCESS){
//通知发送成功
}
}
至此,服务端向客户端发送数据的流程结束。
评论已关闭