我正在为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;
}
答案 0 :(得分:0)
该行:
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
有可能抛出NoSuchMethodException。您没有catch
块来处理此异常。因此,您必须在现有catch
块下添加另一个catch
块,如下所示:
catch(NoSuchMethodException e){
//Insert code here
}
此外,该行代码稍后将抛出以下异常,因此最好也处理它们:IllegalAccessException
和InvocationTargetException
。因此,您的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
}