the differences between createRfcommSocketToServiceRecord and createRfcommSocket
Asked Answered
M

1

41

What are the differences between these two ways below connecting to a bluetooth Device:

1)

UUID uuid = UUID.fromString(Values.SPP_UUID); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); 

2)

Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);

I find the first way cannot work all the time, sometimes it will work, but after I close the bluetooth device, it won't work again. The second way is always work well. I know it is just open the channel one to communicate with bluetooth, but I do not know how it can do that to connect to a bluetooth device without using uuid?

Moulton answered 9/5, 2013 at 8:38 Comment(2)
Do anybody know anything about this question? I really need you guys help.Moulton
From scanning over the documentation it looks like createRfCommSocket gives you a lot more control and fields to tinker withCelina
E
63

Think of it a bit like the difference between opening a TCP connection to a port you specify by number, and opening one to a port you look up by name from /etc/services.

createRfcommSocketToServiceRecord takes the UUID you pass and uses SDP to decide what radio channel to use for the connection. It also checks to make sure that a server is listening on the remote endpoint, with the same UUID. In this way, it's the most reliable way to get a connection: it'll always use the correct channel, and if opening the connection succeeds, you know something at the other end can understand your protocol.

In contrast, createRfcommSocket just connects to the channel you tell it. There's no way to know whether anything is listening on the remote endpoint: you only know the device is there. Also, your choice of radio channel may be completely inappropriate. That's why this function is not published in the API, and the other function is preferred.

createRfcommSocket may appear at first to be more reliable, but it's because it's not checking for the presence of a listener at the other endpoint: it's ignoring some error cases. This might be alright for experimenting, but it's no use for a production system, because often the user will forget to start the server on the other endpoint, and your app will fail in confusing ways.

Of course, as createRfcommSocket isn't published in the API, you've no guarantee it will continue to work at all in future releases of Android.

Expatiate answered 2/9, 2013 at 23:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.