我想配对两个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();
}
}
答案 0 :(得分:0)
您是否尝试通过反射调用createBond()?
这适用于我,设备是BluetoothDevice:
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
答案 1 :(得分:0)
.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);
}
}