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

Jam*_*ame 13 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);
Run Code Online (Sandbox Code Playgroud)

上面的代码表示false用于自动连接.但是,我在这里找到了API ,它说

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

我还尝试了两个标志:true而且false,只有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;
}
Run Code Online (Sandbox Code Playgroud)

Emi*_*mil 31

"直接连接"与"自动连接"相反,因此如果将autoConnect参数设置为false,则会获得"直接连接".请注意,执行"mBluetoothGatt.connect()"也将使用自动连接.

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

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

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

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

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

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

  • connect命令通过了很多层.您可以在https://android.googlesource.com/platform/system/bt/+/master/stack/gatt/gatt_api.cc查看GATT_Connect.这是aidl接口的另一端:https://android.googlesource.com/platform/packages/apps/Bluetooth/+/dbaf9cd/src/com/android/bluetooth/gatt/GattService.java. (2认同)
  • BLE GATT连接和传输不涉及应用程序保持活动状态或被杀死的方式。因此,如果您需要长期的GATT连接或挂起的连接,则应在应用程序进程中运行前台服务,以免进程被杀死。 (2认同)