Android: BluetoothSocket receives its own output Android: BluetoothSocket receives its own output android android

Android: BluetoothSocket receives its own output


I scoured over the Bluetooth classes sources. The workaround seems legit from the first glances. Try this first:

if (delay == 0) {    Log.i("WRT", "Written to RaspberryPi");    out.write("Hello Raspberry. It's me, AndroidPhone".getBytes());    out.flush(); // <-- You are not flushing     delay = 100000000;}

And the message sticks in you socket for you to read over and over again.

If that does not fix it the other option I can think of is that somehow the socket is initialized to be a socket to your Android device. The .createRfcommSocket() method seems to create a socket to your own device if the Bluetooth device is null when the socket was being created. I'm not sure how this would exactly happen, but if the Raspberry Pi's state is somehow mangled after exception I suppose it could be something to look into.

On the raspy side: If you are just starting both of those threads doesn't it mean that you are constantly sending messages to /dev/rfcomm0 and flushing. I recommend that you change it so that raspy reacts to a received message by sending back the wanted message instead of spamming all the time. I'm not sure if this is part of your problem but it would at least make debugging & development a bit easier.


I am not sure if this is the solution you need, because I don't know if you are using bluetooth classic or bluetooth 4.0>+, but I wrote a library for text based BLE and WiFi P2P 2-way communication for android (and I know the Raspberry Pi is capable of BLE communication), I don't create a socket connection for BLE communication though, but I do for WiFi P2P. Take a look, I hope it helps. It isn't published yet, so you would have to clone/fork the repo.


I think you have trouble writing
As far as I know, for buffer, should use \n and ...

bluetoothWriter.write("This is RaspPi\n");

But I prefer to use a combination of DataOutputStream and BufferedReader

For Read:

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));        try {          String line = bufferedReader.readLine();System.out.println(line);        } catch (IOException e) {          e.printStackTrace();        }

for write:

DataOutputStream dataOutputStream = new DataOutputStream(outputStream);    String s = "Hi\n";    try {      dataOutputStream.write(s.getBytes());    } catch (IOException e) {      e.printStackTrace();    }

It is better to correct the point made by a dear friend about flush() ...

I'm not sure, please test yourself ...