Java – How do I get a remote device custom Bluetooth name in Android?

How do I get a remote device custom Bluetooth name in Android?… here is a solution to the problem.

How do I get a remote device custom Bluetooth name in Android?

I want to retrieve the custom name of a remote Bluetooth device in Android.
I’m talking about the name found in the phone settings under Settings / Bluetooth and paired devices.

For example, I have a remote Bluetooth device called “DoorControl”. Under Settings->Bluetooth->paired devices, I renamed the device to “CTRL”. Now I want to access the name of the definition so that it is displayed for the user.

I want to display that name in the list of Bluetooth devices.

knownDevicesAdapter.clear();
knownDevicesArray = mBluetoothAdapter.getBondedDevices();

if (knownDevicesArray.size() > 0) {
    for (BluetoothDevice device : knownDevicesArray) {
        if (device.getName().contains("Door")) {
            knownDevicesAdapter.add(device.getName() 
                    + /*HERE I WANT THE CUSTOM NAME TO SHOW*/ "\n" 
                    + device.getAddress());
        }
    }
}

device.getName(), which returns only the full original name of the device, in this case “DoorControl”.

This is necessary because there can be 4 devices called DoorControl. The only way to distinguish them is by their address. But for a user-friendly approach, it would be much easier for them to rename the device in the Bluetooth settings and only show that name as the “nickname” of the device.

Is there a way to access custom names so I don’t have to write a full “rename-> save name for a specific address->load name”-loop in my own application?

Edit:

After searching for a while, I decided to write the rename function in my own application because I couldn’t find another way to get the name.

If anyone is reading this and knows the answer to my initial question, I’d be happy to know.

Solution

In your app, you can rename the Bluetooth device like this:

public boolean renamePairedDevice(BluetoothDevice bluetoothDevice, String name) {
    try {
        Method m = bluetoothDevice.getClass().getMethod("setAlias", String.class);
        m.invoke(bluetoothDevice, name);
        return true;
    } catch (Exception e) {
        Log.d(TAG, "error renaming device:" + e.getMessage());
        return false;
    }
}

bluetoothDevice.getName() will then return the new name.

This has the same effect as renaming a Bluetooth device in the device settings.

Related Problems and Solutions