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

我的目标是在蓝牙低功耗设备和手机之间建立自动连接.我按照示例代码找到了该行
// We want to directly connect to the device,so we are setting the autoConnect parameter to false.
mBluetoothGatt = device.connectGatt(this,false,mGattCallback);

上面的代码表示虚假用于自动连接.但是,我在here发现了API,它说

BluetoothGatt connectGatt(Context context,boolean autoConnect,BluetoothGattCallback callback,int transport)
Connect to GATT Server hosted by this device.

我还尝试了两个标志:真和假,只有真的是工作.我使用的是版本> = 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;
}

解决方法

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

请注意0​​7000,这是一个影响旧版Android的错误,可能会使您的自动连接成为直接连接.这可以用反射来解决.

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

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

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

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

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

相关文章

这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,...
本文小编为大家详细介绍“Android数据压缩的方法是什么”,内...