1
我正尝试从我的android应用程序连接到Bleno Periphecal GATT服务器。Android应用程序:使用UUID连接到GATT服务器
GATT服务器具有自定义服务和具有唯一UUID的特性。
如何确定连接到此服务器并发送一些文本?
最小的SDK是21,目标SDK是24,所以旧的BluetoothLE扫描方法已被废弃,现在我需要使用BluetoothLEScanner。
我正尝试从我的android应用程序连接到Bleno Periphecal GATT服务器。Android应用程序:使用UUID连接到GATT服务器
GATT服务器具有自定义服务和具有唯一UUID的特性。
如何确定连接到此服务器并发送一些文本?
最小的SDK是21,目标SDK是24,所以旧的BluetoothLE扫描方法已被废弃,现在我需要使用BluetoothLEScanner。
对于连接Ble,只需使用此方法传递您的BT设备的MAC地址即可。
private boolean connectGatt(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
if (mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
return mBluetoothGatt.connect();
}
你应该注册一个回调以知道连接是否成功。
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
//bluetooth is connected so discover services
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
//Bluetooth is disconnected
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// services are discoverd
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
}
};
一旦发现服务,您可以写入或读取服务。
写入到一个服务使用这种方法
private boolean writeRXCharacteristic(byte[] value) {
BluetoothGattService RxService = mBluetoothGatt.getService(/*Place service UUID*/);
if (RxService == null) {
//Service not supported
return false;
}
BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(/*RX_CHAR_UUID*/);
if (RxChar == null) {
// service not supported
return false;
}
RxChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
RxChar.setValue(arr);
return iGatt.writeCharacteristic(iChar);
}
谢谢你的建议。 iGatt,iChar和arr从哪里来?我对这些事情并不熟悉。我需要在writeRXCharacteristic函数中初始化这些值吗?另外什么时候应该调用writeRXCharacteristic函数? –