有没有一种方法可以让我们知道 BLE 设备是否在实际连接之前尝试连接到我?

Is there a way that we can know if a BLE device is trying to connect to me before it actually gets connected?

一个 BLE 追踪器设备试图连接到我的 BLE Android 应用程序。我想知道设备尝试连接到我时发生的事件(意味着在它实际连接到我之前),如果设备无法连接到我,我想知道设备无法连接到我的原因.

private BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() {

  @Override
  public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
    Log.d(TAG, "onConnectionStateChange Status: " + status);
    //            logs += "\n\nonConnectionStateChange Status: " + status;
    //            updateHomeUI();

    if (newState == BluetoothProfile.STATE_CONNECTED) {
      connectedDeviceAddress = device.getAddress().toString();
      Log.i(TAG, "BluetoothDevice CONNECTED:\n" + device);
      FragmentManager fragmentManager = getSupportFragmentManager();
      try {
        logs += "\n\nBluetoothDevice CONNECTED: \n" + device;
        updateHomeUI();
      } catch (Exception e) {
        e.printStackTrace();
      }
      mRegisteredDevices.add(device);
      mHandler.post(new Runnable() {
        @Override
        public void run() {
          Toast.makeText(MainActivity.this, "Device CONNECTED: " + connectedDeviceAddress, Toast.LENGTH_SHORT).show();
        }
      });

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
      Log.i(TAG, "BluetoothDevice DISCONNECTED: " + device);
      //Remove device from any active subscriptions
      logs += "\n\nBluetooth Device DISCONNECTED:\n" + device;
      updateHomeUI();
      mRegisteredDevices.remove(device);
      //restarting everything -- test
      //                bluetoothAdapter.disable();
      //                bluetoothAdapter.enable();
      //                startAdvertising();
      //                startServer();

      mHandler.post(new Runnable() {
        @Override
        public void run() {
          Toast.makeText(MainActivity.this, "Device DISCONNECTED", Toast.LENGTH_SHORT).show();
        }
      });
    }

    if (newState == BluetoothProfile.STATE_CONNECTING) {
      Log.d(TAG, "Connecting...Status: " + status);
      logs += "\n\nConnecting...Status: " + status;
      updateHomeUI();
    }

  }


};

以上是我正在使用的一段代码。你可以看到我已经实现了回调方法onConnectionStateChange。我也在检查以下值:

  1. STATE_CONNECTED
  2. STATE_DISCONNECTED
  3. STATE_CONNECTING

即使我正在检查所有这些,我意识到我的代码永远不会进入 STATE_CONNECTING 检查,因此我无法知道设备何时尝试连接到我并且我找不到方法以防万一设备无法连接到我的应用程序时知道错误。

如有任何帮助,我们将不胜感激。

从 BLE 外围设备的角度来看,不存在远程中央设备正在“连接”这样的状态。刚刚断开连接,突然连接。在 link 层上,只有一个数据包是中央向外围设备发送的:“嘿,你现在已连接”,以响应外围设备发送的广告。

如果您在 https://developer.android.com/reference/android/bluetooth/BluetoothGattServerCallback#onConnectionStateChange(android.bluetooth.BluetoothDevice,%20int,%20int) 阅读 Android 的文档,您会发现 CONNECTING 不是此回调的可能状态之一。