How to programmatically pair a bluetooth device on Android

后端 未结 10 1948
轻奢々
轻奢々 2020-11-30 23:27

For my application I\'m trying to programmatically pair a bluetooth device. I\'m able to show the pairing dialog for the device I want to pair and I can enter a pincode. Whe

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 23:34

    It's my answer:

    in onCreate() write this:

        registerReceiver(incomingPairRequestReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST));
    

    then create variable

    private final BroadcastReceiver incomingPairRequestReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                BluetoothDevice dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //pair from device: dev.getName()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    dev.setPairingConfirmation(true);
                    //successfull pairing
                } else {
                    //impossible to automatically perform pairing,
                    //your Android version is below KITKAT
                }
            }
        }
    };
    

提交回复
热议问题