BluetoothDevice getmethod NoSuchMethodException

时间:2015-10-02 14:17:11

标签: android android-studio bluetooth

我正在为Android Studio上的蓝牙设备创建新的连接类。我无法弄清楚为什么在设计时抛出异常。

public ConnectingThread(BluetoothDevice device,MainActivity activity,BluetoothAdapter adapter) {
    mainActivity=activity;
    bluetoothAdapter=adapter;
    BluetoothSocket temp = null;
    bluetoothDevice = device;

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    bluetoothSocket = temp;
}

Android studio look

1 个答案:

答案 0 :(得分:0)

该行:

temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);

有可能抛出NoSuchMethodException。您没有catch块来处理此异常。因此,您必须在现有catch块下添加另一个catch块,如下所示:

catch(NoSuchMethodException e){
    //Insert code here
}

此外,该行代码稍后将抛出以下异常,因此最好也处理它们:IllegalAccessExceptionInvocationTargetException。因此,您的try-catch块应如下所示:

try {
    temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
    e.printStackTrace();
}
catch(NoSuchMethodException ex){
    //Insert code here
}
catch(IllegalAccessException e){
    //Insert code here
}
catch(InvocationTargetException e){
    //Insert code here
}

或者,您可以使用常规Exception类处理每个异常。在这种情况下,您的代码应如下所示:

try {
    temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (Exception e) {
    //Enter code here
}