1

我目前正在尝试以编程方式将我的 Android 设备(4.4.2 KitKat)与 .NET 项目中的蓝牙加密狗配对。

与用户输入的正常配对(密码对话框)有效,但我想绕过用户输入。

经过一番研究(这里 和这里)我设法想出了一些代码,但对话框仍然出现。

下面我有我的许可:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />

最低api级别设置为19,所以我应该有蓝牙特权。

特定设备配对代码:

    final String SERVER_MAC = "00:1A:7D:DA:71:07";
    final BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
    final ArrayList<BluetoothDevice> server = new ArrayList<>();
    ba.startDiscovery();
    BroadcastReceiver btReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice bd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(TAG,"Found device: " + bd.getName() + " : " + bd.getAddress());
                if(bd.getAddress().equals(SERVER_MAC)){
                    Log.d(TAG,"Server bluetooth found");
                    server.add(bd);
                    Log.d(TAG,"creating bond");
                    bd.createBond();
                    ba.cancelDiscovery();

                }
            }
            else if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
                Log.d(TAG,"setting info");
                setBluetoothPairingPin(server.get(0));
            }
        }
    };
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(btReceiver, filter);
    IntentFilter pairingRequest = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
    registerReceiver(btReceiver,pairingRequest);

和 ACTION_PAIRING_REQUEST 方法:

    byte[] pairingPin = "123456".getBytes();
    try{
        Log.d(TAG,"Trying to set pin");
        bluetoothDevice.getClass().getMethod("setPin", byte[].class).invoke(bluetoothDevice,pairingPin);
        Log.d(TAG,"Success setting pin");
        try{
            bluetoothDevice.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(bluetoothDevice, true);

            Log.d(TAG,"Success setting pairing confirmtion");
        }
        catch(Exception e){
            Log.d(TAG,"Exception: " + e.getMessage());
        }
    }
    catch(Exception e){
        Log.d(TAG,"Exception 2: " + e.getMessage());
    }

任何信息都有帮助。谢谢!

4

1 回答 1

0

不要要求 BLUETOOTH_PRIVILEGED,它可以在 7 之前的 Android 版本上运行。在这些版本上,只需要 BLUETOOTH_ADMIN。然后通过以下方式更改:https ://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-7.0.0_r24

于 2018-11-05T22:27:55.503 回答