在GATT之前,createRfcommSocketToServiceRecord,createInsecureRfcommSocketToServiceRecord
方法可以使设备配对,
但是GATT没有关于配对设备的选项,只使用BluetoothDevice.connectGatt(…)
如果设备已连接,我想创建一个配对设备。
thx .
据我所知,在BLE中启动配对过程有两种方式:
1)从API 19开始,你可以通过调用mBluetoothDevice.createBond()
来开始配对。您无需连接远端BLE设备即可启动配对过程。
2)当您尝试执行Gatt操作时,让我们以
方法为例mBluetoothGatt.readCharacteristic(characteristic)
如果远程BLE设备需要绑定以进行任何通信,则当回调
onCharacteristicRead(
BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status)
被调用,其status
参数值将等于GATT_INSUFFICIENT_AUTHENTICATION
或GATT_INSUFFICIENT_ENCRYPTION
,而不等于GATT_SUCCESS
。如果发生这种情况,配对过程将自动启动。
下面是一个例子,当onCharacteristicRead
回调被调用时,它什么时候失败
@Override
public void onCharacteristicRead(
BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status)
{
if(BluetoothGatt.GATT_SUCCESS == status)
{
// characteristic was read successful
}
else if(BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION == status ||
BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION == status)
{
/*
* failed to complete the operation because of encryption issues,
* this means we need to bond with the device
*/
/*
* registering Bluetooth BroadcastReceiver to be notified
* for any bonding messages
*/
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
mActivity.registerReceiver(mReceiver, filter);
}
else
{
// operation failed for some other reason
}
}
有人提到这个操作会自动启动配对过程:Android蓝牙低功耗配对
接收器是这样实现的
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED))
{
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
switch(state){
case BluetoothDevice.BOND_BONDING:
// Bonding...
break;
case BluetoothDevice.BOND_BONDED:
// Bonded...
mActivity.unregisterReceiver(mReceiver);
break;
case BluetoothDevice.BOND_NONE:
// Not bonded...
break;
}
}
}
};