Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 以编程方式配对蓝牙设备_Android_Android Bluetooth - Fatal编程技术网

Android 以编程方式配对蓝牙设备

Android 以编程方式配对蓝牙设备,android,android-bluetooth,Android,Android Bluetooth,我使用此方法将设备与android手机配对: private void pairDevice(BluetoothDevice device) { try { device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true); device.getClass().getMethod("cancelPairingUserInput").invoke

我使用此方法将设备与android手机配对:

private void pairDevice(BluetoothDevice device) {
    try {
        device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
        device.getClass().getMethod("cancelPairingUserInput").invoke(device);
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Toast.makeText(getActivity(), "Error on pairing devices", Toast.LENGTH_LONG).show();
    }
}
我在三台设备上检查了它。其中一款手机有4.2.2版本的android,另外两款手机使用4.4.2版本的android

pairDevice
方法在这两个4.4.2设备上正常工作。但是,它在4.2.2设备上给出了
java.lang.reflect.InvocationTargetException
错误。这三种设备都有蓝牙V4(根据其规格,分别为V4.0、A2DP和LE)

在配对之前,我会使所有设备可见并可发现。另外,我不想同时将我的设备连接到多个手机


我的代码怎么了?

试试这段代码,它对我有用

  private void pairDevice(BluetoothDevice device) {
            try {
                Method method = device.getClass().getMethod("createBond", (Class[]) null);
                method.invoke(device, (Object[]) null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

哪一行正在抛出异常?很可能缺少某种方法。为什么不尝试强制转换来检测可用的API呢?这一行:m.invoke(device,(Object[])null
Toast
实际类名device.getClass().getName(),并在API级别17(4.2)中查找该类。然后找到
createBond()
或类似方法的正确签名。为什么不使用BluetoothAdapter类?我已经使用BluetoothAdapter类来了解蓝牙状态和配对设备。我如何使用BluetoothAdapter来配对设备???