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;
}

发布于 2016-06-01 00:37:50
这行代码:
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
}https://stackoverflow.com/questions/32909243
复制相似问题