我的蓝牙连接在Android中意外关闭

时间:2017-08-15 14:11:12

标签: android sockets bluetooth

java.io.IOException: bt socket closed, read return: -1
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:434)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.InputStreamReader.read(InputStreamReader.java:231)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.readLine(BufferedReader.java:397)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at com.example.lg.scoreboardapp.MainActivity$ConnectThread.run(MainActivity.java:336)

有时在我的应用中,客户意外关闭。 我不知道为什么...... 我有三次转移。一台设备是服务器。其他人是客户。 它们连接良好,但一个客户端已关闭。其他客户仍然开放。 请给我解决方案...... !! 这是MainActivitity .. 336Line enter code here

while(socket != null){
    i++;
    Log.d("MAinActivity","-----------------"+i+"-----------------------------");
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    final String str1 = in.readLine(); //<<---Line 336
    Log.d("MainActivity","--------------------------------------"+str1+i);
    json1 = str1;
    parse();
}

这是ConnectThread客户端

private class ConnectThread extends Thread {
    private BluetoothSocket socket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Toast.makeText(MainActivity.this, "연결에 실패하였습니다.\n다시 시도하여 주세요", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            //mkmsg("Client connection failed: "+e.getMessage().toString()+"\n");
        }
        socket = tmp;

    }

    public void run() {
        // mkmsg("Client running\n");
        // Always cancel discovery because it will slow down a connection
        mBluetoothAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket.connect();
        } catch (IOException e) {
            //mkmsg("Connect failed\n");
            e.printStackTrace();
            try {
                socket.close();
                socket = null;
            } catch (IOException e2) {
                //mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
                socket = null;
                e2.printStackTrace();
            }
            // Start the service over to restart listening mode
        }
        // If a connection was accepted
        if (socket != null) {
            //mkmsg("Connection made\n");
            //mkmsg("Remote device address: "+socket.getRemoteDevice().getAddress().toString()+"\n");
            //Note this is copied from the TCPdemo code.
            try {
                int i=0;
                while(socket != null){
                    i++;
                    Log.d("MAinActivity","-----------------"+i+"-----------------------------");
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    final String str1 = in.readLine();
                    Log.d("MainActivity","--------------------------------------"+str1+i);
                    json1 = str1;
                    parse();
                }
                Log.d("MainActivity_341Line","socket is null.......... check this");
                handler.post(new Runnable() {
                    @Override
                    public void run() {
    Toast.makeText(getApplicationContext(),"MainActivity_341Line   socket is null.......... check this",Toast.LENGTH_LONG);

                    }
                });


            } catch(Exception e) {
                //mkmsg("Error happened sending/receiving\n");
                e.printStackTrace();

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Error happened sending/receiving\\n",Toast.LENGTH_LONG);
                        Log.d("MainActivity_341Line","Error happened sending/receiving");
                    }
                });

                try {
                    socket.close();
                    socket = null;
                } catch (IOException e2) {
                    //mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
                    socket = null;
                    Log.d("MainActivity_341Line","Error happened "+e2);
                    e2.printStackTrace();
                }


            }
        } else {
            //mkmsg("Made connection, but socket is null\n");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),"Made connection, but socket is null\\n",Toast.LENGTH_LONG);
                }
            });
        }


    }

    public void cancel() {
        try {
            socket.close();
            Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将ConnectThread中的run()方法替换为:

    public void run()
    {
        Log.e(TAG, "BEGIN mConnectThread");
        setName("ConnectThread");

        mAdapter.cancelDiscovery();

        try
        {
            mmSocket.connect();
        }
        catch (IOException e)
        {
            try
            {
                Log.e(TAG,"Trying fallback...");
                mmSocket = (BluetoothSocket)
                        mmDevice.getClass()
                                .getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice, 2);
                mmSocket.connect();
                Log.e(TAG,"Connected");
            }
            catch (Exception e2)
            {
                Log.e(TAG, "Couldn't establish Bluetooth connection!");
                try
                {
                    mmSocket.close();
                }
                catch (IOException e3)
                {
                    Log.e(TAG, "unable to close() " + " socket during connection failure", e3);
                }
                connectionFailed();
                return;
            }
        }

        synchronized (BluetoothHelper.this)
        {
            mConnectThread = null;
        }

        connected(mmSocket, mmDevice);
    }