与Raspberry Pi 3的蓝牙连接:java.io.IOException:读取失败,套接字可能关闭或超时,读取ret:-1

时间:2018-02-11 23:57:16

标签: java android sockets bluetooth

我是Android新手,并且一直在使用tutorial来设置基本的Android应用程序,可以通过蓝牙连接到Raspberry Pi 3.我正在使用Android 7.0(Nougat)测试应用程序,但在尝试连接时遇到异常:

  

java.io.IOException:读取失败,socket可能关闭或超时,读取ret:-1

这似乎是一个相当普遍的例外,我已经尝试了很多建议来解决它,但无济于事。

我的Thread课程中出现错误。

new Thread(){
    public void run(){
        boolean fail = false;

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);

        try {
            bluetoothSocket = createBluetoothSocket(device);
        } catch(IOException e) {
            fail = true;
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
        }

        // Establish the Bluetooth socket connection
        try {
            bluetoothSocket.connect();
        } catch(IOException e){
            try {
//                            // fallback method for android >= 4.2
                bluetoothSocket = (BluetoothSocket)device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class).invoke(device, BTMODULEUUID);

                try {
                    bluetoothSocket.connect();
                } catch (IOException e2){
                    try{
                        fail = true;
                        bluetoothSocket.close();
                        handler.obtainMessage(CONNECTING_STATUS, -1, -1).sendToTarget();
                    } catch (IOException e3){
                        //@Todo Insert code to handle this
                        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                    }
                }

            } catch (NoSuchMethodException e2){
                //@Todo Insert code to handle this
                Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
            } catch (IllegalAccessException e2){
                //@Todo Insert code to handle this
                Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
            } catch (InvocationTargetException e2){
                //@Todo Insert code to handle this
                Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
            }


        }

        if(fail == false){
            connectedThread = new ConnectedThread(bluetoothSocket);
            connectedThread.start();

            handler.obtainMessage(CONNECTING_STATUS, 1, -1, name).sendToTarget();
        }
    }
}.start();

代码使用Android> = 4.2的回退,然后在尝试连接时捕获异常。

我的其余代码与教程相同,但如果需要,我可以发布更多代码。

更新

这已标记为此问题的副本:IOException: read failed, socket might closed - Bluetooth on Android 4.3

我尝试过该解决方案,并收到同样的错误。

bluetoothSocket = (BluetoothSocket)device.getClass().getMethod("createRfcommSocket", new Class[]{Integer.TYPE}).invoke(device, new Object[]{Integer.valueOf(1)});

0 个答案:

没有答案