Android,如何将BLE设备配对设备(已绑定)

use*_*211 8 android bluetooth-lowenergy gatt

在GATT之前,createRfcommSocketToServiceRecord,createInsecureRfcommSocketToServiceRecord

方法可以使配对设备,

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

如果它已连接,我想制作配对设备.

谢谢.

Kik*_*iki 22

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

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

2)当你尝试进行Gatt操作时,让我们以方法为例

mBluetoothGatt.readCharacteristic(characteristic)
Run Code Online (Sandbox Code Playgroud)

如果远程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
    }
}
Run Code Online (Sandbox Code Playgroud)

其他人提到此操作会自动启动配对程序: 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;
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)