蓝牙配对 - 如何显示简单的 Cancel/Pair 对话框?

Bluetooth pairing - how to show the simple Cancel/Pair dialog?

我已经在 GitHub 准备了 a simple test project 这个问题。

我正在尝试创建一个 Android 应用程序,它会从计算机屏幕上扫描二维码,然后使用数据(MAC 地址和 PIN 或哈希值)为 轻松 与蓝牙设备配对(绑定)。

类似于流行的 InstaWifi app - 但适用于经典蓝牙。

出于测试目的,我还没有进行任何条形码扫描,只是显示了一个设备列表:

用户触摸其中一个设备后,在 MainActivity.java:

中尝试配对
private void startBluetoothPairing(BluetoothDevice device) {
    Intent pairingIntent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
    pairingIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
    pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
                BluetoothDevice.PAIRING_VARIANT_PIN);
    pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 1234);
    //device.setPin(new byte[]{1,2,3,4});  <- DOES NOT CHANGE ANYTHING
    //device.setPairingConfirmation(false);
    startActivityForResult(pairingIntent, REQUEST_BT_SETTINGS);
}

不幸的是,弹出窗口仍然要求输入 PIN:

因为我实际上已经在我的源代码中指定了一个 PIN,所以我实际上期待显示另一个更简单的系统对话框(在进行 NFC OOB 配对时显示这个对话框):

通过搜索解决方案,我知道有一个 setPin() 方法,但它不适用于此处(或者是吗?) - 因为我正在尝试将整个智能手机与蓝牙设备配对,并且不仅仅是应用程序...

我的问题:如何让AndroidOS显示简单的Cancel/Pair对话框?

在 GitHub 搜索 Bluetooth pairing request 字符串没有显示任何提示...

更新: 根据 unrealsoul007 的建议(谢谢)我已经更新了 MainActivity.java 中的源代码,现在显示了简单的 Cancel/Pair 对话框:

private void startBluetoothPairing(BluetoothDevice device) {
    Intent pairingIntent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
    pairingIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
    pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
        BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION);
    pairingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivityForResult(pairingIntent, REQUEST_BT_PAIRING);
}

但是我不确定如何完成配对过程 - 因为 onActivityResult 甚至在对话框关闭之前就用 resultCode=0 调用了:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    // this is called before user clicks Cancel or Pair in the dialog
    if (requestCode == REQUEST_BT_PAIRING) { 
        if (resultCode == Activity.RESULT_OK) {  // 0 != -1
            Log.d("XXX", "Let#s pair!!!!"); // NOT CALLED
        }

        return;
    }
}

系统会提示您输入 PIN 码,因为这是您在 pairingIntent 中请求的内容。

而不是使用

pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
                BluetoothDevice.PAIRING_VARIANT_PIN);
pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 1234);

使用

pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PASSKEY_CONFIRMATION);

如前所述here

The user will be prompted to confirm the passkey displayed on the screen or an app will confirm the passkey for the user.