如何在不配对的情况下使 BLE 自动连接到 android phone 的蓝牙

how to make BLE autoconnect to Bluetooth of android phone without pairing

我有一个带 BLE 的 Arduino,它必须在其范围内通过蓝牙向 any/all android phones 发送一些数据。我的 android phone 应该有一个应用程序,我打算制作它来通知收到的数据。

我如何制作这样的 android 应用程序,它可以自动连接到任何附近的 BLE,即使是第一次发现也没有配对并交换数据。我的意思是我如何在任何应用程序中实现无密钥自动连接 pairing.I 发现设置 autoconnect=true 将完成此任务,但我不确定。 任何帮助,甚至是一些资源,我都会参考并消除我的疑虑。

先决条件和步骤是(Java 中的代码片段):

  • Arduino 端的 HC-XX 模块或类似 BLE 设备设置为安全模式 1 和安全级别 1(无安全且无配对)
  • Android 4.3(API 级别 18)内置平台支持低功耗蓝牙 (BLE)
  • 检查设备(手机)是否启用了 BLE

    // Ensures Bluetooth is available on the device and it is enabled. If not,
    // displays a dialog requesting user permission to enable Bluetooth.
    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
         Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
    
  • 找到 BLE 设备。您使用 startLeScan() 方法。此方法将 BluetoothAdapter.LeScanCallback 作为参数。您必须实施此回调,因为这是返回扫描结果的方式。由于扫描会消耗大量电池电量,因此您应遵守以下准则:

    • 找到所需设备后,立即停止扫描。
    • 切勿循环扫描,并设置扫描时间限制。以前可用的设备可能已移出范围,继续扫描会耗尽电池电量。
  • 如果您只想扫描特定类型的外围设备,您可以改为调用 startLeScan(UUID[], BluetoothAdapter.LeScanCallback),提供一组 UUID 对象,指定您的应用程序支持的 GATT 服务。

  • 与 BLE 设备交互的第一步是连接到它——更具体地说,连接到设备上的 GATT 服务器。要连接到 BLE 设备上的 GATT 服务器,您可以使用 connectGatt() 方法。此方法采用三个参数:Context objectautoConnect(表示是否在 BLE 设备可用时立即自动连接的布尔值)和对 BluetoothGattCallback.[= 的引用21=]

    // Here we set autoconnect to true
    bluetoothGatt = device.connectGatt(this, true, gattCallback); 
    

总而言之,仅靠自动连接无法完成工作,因为您不需要配对。因此必须设置安全模式 1 和安全级别 1(完全没有安全性)。因此,请确保通过使用软件侧 encryption/auto 登录,没有未经授权的人使用您的设备

Read more about BLE in Android in detail here
Read more about BLE security in detail here