如何防止在Android上通过蓝牙进行数据交换

时间:2013-10-28 11:32:12

标签: android bluetooth connection disconnect

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

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>

2 个答案:

答案 0 :(得分:1)

我找到了以下解决方案。

在配对和文件传输尝试期间发送

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

<强>优势

  • 可靠性

<强>缺点

  • 耳机停止工作

答案 1 :(得分:-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();