views:

36

answers:

1

Hi ~

I could connect to two devices from Android based cell phone simultaneously using SPP, but once I turn on the inputstream (like socket.getInputStream()), one of them will return 0 in the stream, that is, no data available on the stream. For example, thread A(thA) and thread B(thB) connected to device A(devA) and device B(devB) respectively. So, thA uses inputstream A(inA) to receive data from devA, thB uses inputstream B(inB) to receive data from devB. As follow: devA --->inA --->thA devB --->inB --->thB It works fine if I connect to each device separately. However, in the case of connecting two devices at the same time, then only inA or inB has data on it.

If it happens to you, please share your experence with me, I would be very appreciated!! Thank you in advance. YT

A: 
  1. Why are you using reflection for the createRFCommSocket? device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

as opposed to

        try {mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
        } catch (Exception e1) {
            msg ("connect(): Failed to bind to RFCOMM by UUID. msg=" + e1.getMessage());
            return false;
        }

The reflection can easily be the source of problems. If there is no reason to use it then avoid it at all costs.

Furthermore, if the getClass call fails, then your "m" variable will be null, and you're not trapping for that situation. You should generalize your exception more too, instead of using specific exceptions, just use "Exception" Like in my code snippet above. It's much easier than adding a catch for every possible type of exception that might get thrown.

  1. I'm confused about what you're doing with the handlers, it doesn't make sense to me. Can you remove the handler code to simplify things?

  2. There's just too much complication. Remove all the reflection, extra catch's.

  3. It's good coding practice to make your methods one page or less. When a method is more than a page it is too complicated and it makes reading it AND debugging it very difficult. Reduce the size of your methods by creating other methods to perform common tasks.

  4. Separate your connect() logic, from your I/O logic. You should have a method for sending data, and a method for receiving data, a method for connect(). Then once you get those working, chunk up and create methods for higher level I/O for sending and receiving whole blocks of data. then perfect those methods and keep growing up and up.

in my code the read, write, connect, and ALL I/O methods are only 1-20 lines each. Keep them very simple because your I/O logic is at the core of your app and it needs to be clean clean clean.

Brad Hein
I update my information as follow:http://stackoverflow.com/questions/3857508/could-more-than-one-rfcomm-channels-be-created-per-time