Bluetooth Pairing with Nrf UART is not working properly

眉间皱痕 提交于 2019-11-29 17:51:22

You can bypass the native Bluetooth pairing process and pair with Bluetooth peripheral pro-grammatically. Try this:

Register a receiver for BluetoothDevice.ACTION_PAIRING_REQUEST with the highest priority.

private void notPaired(){
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
    filter.setPriority(SYSTEM_HIGH_PRIORITY-1);
    registerReceiver(mReceiver, filter);
    mDevice.createBound();// OR establish connection with the device and read characteristic for triggering the pairing process 
    getBoundState();
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
            final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);

            if(type == BluetoothDevice.PAIRING_VARIANT_PIN){
                byte[] pin = "123456".getBytes();
                device.setPin(pin);
                Log.i("Pairing Process ", "Pairing Key Entered");
                abortBroadcast();
            }else
                Log.i("Pairing Process: ", "Unexected Pairing type");
        }
    }
};

To make sure that device is paired register a receiver for BluetoothDevice.ACTION_BOND_STATE_CHANGED

private void getBoundState(){
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    registerReceiver(boundStateReciver, filter);
}

private final BroadcastReceiver boundStateReciver= new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            final int d = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,-1);
            switch(d){
                case BluetoothDevice.BOND_BONDED:
                    Log.i("Pairing Process ", "Paired successfully");
                break;
            }
        }
    }
};

In Manifests add this permission

<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!