Исключение IOException в классе для работы c Bluetooth

194
24 сентября 2019, 15:00

Всем привет. Пишу класс для работы с Bluetooth. В нем содержится два класса, которые наследуют Thread. Первый класс служит для соединения с Bluetooth устройством, а второй для передачи и приема данных.

В основном классе имеется метод stop(), который останавливает все потоки. Но при вызове данного метода, у меня вылетает исключение типа IOException, связанное с ошибкой чтения, не может читать далее, потому что bt socket close

E/BluetoothMan: ConnectedThread: run() -> Failed to read data
java.io.IOException: bt socket closed, read return: -1
    at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:573)
    at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:60)
    at ru.astar.myautobt.btconnector.BluetoothMan$ConnectedThread.run(BluetoothMan.java:292)

А вот сам метод stop() и два класса ConnectThread и СonnectedThread

public synchronized void stop() {
    // TODO закрыть все соединения
    if (connectedThread != null) {
        connectedThread.close();
        connectedThread = null;
    }
    if (connectThread != null) {
        connectThread.close();
        connectThread = null;
    }

    setConnectState(ConnectStatus.NONE);
    setDiscoverStatus(DiscoverStatus.NONE);
}
public synchronized void connect(BluetoothDevice device) {
    // TODO соединение с устройством
    if (connectThread != null) {
        connectThread.close();
        connectThread = null;
    }
    connectThread = new ConnectThread(device);
    connectThread.start();
    setConnectState(ConnectStatus.CONNECTING);
}
private synchronized void connected(BluetoothDevice device, BluetoothSocket socket) {
    // TODO запуск потока для передачи и приема данных
    if (connectedThread != null) {
        connectedThread.close();
        connectedThread = null;
    }
    connectedThread = new ConnectedThread(socket);
    connectedThread.start();
    setConnectState(ConnectStatus.CONNECTED);
}
public void write(byte[] bytes) {
    // TODO передача данных в BluetoothSocket
    if (D) Log.d(TAG, "write() -> bytes length = " + bytes.length);
    ConnectedThread tmp;
    synchronized (this) {
        if (connectState != ConnectStatus.CONNECTED) return;
        tmp = connectedThread;
    }
    tmp.write(bytes);
}
private class ConnectThread extends Thread {
    private BluetoothDevice device;
    private final BluetoothSocket socket;
    public ConnectThread(BluetoothDevice device) {
        this.device = device;
        BluetoothSocket tmpSocket = null;
        try {
            Method method = this.device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            tmpSocket = (BluetoothSocket) method.invoke(device, 1);
        } catch (Exception e) {
            Log.e(TAG, "ConnectThread() -> Error calling method createRfcommSocket()", e);
        }
        this.socket = tmpSocket;
    }
    @Override
    public void run() {
        try {
            if (adapter.isDiscovering())
                adapter.cancelDiscovery();
            socket.connect();
            connected(device, socket);
        } catch (IOException e) {
            Log.e(TAG, "ConnectThread: run() -> Error socket connecting", e);
        }
    }
    public void close() {
        try {
            socket.close();
        } catch (IOException e) {
            Log.e(TAG, "ConnectThread: close() -> Error closing socket", e);
        }
    }
}
private class ConnectedThread extends Thread {
    private final BluetoothSocket socket;
    private final InputStream inputStream;
    private final OutputStream outputStream;
    private boolean start;
    public ConnectedThread(BluetoothSocket socket) {
        this.socket = socket;
        this.start = true;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = this.socket.getInputStream();
            outputStream = this.socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "ConnectedThread() -> Failed to get IO streams", e);
        }
        this.inputStream = inputStream;
        this.outputStream = outputStream;
    }
    @Override
    public void run() {
        try {
            int readData;
            StringBuffer sb = new StringBuffer();
            while (start) {
                if (socket != null) {
                    readData = inputStream.read();
                    sb.append((char) readData);
                    int eof = sb.indexOf("\r\n");
                    if (eof > 0) {
                        callback.onReadData(sb.toString());
                        sb.delete(0, sb.length());
                    }
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "ConnectedThread: run() -> Failed to read data", e);
        }
    }
    public void write(byte[] bytes) {
        try {
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException e) {
            Log.e(TAG, "ConnectedThread: write() -> Failed to write in OutputStream ", e);
        }
    }
    public void close() {
        try {
            start = false;
            if (outputStream != null) outputStream.close();
            if (inputStream != null) inputStream.close();
            socket.close();
        } catch (IOException e) {
            Log.e(TAG, "ConnectedThread: close() -> Failed to close socket", e);
        }
    }
}
READ ALSO
Работа WebSocket в Java (spring и android)

Работа WebSocket в Java (spring и android)

Никак не могу понять, как реализовывать сокеты на java на клиентеЕсть несколько проблем:

162
При добавлении зависимости в проект MAVEN и развертывании на GLASSFISH вылетает ERROR

При добавлении зависимости в проект MAVEN и развертывании на GLASSFISH вылетает ERROR

В web проекте Java есть 2 объекта типа String - JSON и JSONSchemaПытаюсь проверить соответствует ли json схеме

168
transceive() возвращает не то, что должен

transceive() возвращает не то, что должен

Пытаюсь записать/прочитать информацию с NFC тэга (NfcV) M24LR64E-R

162
Почему выдаёт ошибку java.lang.StringIndexOutOfBoundsException: length=0; index=0?

Почему выдаёт ошибку java.lang.StringIndexOutOfBoundsException: length=0; index=0?

У меня есть две картинки, они кликабельные, нажимая на эти картинки, я меняю цвет Action BarНо один код работает отлично, другой абсолютно такой...

188