Search code examples
javaandroidbluetoothdistancerssi

Getting distance between two android devices using bluetooth


I founds lots of similar questions on SO. But most of them didn't work or out of date.

I'm trying to build an android application which uses Bluetooth to scan nearby devices, I want the application to alert the user when a phone is nearly 2 meters away.

So I'm trying to get the distance using the following method found on SO.

protected double calculateDistance(float txPower, double rssi) {

    if (rssi == 0) {
        return -1.0; // if we cannot determine distance, return -1.
    }

    double ratio = rssi * 1.0 / txPower;

    if (ratio < 1.0) {
        return Math.pow(ratio, 10);
    } else {
        double accuracy = (0.89976) * Math.pow(ratio, 7.7095) + 0.111;
        return accuracy;
    }
}

The method is returning a weird small number, I don't think it's even the distance because it just keeps on changing even when the phone is in the same location.

Any idea about how to get an accurate distance?


Solution

  • For those who are looking for the distance between devices. After lots of research and searching, I found out that getting the accurate or exact distance is not something easy to implement. Android and Apple are still working on stuff like this.

    What I used as a workaround since I was in a hurry for a solution, is something called Nearby Messages API.

    It is a publish-subscribe API, available for both Android and iOS. Which catch the nearby devices that are subscribed to a specific Message using a specific MessageListener. And you can add some Strategy to the Listener in order to know if the distance is really near EARSHOT or not.

    It is exactly what I needed, so that worked for me.