【问题标题】:How to unpair or delete paired bluetooth device programmatically on android?如何在 android 上以编程方式取消配对或删除配对的蓝牙设备?
【发布时间】:2012-03-25 08:58:42
【问题描述】:

该项目是使用我的安卓手机连接我的 arduino 设备。但我怎样才能取消配对的配对。我看到配对列表似乎存储在蓝牙适配器可以随时检索的位置。

PS: 第一,我知道长按配对设备会取消配对。
但这里的问题是如何以编程方式实现这一点?

第二,我检查了bluetoothdevice和bluetoothAdapter类,没有实现这个的函数。

谢谢。

【问题讨论】:

标签: android bluetooth arduino


【解决方案1】:

此代码对我有用。

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());
    }
}

【讨论】:

  • @Ewoks,不确定你的意思
  • 这适用于果冻豆(又名 4.1.x)吗?因为我很确定他们添加了新的蓝牙堆栈并且 createBond 方法消失了..
  • 答案是正确的,但是……天啊……他们为什么一直隐藏这些方法?至少,它们应该公开诸如 BluetoothAdapter 启用/禁用之类的意图。
  • Google 显然只是讨厌蓝牙——这个简单的方法已经隐藏了 4 年。他们甚至没有尝试实现带外配对方法,这是唯一没有被破坏的方法。
  • 有什么办法吗?不使用反射?
【解决方案2】:

取消配对所有设备:

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());
                }
            }
        }

【讨论】:

【解决方案3】:

如果您使用的是 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}")
    }
}

【讨论】:

    【解决方案4】:

    在 BluetoothService 类中有一个方法 removebond() 可以取消配对、配对的设备。最后这个方法调用 rmovebondnative()。

    【讨论】:

    • 是公开的api吗?
    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2012-12-23
      • 2011-09-16
      • 1970-01-01
      • 2011-07-07
      • 2014-03-13
      相关资源
      最近更新 更多