1

建立连接后如何立即断开与设备的连接?我需要阻止我的设备与列入黑名单的设备进行数据交换

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>
4

2 回答 2

2

我找到了以下解决方案。

ACTION_UUID在配对和文件传输尝试期间发送,由于EXTRA_DEVICE,我可以获得设备。如果我想立即断开与此设备的连接,我可以运行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");
    }
}

这不是完全断开连接。

更新#1。

有时会被调用,但在发送/接收文件removeBond,我连接的设备会取消配对。因此,我现在知道的防止设备通过蓝牙进行数据交换的唯一方法是通过调用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();
    } 
}

好处

  • 可靠性

缺点

  • 耳机停止工作
于 2013-10-29T10:41:33.023 回答
-1
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            // TODO Auto-generated method stub
            String intentAction;
            if(newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

            } else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server");
                broadcastUpdate(intentAction);
            }
        }
}

定义mBluetoothGatt后,您可以在按下按钮或任何操作后调用以下代码:

mBluetoothGatt.disconnect();
于 2013-10-28T12:22:07.980 回答