Question

I have a BluetoothSocket that I am reading data from, using a separate Thread process from the GUI. I wrap the InputStream in DataInputStream so I can do use a a readFully(..) to wait for a specified amount of data. I can run this code for about an hour and then the program locks up and when I debug its stuck at the readFully(). I included in my GUI thread BroadcastReceivers to notify me when the bluetooth disconnects. The BroadCastReceivers never get notified. Not sure why the device just stops sending data if that is the case or not eve sure if the Bluetooth SPP gets dropped but the socket is still open so the Bluetooth Disconnect message never happens. Any ideas as to the fix or even why or how to debug why its stuck would be appreciated.

Here is my ReadBlueTooth class...

public class ReadBlueToothData extends Thread {
    private BluetoothSocket btSocket;
    private BluetoothAdapter bta;
    private DataInputStream dinput;

    public ReadBlueToothData(Activity a,String mac) {
       ...init object...
    }

    public void run() {
        // if socket connected otherwise stop
        if (dinput==null) return;

        byte[] byteArray = new byte[3];


        while (!Thread.interrupted()) {

            dinput.readFully(byteArray, 0, 3);

            // DO something ....
        }

        // close out InputStream nicely
        if (dinput!=null) {
            try {
                dinput.close();

            } catch (IOException e) {   }
        }

        if (btSocket != null) {
            try {
                btSocket.close();
            } catch (IOException e) {}
        }
    }
}
Was it helpful?

Solution

I don't get this error anymore by doing this gracefully when detecting a Bluetooth disconnect.

dinput.close();
readBlueToothData().interrupt();
btSocket.close();
//make sure to check for nulls for all these too

and also then do a check by looking at the data coming in and if the buffer doesn't increase in size then also call disconnect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top