Сопряжение Bluetooth с Nrf UART не работает должным образом

Сопряжение Bluetooth не работает должным образом. Я разрабатываю приложение на основе сопряжения Bluetooth с UART. Здесь я включил свою концепцию и программу. Помогите мне решить проблему.

Мой ожидаемый результат: если пользователь нажимает кнопку «Подключиться». Это должна быть пара без пользовательского ввода и экрана подтверждения для запроса пары и PIN-кода. Наконец, устройство отвечает на подключение.

Мой фактический результат - это экран подтверждения, и откроется всплывающее окно ввода данных пользователем. После этого устройство будет сопряжено. Наконец, устройство не отвечает на сообщение «Я подключен».

Я застрял в этой проблеме более 2 дней. Помогите мне решить эту проблему.

<сильный>1. Зарегистрируйте СОПРЯЖЕНИЕ в методе onstart()

          IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
         this.registerReceiver(mPairingRequestReceiver, filter);

<сильный>2. BroadcastReceiver для получения PairingRequest.

  private BroadcastReceiver mPairingRequestReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
            try {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int pin = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 123456);
                //the pin in case you need to accept for an specific pin
                byte[] pinBytes;
                pinBytes = ("" + pin).getBytes("UTF-8");
                device.setPin(pinBytes);


        } catch (Exception e) {
                Log.e(TAG, "Error occurs when trying to auto pair");
                e.printStackTrace();
            }
        }
    }
};

/* После подключения устройств я создаю Bond*/

     @Override
     public void onDeviceConnected(BluetoothDevice device) {

        device.createBond();

      }

person sivaprakash    schedule 22.01.2018    source источник


Ответы (1)


Вы можете обойти собственный процесс сопряжения Bluetooth и программно выполнить сопряжение с периферийным устройством Bluetooth. Попробуй это:

Зарегистрируйте получателя для BluetoothDevice.ACTION_PAIRING_REQUEST с наивысшим приоритетом.

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");
        }
    }
};

Чтобы убедиться, что устройство сопряжено, зарегистрируйте приемник для 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;
            }
        }
    }
};

В манифестах добавьте это разрешение.

<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
person Salman Naseem    schedule 22.01.2018
comment
вам нужно установить максимальный приоритет для вашего IntentFilter, чтобы обойти всплывающее окно сопряжения системы. - person Salman Naseem; 22.01.2018
comment
Я пробовал как ВЫСОКИЙ, так и НИЗКИЙ приоритет. Он не работает нормально. Показывает одно и то же всплывающее окно. - person sivaprakash; 22.01.2018
comment
Вы, ребята, не видите всплывающее окно сопряжения, которое появляется и исчезает на долю секунды? - person Yogesh Byndoor; 07.11.2018
comment
@YogeshByndoor установил высокий приоритет для фильтра намерений filter.setPriority(SYSTEM_HIGH_PRIORITY-1); - person Salman Naseem; 07.11.2018