如何在Android上以编程方式取消配对或删除配对的蓝牙设备?

Dev*_*lar 34 android bluetooth arduino

该项目是使用我的Android手机连接我的arduino设备.但是我如何解除配对的配对.我看到配对列表似乎存储在bluetoothadapter可以随时检索的位置.

PS:1,我知道长按配对设备将取消配对.
但问题是如何以编程方式实现这一目标?

2,我检查了bluetoothdevice和bluetoothAdapter类,没有实现这个的功能.

谢谢.

Dev*_*lar 63

这段代码适合我.

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 答案是正确的但是...... omg ...为什么他们继续隐藏这些方法?至少,他们应该暴露像BluetoothAdapter启用/禁用的意图. (7认同)
  • 从Android 9.0开始,该方法不再适用于用户级应用程序,因为该方法现在被标记为系统API,需要通过反射调用系统级权限。 (3认同)
  • 谷歌显然只是讨厌蓝牙——这个简单的方法已经隐藏了 4 年了。他们甚至还没有尝试实现带外配对方法,这是唯一一种没有损坏的方法。 (2认同)
  • 取消配对不适用于Android 7或7+ (2认同)

Pét*_*égi 12

取消配对所有设备:

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());
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 不,它带有“ @hide”注释,这使得它对公众不可用。 (2认同)

Exa*_*aqt 5

如果您使用的是 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}")
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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