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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...