在BLE的connectGatt中哪个正确的autoConnect标志?

时间:2016-10-20 14:02:45

标签: android bluetooth bluetooth-lowenergy bluetooth-gatt

我的目标是在蓝牙低功耗设备和手机之间建立自动连接。我按照示例代码找到了行

// We want to directly connect to the device, so we are setting the autoConnect parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

上述代码表示false用于自动连接。但是,我在here找到了API,它说

  

BluetoothGatt connectGatt(上下文上下文,布尔autoConnect,BluetoothGattCallback回调,int传输)   连接到此设备托管的GATT服务器。

我还尝试了两个标记:truefalse,只有true才有效。我使用的是版本> = Android 5.0。代码和API之间有什么不一致吗?哪个标志是正确的?如果我想进行自动连接,是否需要注意?

这是我的代码

public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    // Previously connected device.  Try to reconnect.
    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
            && mBluetoothGatt != null) {
        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
        if (mBluetoothGatt.connect()) {
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            return false;
        }
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    // We want to directly connect to the device, so we are setting the autoConnect
    // parameter to false.
    mBluetoothGatt = device.connectGatt(this, true, mGattCallback);
    Log.d(TAG, "Trying to create a new connection.");
    mBluetoothDeviceAddress = address;
    mConnectionState = STATE_CONNECTING;
    return true;
}

2 个答案:

答案 0 :(得分:25)

"直接连接"与" auto connect"相反,因此如果将autoConnect参数设置为false,则会得到"直接连接"。注意做一个" mBluetoothGatt.connect()"也将使用自动连接。

谨防https://code.google.com/p/android/issues/detail?id=69834这是一个影响旧版Android的错误,可能会使您的自动连接成为直接连接。这可以通过反思来解决。

直接和自动连接之间存在一些未记录的差异:

直接连接是30秒超时的连接尝试。当直接连接正在进行时,它将暂停所有当前的自动连接。如果已经存在直接连接挂起,则最后一次直接连接将不会立即执行,而是排队并在上一次完成时启动。

使用自动连接,您可以同时拥有多个待处理的连接,并且它们永远不会超时(直到明确中止或直到蓝牙关闭)。

如果通过自动连接建立连接,Android将在断开连接时自动尝试重新连接到远程设备,直到您手动调用disconnect()或close()。通过直接连接建立连接后,不会尝试重新连接到远程设备。

直接连接具有不同的扫描间隔和扫描窗口,其占空比高于自动连接,这意味着它将专用更多的无线电时间来监听远程设备的可连接广告,即连接将更快地建立。

答案 1 :(得分:0)

autoConnect 参数决定是否主动连接 远程设备,或者更确切地说是被动扫描并完成连接 当远程设备在范围内/可用时。一般来说,有史以来第一次 与设备的连接应该是直接的(autoConnect 设置为 false)并且 与已知设备的后续连接应使用 autoConnect 参数设置为 true。