2015-10-02 3 views
0

Я создаю новый класс подключения для устройства Bluetooth на Android Studio. Я не могу понять, почему выбрано исключение во время разработки.BluetoothDevice getmethod NoSuchMethodException

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

ответ

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 
} 
Смежные вопросы