BLE 连接何时建立?通过调用建立连接()?或者在它之后调用第一个特征?

When is physically a BLE connection is establishing? by calling establish connection() ? or calling the first characteristic after it?

实际上,我对与“establishconnection()”相关的其他问题和相关讨论中的答案感到困惑。自从我开始使用低功耗 BLE 设备连接到我的应用程序,我对应用程序和设备之间的物理通信建立有疑问。在我的程序中,我在读取特征之前调用 establishconnection() 。但是在之后的同步过程中,我总是在应用程序和设备之间遇到一些连接问题。所以我需要再次深入检查我的设备的连接过程。那么,您能否根据以上几点 给我一个准确的代码点,其中与 BLE 设备的物理连接实际上是从应用程序建立的

有几种方法可以确定连接发生的确切时间。这可以在几个层面上完成:

Android 默认日志

通常当连接到 BLE 外围设备时,在 logcat:

中可以看到特定的线路

D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=6 device=00:00:00:00:00:00

RxAndroidBle 日志

可以设置 RxBleLog.setLogLevel(RxBleLog.VERBOSE) 使库内部日志可见。系统通知图书馆建立连接的时刻用log:

D/RxBle#BluetoothGatt: onConnectionStateChange newState=2 status=0

低级 ACL 广播

大多数 Android 操作系统会在建立低级蓝牙连接时广播信息。要访问它,必须注册 BroadcastReceiver

Context context = /* your Context */;
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.d("Connected", "BluetoothDevice[macAddress=" + bluetoothDevice.getAddress() + ']');
    }
};
context.registerReceiver(broadcastReceiver, intentFilter);

这将触发以下日志:

D/Connected: BluetoothDevice[macAddress=00:00:00:00:00:00]