配对两个Android蓝牙设备没有任何密码弹出窗口

时间:2014-12-11 05:55:45

标签: android bluetooth

我想配对两个Android蓝牙设备(Kitkat),没有任何弹出密钥交换。我使用反射尝试了广播接收器内的setpin()和cancelPairingUserInput()方法PAIRING_REQUEST intent,但没有得到任何结果。任何人都可以帮助我吗?

 if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){

               BluetoothDevice localBluetoothDevice = (BluetoothDevice)intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
               try {

                   Log.d("setPin()", "Try to set the PIN");
                   Method m = localBluetoothDevice.getClass().getMethod("setPin", byte[].class);
                   m.invoke(localBluetoothDevice, ByteBuffer.allocate(4).putInt(1234).array());
                   Log.d("setPin()", "Success to add the PIN.");
                 } catch (Exception e) {
                   Log.e("setPin()", e.getMessage());
                 }
               Class localClass = localBluetoothDevice.getClass();
               Class[] arrayOfClass = new Class[0];
               try {
                   localClass.getMethod("setPairingConfirmation", boolean.class).invoke(localBluetoothDevice, true);
                localClass.getMethod("cancelPairingUserInput", arrayOfClass).invoke(localBluetoothDevice, null);
            } catch (IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException | NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           }

2 个答案:

答案 0 :(得分:0)

您是否尝试通过反射调用createBond()?

这适用于我,设备是BluetoothDevice:

Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);

答案 1 :(得分:0)

  1. 从给定的Intent
  2. 获取设备和PIN(或配对密钥)
  3. 如果给定的PIN不是-1,请在设备中设置
  4. 调用设备的.setPairingConfirmation()方法
  5. .bluetoothEventReceived()回调方法中的代码(实现此目的)如下所示:

    private void bluetoothEventRecieved(Context context, Intent intent)
    {
        if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            int pin = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, -1);
            if (pin != -1) {
                byte[] pinBytes = String.format(Locale.US, "%04d", pin).getBytes();
                device.setPin(pinBytes);
            }
            device.setPairingConfirmation(true);
        }
    }