首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BluetoothDevice getmethod NoSuchMethodException

BluetoothDevice getmethod NoSuchMethodException
EN

Stack Overflow用户
提问于 2015-10-02 22:17:11
回答 1查看 764关注 0票数 0
代码语言:javascript
复制
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;
}

EN

回答 1

Stack Overflow用户

发布于 2016-06-01 00:37:50

这行代码:

代码语言:javascript
复制
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);

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

代码语言:javascript
复制
catch(NoSuchMethodException e){
    //Insert code here
}

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

代码语言:javascript
复制
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类来处理每个单个异常。在这种情况下,您的代码应该如下所示:

代码语言:javascript
复制
try {
    temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (Exception e) {
    //Enter code here
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32909243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档