Android-BLE-Library 使用教程
1. 项目介绍
Android-BLE-Library 是由 Nordic Semiconductor 开发的一个库,它简化了在 Android 平台上使用蓝牙低功耗(Bluetooth Low Energy,BLE)的过程。库使用 Kotlin 编写,并结合了 Kotlin 的协程以实现异步操作,让 BLE 相关的操作更加自然且符合规范。该库提供了一个 BLE Scanner 模块,用于扫描并获取可用的 BLE 设备列表,以及设备的扫描记录。
2. 项目快速启动
添加依赖
在你的 build.gradle
文件中添加以下依赖:
dependencies {
implementation 'no.nordicsemi.android:ble:2.7.5'
// 如需使用 Kotlin 扩展功能
implementation 'no.nordicsemi.android:ble-ktx:2.7.5'
}
然后同步 Gradle 项目。
初始化与扫描
下面是一个简单的初始化和扫描设备的示例:
import no.nordicsemi.android.ble.BleManager
import no.nordicsemi.android.ble.scan.BleScanResultAggregator
import no.nordicsemi.android.ble.callback.ScanCallback
import no.nordicsemi.android.ble.scan.BleScanner
val manager = BleManager.getInstance(this)
val aggregator = BleScanResultAggregator()
manager.init {
val scanner = BleScanner(this)
scanner.scan().map { aggregator.aggregateDevices(it) }.launch()
}
断开扫描
当不再需要扫描时,可以这样关闭扫描:
manager.terminate()
3. 应用案例和最佳实践
可靠性写入
确保可靠的数据写入:
manager.write(device, characteristic, data)
.timeout(5, TimeUnit.SECONDS)
.catch { println("Write failed: $it") }
.collect()
错误处理
使用异常捕获来处理错误情况:
manager.connect(device)
.catch { println("Connection failed: $it") }
.onFailure { println("Failed to connect: $it") }
.onSuccess { connected ->
if (connected) {
// Connected successfully, perform actions...
}
}
4. 典型生态项目
- Android Scanner Compat Library:推荐用来替代原生扫描,为老版本 Android 提供更现代的 BLE 设备扫描特性。
- nRF Toolbox:一个开源应用程序,展示了如何使用 Android-BLE-Library 来实现各种 BLE 功能,包括连接、读取、写入等操作。
- GATT Server 示例:从 2.2 版本起,库内提供了 GATT 服务器支持,参考项目中的
examples/ble-gatt-server
文件夹,了解如何设置和使用 GATT 服务器。
以上内容应能帮助您开始使用 Android-BLE-Library。若要了解更多细节或查阅完整的 API 文档,请参考项目官方仓库:https://github.com/NordicSemiconductor/Android-BLE-Library。