如何在安卓设备上通过编程取消配对或删除配对的蓝牙设备?

45

这个项目的目标是使用我的安卓手机连接我的Arduino设备。但是如何取消已配对的设备呢?看起来已配对设备列表存储在蓝牙适配器可以随时检索到的地方。

PS: 1、我知道长按已配对设备会将其解除配对,但是问题是如何以编程方式实现这一点?
2、我已经检查了蓝牙设备和蓝牙适配器类,发现没有实现这一功能的函数。

谢谢。

5个回答

78

这段代码对我有效。

private void pairDevice(BluetoothDevice device) {
    try {
        if (D)
            Log.d(TAG, "Start Pairing...");

        waitingForBonding = true;

        Method m = device.getClass()
            .getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);

        if (D)
            Log.d(TAG, "Pairing finished.");
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

private void unpairDevice(BluetoothDevice device) {
    try {
        Method m = device.getClass()
            .getMethod("removeBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

11
答案是正确的,但是...哎呀...为什么他们一直隐藏这些方法?至少应该公开意图,比如BluetoothAdapter的启用/禁用。 - andrea.rinaldi
2
谷歌显然非常讨厌蓝牙——这种简单的方法已经被隐藏了4年。他们甚至没有尝试实现唯一没有破解的外带配对方法。 - Timmmm
1
有没有不使用反射的方法? - mumair
1
请慎重使用此解决方案。谷歌开始了一个隐藏 API 的淘汰计划,createbond 方法已经列入灰名单(仍然允许使用,但不能保证能用多久):https://android.googlesource.com/platform/frameworks/base/+/pie-release/config/hiddenapi-light-greylist.txt - user7209975
3
从Android 9.0开始,由于该方法被标记为系统API,用户级应用程序不能再使用此方法,因为需要通过反射调用需要系统级权限。 - Daniel Lee
显示剩余3条评论

15

如果您正在使用 Kotlin:

fun removeBond(device: BluetoothDevice) {
    try {
        device::class.java.getMethod("removeBond").invoke(device)
    } catch (e: Exception) {
        Log.e(TAG, "Removing bond has been failed. ${e.message}")
    }
}

或者创建一个扩展函数,在这种情况下,您可以使用device.removeBond()

fun BluetoothDevice.removeBond() {
    try {
        javaClass.getMethod("removeBond").invoke(this)
    } catch (e: Exception) {
        Log.e(TAG, "Removing bond has been failed. ${e.message}")
    }
}

14

取消所有设备的配对:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                try {
                    Method m = device.getClass()
                            .getMethod("removeBond", (Class[]) null);
                    m.invoke(device, (Object[]) null);
                } catch (Exception e) {
                    Log.e("Removing has been failed.", e.getMessage());
                }
            }
        }

removeBond() 不应该是 BluetoothDevice 上的公共方法吗?http://androidxref.com/7.1.1_r6/xref/frameworks/base/core/java/android/bluetooth/BluetoothDevice.java - IgorGanapolsky
2
不,它被标记为@hide注释,这使其对公众不可用。 - Christopher

1
在BluetoothService类中有一个名为removebond()的方法,用于取消配对已配对的设备。最后,该方法调用rmovebondnative()。

2
它是一个公开的 API 吗? - IgorGanapolsky

-9

如果您想删除配对的蓝牙设备,首先必须取消所有设备的配对,然后单击搜索选项,您会发现所有设备都已从列表中删除。


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