Search code examples
androidbluetoothmac-addressrfcommbeacon

Android Bluetooth connection using createInsecureRfcommSocketToServiceRecord without MAC address


I am creating an application for communicating Android mobile devices with Bluetooth beacons. I have successfully achieved this between one beacon (which acts as a client) and one android mobile device (acts as the server, listening for the connection). Please find the code snippet below,

Client app

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(MACaddress);
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("f3c74f47-1d38-49ed-8bbc-0369b3eb277c"));
mBluetoothAdapter.cancelDiscovery();
socket.connect();

Server app

mmServerSocket = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("NAME", UUID.fromString("f3c74f47-1d38-49ed-8bbc-0369b3eb277c"));
socket = mmServerSocket.accept();

This works fine with one mobile device (server) where I am able to obtain its MACaddress by scanning nearby Bluetooth devices. But consider the case when there are around 20-25 mobile devices present in range - scanning would consume so much time. I would like to do this without performing a scan.

Is there a way to achieve this without using the server's MACaddress? Can the connection be established with the unique UUID alone? Please note that I do not want to pair the devices.

Any other solution in this regard is also welcome. Thanks!


Solution

  • You can't create a socket connection to a bluetooth device without identifying the bluetooth device itself, and the unique identifier for bluetooth device is a MAC Address. Even if there were an Android API that would allow you to do this via UUID alone, the underlying implementation would still have to search for nearby devices (e.g. scan) and find one that is accepting socket connections using the UUID. So the scanning mentioned in the question would still have to happen.

    Yes, scanning can use a bit of power and CPU intensive if a number of bluetooth devices are around. You can limit this two ways:

    1. Only scan briefly. For your use case, it seems you could just scan for a few seconds then stop once you find a supporting device. This should not be too resource intensive.

    2. Use scan filters on Android 5.0+ to match only the devices that you are interested in.