android - 如何在每次打开同一蓝牙低功耗设备时重新连接我的应用程序?

标签 android bluetooth bluetooth-lowenergy

我正在开发一个 Android 应用程序。在开始时,这个应用程序会向用户显示一个蓝牙设备列表,当他选择其中一个时,会打开另一个 Activity 。

我的目标是:有一天当用户重新打开应用程序时,应用程序必须记住蓝牙设备并且必须尝试重新连接到它。

目前我已经通过这种方式实现了我的目标:

  • 我优先记住所选设备的 mac 地址
  • 当用户重新打开该应用时,该应用会执行隐藏扫描并尝试重新连接到具有相同 MAC 地址的设备。
  • 为了检索 mac 地址,我使用函数 getAddress() (当我尝试连接到 android 外围设备时,这个函数给了我 有些问题,因为设备每次都会更改其 MAC 地址 开始 :/)

同样的东西有没有最好的获取方式?

题外话:ScanResult中的onScanResult函数有时返回给我空设备,是否正常? 我使用了 startLeScan(UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback) 并且在 lollipop 之后我使用了带有 Scanfilter 的新版本的 startLeScan。这可能是问题所在吗?

最佳答案

出于隐私原因,mac 地址不断变化 - 请引用以下来自 ble 规范的 fragment :

5.4.5 Privacy Feature

Bluetooth LE supports a feature that reduces the ability to track a LE device over a period of time by changing the Bluetooth device address on a frequent basis. The privacy feature is not used in the GAP discovery mode and procedures but it is used, when supported, during connection mode and connection procedures. In order for a device using the privacy feature to reconnect to known devices, the device address, referred to as the private address, must be resolvable by the other device.

The private address is generated using the device’s resolving identity key (IRK) exchanged during the bonding procedure.

所以理想的方法是使用 IRK 来生成设备的实际地址。但是我没有找到任何 API 来做这件事。

目前,我正在 mny 应用程序中使用的解决方法是重新连接到设备,

  1. 遍历所有可用设备。
  2. 获取序列号——如果序列号与已经存储的号码匹配 然后保持连接,否则断开连接。
  3. 对所有设备重复第 2 步。

    只有当设备通过某些服务公开序列号时,此解决方法才会起作用。

您也可以尝试在调用 connectGatt (Context context, boolean autoConnect, BluetoothGattCallback callback) 时将autoconnect 标志设置为 true

来自文档:

public BluetoothGatt connectGatt (Context context, boolean autoConnect, BluetoothGattCallback callback) Added in API level 18

Connect to GATT Server hosted by this device. Caller acts as GATT client. The callback is used to deliver results to Caller, such as connection status as well as any further GATT client operations. The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct GATT client operations. Parameters

autoConnect Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true).

callback GATT callback handler that will receive asynchronous callbacks. Throws IllegalArgumentException if callback is null

关于android - 如何在每次打开同一蓝牙低功耗设备时重新连接我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29444709/

相关文章:

android - 在 Python 中为 Kivy 跨平台、移动、MIDI 演奏——这可能吗?

android - 信标 : Android/Iphone Bluetooth range

java - 应用程序已停止(Android Studio 蓝牙)

android - 如何通过蓝牙或 BLE 在两个 Android 设备之间发送消息?

bluetooth - 为什么暴露服务的总是GATT服务器呢?

android - 如何在 kotlin 中简化代码?

android - 如何从 InputStream 而不是 File 获取 Exif 数据?

java - 如何在节点Firebase中获得唯一的随机产品?

ios - XCode:如何通过 UUID 连接到 BLE 外设?

ios - 从字节中获取位的值 | swift 5