How to disconnect from a device right after connection has been established? I need to prevent my device from data exchange with blacklisted devices
public class BluetoothReceiver extends BroadcastReceiver {
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
BluetoothDevice remoteDevice = (BluetoothDevice) intent.getExtras().get(BluetoothDevice.EXTRA_DEVICE);
// I'd like to disconnect from remoteDevice here
}
}
AndroidManifest.xml
<receiver android:name="com.app.receivers.BluetoothReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
</intent-filter>
</receiver>
I found the following solution.
ACTION_UUID is sent during pairing and a file transfer attempt, and I can get the device due to EXTRA_DEVICE. If I want to immediately disconnect from this device, I can run removeBond
private void removeBond(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e("TAG", "Failed to disconnect from the device");
}
}
It is not quite disconnection.
Update #1.
Sometimes removeBond
is called, but the device I connected to gets unpaired after a file has been sent/received. So, the only way to prevent a device from data exchange via Bluetooth I know now is to disable its Bluetooth module by calling BluetoothAdapter.getDefaultAdapter().disable()
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
BluetoothDevice remoteDevice = (BluetoothDevice) intent.getExtras().get(BluetoothDevice.EXTRA_DEVICE);
if (isBlackListed(remoteDevice)) {
BluetoothAdapter.getDefaultAdapter().disable();
}
}
Benefits
Drawbacks