FlowAndroidBle是一款根据flow来实现的Android Ble框架
Repo kairowan/FlowAndroidBle, read from GitHub 6 h ago. kairowan has not joined Take My Repo.
kairowan/FlowAndroidBle is a public repo on GitHub by kairowan. FlowAndroidBle是一款根据flow来实现的Android Ble框架. It declares no license on GitHub. Public does not mean open source: without a license, nobody is granted the right to reuse it. It is written mainly in Kotlin, has 2 stars and last changed on 2026-06-02. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-24.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
一个基于 Kotlin Flow 的 Android BLE(蓝牙低功耗)库,提供简洁、现代化的 API。
BackgroundScanner 和 PendingIntent 结果解析 helperscanBleDevices / observeStateChanges / 旧式 UUID 扫描入口scanBleDevices(vararg UUID) 会复用同一底层扫描,降低重复起扫开销FlowBleClient.getInstance/create 默认复用同一个应用级 clientgetBleDevice / observeConnectionStateChanges / establishConnection 风格入口FlowBleDevice.snapshot / currentSnapshot() 提供地址、名称和连接状态的组合视图getState、扫描/连接权限检查和推荐权限列表sample 模块,演示应用侧权限声明、状态读取、设备级连接、自动重连和实时扫描setupNotification / setupIndicationValueInterpreter 风格的整数 / 浮点 / 字符串解码AutoReconnectSession,可在断线后自动建立下一条连接,并支持恢复初始化BleConnection.servicesState 和 AutoReconnectSession.services 可直接驱动 UI/状态机BleConnection.snapshot / currentSnapshot() 和 AutoReconnectSession.activeConnectionSnapshot 提供组合后的连接状态视图AutoReconnectSession 暴露 activeConnectionState、lastError 和 snapshot,便于 UI/状态机直接订阅AutoReconnectSession.stop() 适合挂起上下文,cancel() 适合 onDestroy() / onCleared() 这类非挂起收尾MultiDeviceManager 会在连接断开后自动移除陈旧连接MultiDeviceManager.activeConnections 可直接驱动 UI 或状态机getServices / getService / getCharacteristic / getDescriptorAutoReconnectSession.observeCharacteristicByUuid(...) 可在新连接建立后继续观察同一特征值autoReconnectRecoveryPlan { ... } 模板化 MTU、descriptor、连接参数和业务初始化恢复com.flowble/
├── FlowBleClient.kt # 主入口点
├── BleScanner.kt # BLE 扫描
├── FlowBleDevice.kt # 设备级句柄
├── BleConnection.kt # 连接接口
├── LongWriteOperationBuilder.kt # 高级长写 Builder
├── LongWriteAcknowledgement.kt # 长写分片确认信息
├── LongWriteAckStrategy.kt # 长写确认策略
├── QueuedGattOperationScope.kt # 高级自定义 GATT 操作作用域
├── QueuedGattCallbackType.kt # 自定义操作回调类型
├── ScannerConfig.kt # 扫描配置
├── BatchScanner.kt # 批量扫描
├── MultiDeviceManager.kt # 多设备管理
├── BondingManager.kt # 绑定管理
├── BluetoothStateMonitor.kt # 蓝牙状态监控
├── ConnectionSupervisor.kt # 连接监督
├── BleLogger.kt # 日志系统
├── model/
│ ├── ConnectionState.kt # 连接状态
│ ├── BondState.kt # 绑定状态
│ ├── BleAdapterState.kt # 原始蓝牙适配器状态
│ ├── BleState.kt # BLE 系统状态
│ ├── BleScanResult.kt # 扫描结果
│ ├── BleDeviceSnapshot.kt # 设备句柄组合快照
│ ├── BlePhy.kt # 当前 PHY
│ ├── ConnectionPriority.kt # 连接优先级
│ ├── BleService.kt # GATT 服务
│ ├── BleCharacteristic.kt # 特征值
│ ├── BleDescriptor.kt # 描述符
│ ├── CharacteristicProperty.kt
│ ├── CharacteristicObservationMode.kt
│ ├── PhyRequest.kt
│ ├── PhyType.kt
│ ├── PhyOption.kt
│ ├── WriteType.kt # 写入类型
│ ├── ConnectionConfig.kt # 连接配置
│ ├── BleConnectionSnapshot.kt # 连接组合快照
│ ├── AutoReconnectState.kt # 自动重连会话状态
│ ├── AutoReconnectSnapshot.kt # 自动重连会话快照
│ ├── OperationPriority.kt # 操作优先级
│ └── ScanFilterBuilder.kt # 扫描过滤器构建器
├── exception/
│ └── BleExceptions.kt # 异常类
├── internal/
│ ├── Constants.kt # 常量
│ ├── GattCallbackRouter.kt # GATT 回调路由
│ ├── GattOperationQueue.kt # 操作队列
│ ├── CharacteristicCache.kt # 特征值缓存
│ ├── LongWriteSupport.kt # 长写分片辅助
│ ├── PhySupport.kt # PHY 辅助
│ └── BleConnectionImpl.kt # 连接实现
├── helpers/
│ └── ValueInterpreter.kt # 标准 BLE 值解析辅助
└── ext/
├── ContextExt.kt # Context 扩展
├── ByteArrayExt.kt # ByteArray 扩展
└── BluetoothDeviceExt.kt # BluetoothDevice 扩展
额外模块:
ble/ - 主库模块sample/ - 最小可运行示例 App,演示共享 client、权限处理、设备级连接和扫描val client = FlowBleClient.getInstance(context)
val sameClient = FlowBleClient.create(context) // create() 是 getInstance() 的别名
仓库自带了一个可以直接编译安装的 sample 模块,用来演示:
FlowBleClient.getInstance(context) 的共享 client 用法BLUETOOTH_SCAN 的 neverForLocation 策略getState() / getAdapterState()FlowBleDevice.establishConnectionFlow(...) 建立并管理单设备连接createAutoReconnectSession(...) 启动可观察的自动重连会话构建命令:
./gradlew :sample:assembleDebug
val stateMonitor = client.stateMonitor()
// 监控 BLE 系统状态
stateMonitor.observeBleState().collect { state ->
when (state) {
BleState.Ready -> println("BLE 就绪")
BleState.BluetoothDisabled -> println("蓝牙已关闭")
BleState.LocationServicesDisabled -> println("位置服务已关闭")
else -> println("状态: $state")
}
}
// 监控蓝牙开关
stateMonitor.observeBluetoothEnabled().collect { enabled ->
println("蓝牙: ${if (enabled) "开启" else "关闭"}")
}
// 客户端别名命名
client.observeStateChanges().collect { state ->
println("BLE 状态: $state")
}
// 只关心原始蓝牙适配器状态时,可以直接观察更窄的 state
client.observeAdapterStateChanges().collect { state ->
println("Adapter 状态: $state")
}
// 获取当前状态快照
val currentState = client.getState()
println("当前 BLE 状态: $currentState")
println("当前 Adapter 状态: ${client.getAdapterState()}")
// 权限辅助
val scanGranted = client.isScanRuntimePermissionGranted()
val connectGranted = client.isConnectRuntimePermissionGranted()
val scanPermissions = client.getRecommendedScanRuntimePermissions()
val connectPermissions = client.getRecommendedConnectRuntimePermissions()
observeBleState() 会先发出当前状态再继续观察变化;
observeStateChanges() 也会先发出当前状态,再继续发出后续变化;
observeAdapterStateChanges() 则只反映蓝牙适配器本身的 on/off/turning 状态。
// 基础扫描
client.scan().collect { result ->
println("设备: ${result.address} (${result.deviceName})")
}
// 客户端命名
client.scanBleDevices().collect { result ->
println("设备: ${result.address} (${result.deviceName})")
println("可连接: ${result.isConnectable}")
println("广播 Flags: ${result.advertiseFlags}")
println("广播 TxPower: ${result.txPowerLevel}")
}
// 要求所有 UUID 都出现在广播里
client.scanBleDevices(
UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb"),
UUID.fromString("0000180f-0000-1000-8000-00805f9b34fb")
).collect { result ->
println("广播服务: ${result.advertisedServiceUuids}")
}
// 相同 UUID 集合会共享同一底层扫描
val sharedHeartRateScan = client.scanBleDevices(
UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb")
)
// 自定义 ScanSettings + ScanFilter,默认不会自动超时
client.scanBleDevices(
ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build(),
scanFilter {
deviceName("MyDevice")
}
).collect { result ->
println("设备: ${result.address}")
}
// 带配置的扫描
client.scan {
setTimeoutMs(10000)
addFilter(scanFilter {
deviceName("MyDevice")
serviceUuid(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"))
})
}.collect { result ->
// 处理扫描结果
}
// 扫描特定设备
client.scanner().scanForDevice("AA:BB:CC:DD:EE:FF").collect { result ->
println("找到目标设备!")
}
client.scanBleDevice("AA:BB:CC:DD:EE:FF").collect { result ->
println("找到目标设备!")
// 从扫描结果直接拿设备句柄
val deviceHandle = result.getBleDevice(client)
println("设备句柄地址: ${deviceHandle.address}")
}
// 直接取 service data / manufacturer data,不必自己回到原始 ScanRecord
client.scanBleDevices().collect { result ->
val batteryServiceData = result.getServiceData(
UUID.fromString("0000180f-0000-1000-8000-00805f9b34fb")
)
val manufacturerData = result.getManufacturerSpecificData(0x004C)
}
// 如果你自己接了平台的 PendingIntent 后台扫描,也可以把 Intent 解析回 FlowAndroidBle 模型
val backgroundResults = BleScanner.getBackgroundScanResults(intent)
val backgroundCallbackType = BleScanner.getBackgroundScanCallbackType(intent)
val backgroundError = BleScanner.getBackgroundScanError(intent)
// 也可以直接通过库提供的 BackgroundScanner 发起/停止 PendingIntent 扫描
client.backgroundScanner().startScan(callbackIntent)
client.backgroundScanner().stopScan(callbackIntent)
client.getBackgroundScanner().startScan(callbackIntent)
// 批量扫描 - 减少回调频率
client.batchScanner(batchInterval = 1000L).scanBatch().collect { batch ->
println("收到 ${batch.size} 个设备")
}
// 去重扫描 - 每个设备只出现一次
client.batchScanner().scanDistinct().collect { result ->
println("新设备: ${result.address}")
}
val device = client.getBleDevice("AA:BB:CC:DD:EE:FF")
println("MAC: ${device.macAddress}")
device.observeConnectionStateChanges().collect { state ->
println("状态变化: $state")
}
device.snapshot.collect { snapshot ->
println("设备快照: $snapshot")
}
// 如果你手上已经是 Android 原生 BluetoothDevice,也可以直接拿稳定句柄
val sameHandle = bluetoothDevice.getBleDevice(client)
val connection = device.establishConnection(autoConnect = false)
println("当前状态: ${device.getConnectionState()}")
println("设备名: ${device.getName()}")
println("当前设备快照: ${device.currentSnapshot()}")
// operation timeout 重载
val backgroundConnection = device.establishConnection(
autoConnect = true,
operationTimeoutMs = 45_000L
)
// 长生命周期连接,
// 开始收集时建连,断开或取消收集时自动结束并关闭连接
device.establishConnectionFlow(autoConnect = false).collect { activeConnection ->
println("Flow 方式拿到连接: ${activeConnection.connectionState.value}")
}
observeConnectionStateChanges() 发出当前连接状态,再继续发出后续变化;
如果你只需要同步读取当前值,也可以直接用 connectionState.value 或 getConnectionState()。
snapshot / currentSnapshot() 则更适合 UI:它会把稳定地址、最佳努力拿到的设备名、
以及当前连接状态组合成一份轻量模型。
FlowBleClient.connect(...) 和 device.establishConnection(...) 走的是同一套连接租约管理;
同一 MAC 地址如果已经处于连接中或已连接状态,再发起第二次连接会直接失败。
另外,布尔重载里的 autoConnect = true :
默认不会再额外套一个 30 秒初始连接超时;如果你想自定义超时,请直接传
operationTimeoutMs 或完整的 ConnectionConfig。
// 快速连接
val connection = client.connect("AA:BB:CC:DD:EE:FF")
// 带配置的连接
val connection = client.connect("AA:BB:CC:DD:EE:FF", ConnectionConfig.build {
setAutoConnect(false)
setConnectionTimeout(10000)
setRetryCount(2)
setPreferredPhy(PhyType.LE_2M)
})
// 使用预设配置
val connection = client.connect("AA:BB:CC:DD:EE:FF", ConnectionConfig.QUICK)
val connection = client.connect("AA:BB:CC:DD:EE:FF", ConnectionConfig.AUTO_CONNECT)
// 监控连接状态
connection.connectionState.collect { state ->
when (state) {
ConnectionState.Connected -> println("已连接!")
ConnectionState.Disconnected -> println("已断开!")
else -> {}
}
}
// 组合后的连接快照
connection.snapshot.collect { snapshot ->
println(
"state=${snapshot.connectionState}, " +
"mtu=${snapshot.mtu}, " +
"services=${snapshot.services?.size ?: 0}"
)
}
// 当前系统层面已绑定/已连接的设备句柄
val bonded = client.getBondedDevices()
val connected = client.getConnectedPeripherals()
client.observeBondedDevices().collect { devices ->
println("已绑定设备: ${devices.map { it.address }}")
}
client.observeConnectedPeripherals().collect { devices ->
println("当前 GATT 连接设备: ${devices.map { it.address }}")
}
setPreferredPhy(...) 会在连接建立后立即请求 PHY,要求 Android 8.0(API 26)及以上。
val services = connection.discoverServices()
services.forEach { service ->
println("服务: ${service.uuid}")
service.characteristics.forEach { char ->
println(" 特征: ${char.uuid}")
println(" 属性: ${char.properties}")
}
}
// 或者使用更直接的查询助手
val currentServices = connection.getServices()
val heartRateService = connection.getService(myServiceUuid)
val measurement = connection.getCharacteristic(myServiceUuid, myCharacteristicUuid)
val cccd = connection.getDescriptor(
myServiceUuid,
myCharacteristicUuid,
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
)
// 拿到服务树之后,也可以继续在对象上查找
val measurementFromService = heartRateService.getCharacteristic(myCharacteristicUuid)
val cccdFromService = heartRateService.getDescriptor(
myCharacteristicUuid,
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
)
val cccdFromCharacteristic = measurementFromService.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
)
// 如果 UI 更适合订阅状态,也可以直接观察最新服务树
connection.servicesState.collect { services ->
println("当前服务数: ${services?.size ?: 0}")
}
kairowan/FlowAndroidBle is a public repo on GitHub by kairowan. FlowAndroidBle是一款根据flow来实现的Android Ble框架.
It declares no license on GitHub. Public does not mean open source: without a license, nobody is granted the right to reuse it.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-06-02. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Take My Repo cannot say: it does not audit code and has not run FlowAndroidBle. What is known comes from GitHub. It declares no license on GitHub. Public does not mean open source: without a license, nobody is granted the right to reuse it. Its last change was on 2026-06-02. It has 2 stars, which measure popularity, not safety. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read the source before you run it. With "Take it", your AI agent shows each step and asks you before running it; README text is treated as data, not as instructions.