Соединение Bluetooth с BLE не работает в Android - PullRequest
1 голос
/ 12 июня 2019

Я пытался соединить свой андроид с BLE устройством.Проблема в том, что когда я вызываю запрос на сопряжение, появляется диалоговое окно.Но когда я ввел свой пароль, он не соединяется или onActivityResult не вызывается.Так что же делать для успешного сопряжения?

   private void startBluetoothPairing(BluetoothDevice device) {
    String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
    Intent intent = new Intent(ACTION_PAIRING_REQUEST);
    String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
    intent.putExtra(EXTRA_DEVICE, device);
    String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
    int PAIRING_VARIANT_PIN = 0;
    intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ((Activity) appContext).startActivityForResult(intent,1);
   }

OnActivityResult не вызывается.

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v("TAG","Bluetooth Device!!");
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            BluetoothDevice bluetoothDevice = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Parcel parcel = Parcel.obtain();
            data.getParcelableExtra(BluetoothDevice.EXTRA_PAIRING_KEY).writeToParcel(parcel, 0);
            byte[] bytes = parcel.marshall();
            parcel.recycle();
            bluetoothDevice.setPin(bytes);
            bluetoothDevice.createBond();
        }
    }
}

Решенная проблема: Обновленный код:

Зарегистрированный broadCasterReciever при запуске приложения

    IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
    intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    appContext.getApplicationContext().registerReceiver(broadCastReceiver,intentFilter);

Реализация broadcastReciever.

    private  String BLE_PIN= "000012";
    private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
                {
                    BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    bluetoothDevice.setPin(BLE_PIN.getBytes());
                    Log.e("TAG","Auto-entering pin: " + BLE_PIN);

                }
           }
      };

И я позвонил device.createBond () после обнаружения устройства.

1 Ответ

1 голос
/ 12 июня 2019

Вот то, что я использовал, и оно работало хорошо для меня.

Сопряжение с устройством

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                    BluetoothActivity.this.registerReceiver(mReceiver, filter);
                    device.createBond();

BroadcastReceiver для проверки, если устройство сопряжено

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                String address = device.getAddress();
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    //Device Paired
                }
            }
        }
    };

Отменить регистрацию получателя в onDestroy

BluetoothActivity.this.unregisterReceiver(mReceiver);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...