操作蓝牙时获取BluetoothDevie.isConnected()方法时出现异常,怎么解决?[复制链接]

获取设备连接状态的方法时,为什么返回的null,并且会进入异常?
isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);

完整代码如下:
boolean isDeviceConnected(BluetoothDevice device)

{
    Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
    Method method = null;

    try
    {
        Log.e("BthDevice.java","Action:开始获取蓝牙连接状态!");
        method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
    }
    catch (NoSuchMethodException e)
    {
        Log.e("BthDevice.java","Error:获取蓝牙连接状态失败!");
        e.printStackTrace();
    }

    method.setAccessible(true); //打开权限
    Method isConnectedMethod = null;
    try
    {
        Log.e("BthDevice.java","Action:开始获取蓝牙连接状态方法!");
        isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
    }
    catch (NoSuchMethodException e)
    {
        Log.e("BthDevice.java","Error:获取蓝牙连接状态方法失败!");
        e.printStackTrace();
    }

    method.setAccessible(true); //打开权限
    boolean isConnected = false;
    try
    {
        Log.e("BthDevice.java","Action:调用连接状态方法,读取连接状态!");
        isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
    }
    catch (IllegalAccessException e)
    {
        e.printStackTrace();
    }
    catch (InvocationTargetException e)
    {
        e.printStackTrace();
    }

    Log.e("BthDevice.java","Action:准备返回连接状态!");
    return isConnected;
}

错误提示:
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x419bae00)
Caused by: java.lang.NullPointerException

wanzhilin88 616查看 · 0回复 · 2019-1-22 14:58 有用(0
共0个回答
需要登入后才可以评论 登录 | 立即注册