这个项目的目标是使用我的安卓手机连接我的Arduino设备。但是如何取消已配对的设备呢?看起来已配对设备列表存储在蓝牙适配器可以随时检索到的地方。
PS:
1、我知道长按已配对设备会将其解除配对,但是问题是如何以编程方式实现这一点?
2、我已经检查了蓝牙设备和蓝牙适配器类,发现没有实现这一功能的函数。
谢谢。
这段代码对我有效。
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());
}
}
如果您正在使用 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}")
}
}
取消所有设备的配对:
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());
}
}
}
@hide
注释,这使其对公众不可用。 - Christopher如果您想删除配对的蓝牙设备,首先必须取消所有设备的配对,然后单击搜索选项,您会发现所有设备都已从列表中删除。