10

在 GATT 之前,createRfcommSocketToServiceRecord,createInsecureRfcommSocketToServiceRecord

方法可以使配对设备,

但是 GATT 没有关于配对设备的选项,只能使用 BluetoothDevice.connectGatt(...)

如果它已经连接,我想制作一个配对设备。

谢谢。

4

1 回答 1

26

据我所知,在 BLE 中启动配对程序有两种方法:

1) 从 API 19 起,您可以通过调用mBluetoothDevice.createBond(). 您无需连接远程 BLE 设备即可开始配对过程。

2)当你尝试做一个 Gatt 操作时,我们以方法为例

mBluetoothGatt.readCharacteristic(characteristic)

如果需要绑定远程 BLE 设备进行任何通信,那么当回调

onCharacteristicRead( BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)

被调用它的status参数值将等于GATT_INSUFFICIENT_AUTHENTICATIONGATT_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 Bluetooth Low Energy Pairing

这就是接收器的实现方式

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;
            }
        }
    }
};
于 2014-07-14T15:38:48.980 回答