如何在Android中获取远程设备的自定义蓝牙名称?

3
我想获取Android中远程蓝牙设备的自定义名称。我指的是在手机设置下找到的名称,即Settings/Bluetooth和已配对设备。

例如,我有一个名为“DoorControl”的远程蓝牙设备。在设置->蓝牙->配对设备下,我已将设备重命名为“CTRL”。现在我想访问定义的名称,以便我可以向用户显示它。
我想在蓝牙设备列表中显示该名称。
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()方法只返回设备的原始完整名称,这种情况下是"DoorControl"。

这是必要的,因为可能会有4个名为DoorControl的设备。区分它们的唯一方法是通过它们的地址。但对于用户友好的方法,让他们在蓝牙设置中重命名设备并将该名称显示为设备的“昵称”会更容易。

是否有方法可以访问自定义名称,以便我不必在自己的应用程序中编写完整的“重命名 -> 保存某个地址的名称 -> 加载名称”的循环?

编辑:

搜索了一段时间后,我决定在自己的应用程序中编写重命名功能,因为我找不到其他方式来获取名称。

如果有人阅读此内容并知道我的原始问题的答案,我很想知道。

2个回答

4

在您的应用中,您可以通过以下方式重命名蓝牙设备:

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()将返回新名称。

这与在设备设置中重命名蓝牙设备具有相同的效果。


这实际上有点像我必须做的事情。 仍然没有回答我的原始问题..如何从应用程序本身访问人们在Android设备的蓝牙设置中设置的“昵称”? 我知道这一定是可能的。 只是不知道Android保存蓝牙设备名称的信息在哪里..我知道如何直接从应用程序重命名蓝牙设备,但在应用程序本身中这样做很不方便,因为它不会更改Android设置中的名称或反之亦然。但感谢您的答案,也许有人会从中得到帮助。 - Nahkala

4
我发现的问题是getName()函数只返回默认设备名称,而不是用户可以设置的别名。在我的情况下,我配对了多个相同的设备,它们的默认名称是“Motorola T605”。我无法分辨它们,所以我使用Android设置将它们重命名。然而,getName()仍然返回“Motorola T605”。我需要获取别名。该函数存在,但未公开。您可以在这个Java类中看到它:https://android.googlesource.com/platform/frameworks/base/+/56a2301/core/java/android/bluetooth/BluetoothDevice.java 这对我很有用。
首先获取已配对设备的数组:
Set<BluetoothDevice> pairedDevices = mBTA.getBondedDevices();

然后遍历数组:

for (BluetoothDevice device : pairedDevices) 

然后看看是否可以找到替代名称:

                           String name = null;

                        try {
                            Method m = device.getClass().getMethod("getAlias");
                            Object res = m.invoke(device);
                            if(res != null)
                            name = res.toString();
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                        if(name == null)
                        name = device.getName();

如果无法获取别名,则使用普通名称。我可以更好地防止和处理异常情况,但似乎这样做就可以了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接