How to unpair or delete paired bluetooth device programmatically on android?
This code works for me.
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());
}
}
unpair all devices:
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());
}
}
}
If you are using 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}")
}
}
Or create an extension function, in this case you can use device.removeBond()
fun BluetoothDevice.removeBond() {
try {
javaClass.getMethod("removeBond").invoke(this)
} catch (e: Exception) {
Log.e(TAG, "Removing bond has been failed. ${e.message}")
}
}