1

Hi I'm trying to implement a bluetooth library and in it I want to connect an rfcomm socket once and then reuse it on all calls. I want to know if it's connected or not in order to know if I should call the connect method. I can't find anything in the source code for Bluetooth sockets since it's all native calls and there's no isConnected method defined in the API... Does anyone have any experience with this?

ekatz
  • 963
  • 3
  • 18
  • 38

3 Answers3

2

I answered a similar question here. Starting from API Level 14 there is a isConnected method in the BluetoothSocket class available. For lower API levels, you may open a socket, do your work and close it again. However there are some thing you might have to consider, more in the linked answer.

Community
  • 1
  • 1
AgentKnopf
  • 4,295
  • 7
  • 45
  • 81
  • 1
    Some device always return false to the method isConnected – Anthone Feb 12 '15 at 14:40
  • @Anthone afaik per spec it should work. So if it does not work, I'd consider that an anomaly where it would probably make sense to file a bug report. Alternatively use Icsmoretto's answer for the time being. – AgentKnopf Feb 13 '15 at 10:12
1

isConnected() never works for me. Try something like this:

try {
  mSocket.connect()
} catch (IOException e) {
  // Create a new socket
  // mSocket.connect();
}
Lucas Moretto
  • 404
  • 1
  • 6
  • 18
  • 1
    Maybe it would help if you list the devices for which isConnected does not work and possibly file a bug report for them? – AgentKnopf Feb 13 '15 at 10:10
1

I think you would have a member variable maintain the state of your connection. on successful connection set it to true, start a thread that loops always reading bytes from the sockets inputstream and if you get an IOException on that thread, set your flag to false.

jkhouw1
  • 7,320
  • 3
  • 32
  • 24
  • since I'm trying to write a synchronous (blocking) call methodology, I'm going to do a write then immediately read, this means that I won't be able to maintain a thread that loops and always tries to read. however, if I understand your answer correctly, you say that I should assume that if I get a read exception from the socket's input or output streams, I can assume that the connection is dead. Is that correct? – ekatz May 19 '11 at 15:15
  • yes IO exceptions or a "bluetooth disconnected" intent tell us the connection is dead. check out https://github.com/gtosoft/libvoyager/blob/master/src/com/gtosoft/libvoyager/android/ELMBT.java – Brad Hein May 19 '11 at 16:53