Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to a specific bluetooth port on a bluetooth device using Android

Is there any way for Android to connect to a Bluetooth device using a specific port instead of using service UUID? I know this option is available in other platforms which provide Bluetooth support (Java ME for example by specifying a "btspp://" style URL).

Thanks!

like image 585
dcoder Avatar asked Dec 27 '22 04:12

dcoder


1 Answers

Ok, it's been a while, but I found a solution to the problem. I actually intended to give up and use UUID, but I kept getting a Service Discovery Failed (IO)exception, and when I tried to find a solution to the service discovery issue, I found the solution to my original question... Ain't life something?:)

Anyways, this is the link I stumbled upon, though you should note there is a mistake in the answer (they actually simply connected to port 1, instead of using a service UUID).

And after this short history lesson, here is the solution:

Using reflection, it is possible to create the Rfcomm socket connecting to a port number instead of UUID:

int bt_port_to_connect = 5; // just an example, could be any port number you wish
BluetoothDevice device = ... ; // get the bluetooth device (e.g., using bt discovery)
BluetoothSocket deviceSocket = null;
...
// IMPORTANT: we create a reference to the 'createInsecureRfcommSocket' method
// and not(!) to the 'createInsecureRfcommSocketToServiceRecord' (which is what the 
// android SDK documentation publishes
Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});

deviceSocket = (BluetoothSocket) m.invoke(device,bt_port_to_connect);

A few things to notice:

  1. since we're using Invoke, the first parameter is the object we're invoking the method on, the second parameter of invoke is actually the first function parameter)
  2. There is also a secure version available ('createRfcommSocket'), which accepts a bluetooth channel number as a single parameter (again, since this is invoke style, you'll need to pass the object to invoke the method on, as mentioned in -1- )
  3. I found what appears to be a link to these functions' prototypes

Good luck to all.

like image 58
dcoder Avatar answered Jan 05 '23 17:01

dcoder