一、前言
在物联网设备开发中,蓝牙通信(Bluetooth Low Energy, BLE) 是最常见的无线数据传输方式之一。
很多 Android 项目(如健康手环、传感模块等)都需要实现 BLE 的扫描、连接、收发数据、断线重连等功能。
本文将分享一个我在项目中实际使用的 BLE 工具类 —— BluetoothBleUtil,
它将 Android 原生的蓝牙 API 封装成简单易用的接口,让开发者可以几行代码就完成 BLE 通信。
二、功能概述
本工具类实现了以下 BLE 功能模块:
功能 说明
蓝牙初始化 初始化 BluetoothAdapter、BluetoothManager
扫描设备 支持超时自动停止扫描
自动连接目标设备 根据设备名过滤并自动连接
读写 GATT 特征 支持发送指令与接收通知
断开与释放 断线自动清理,防止内存泄漏
重连功能 自动重连上次已连接设备
状态监听 支持 LiveData 与回调接口
三、核心架构设计
BluetoothBleUtil 使用 Kotlin 单例模式 (object) 设计,保证 BLE 连接全局唯一。
核心流程如下:
startScan() → onScanResult() → connect() → onServicesDiscovered()
↓ ↓
stopScan() enableNotify()
↓ ↓
sendBytes() ←→ onCharacteristicChanged()
四、代码实现详解
import android.annotation.SuppressLint
import android.bluetooth.*
import android.bluetooth.le.*
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.comm.library.utils.LogUtils
import com.comm.library.utils.SPUtils
import com.htnova.gasdetection.model.SpConstance
import java.util.*
/**
* 低功耗蓝牙
*/
@SuppressLint("MissingPermission")
object BluetoothBleUtil {
private const val TAG = "gasdetection"
// ------------------------- BLE参数配置 UUID根据设备配置 -------------------------
private const val DEVICE_NAME = "GCPID"
private val SERVICE_UUID = UUID.fromString("0000a002-0000-1000-8000-00805f9fb")
private val WRITE_UUID = UUID.fromString("0000c303-0000-1000-8000-00805f9bfb")
private val NOTIFY_UUID = UUID.fromString("0000c30-0000-1000-8000-00805f9b3b")
// ------------------------- 回调接口 -------------------------
interface Callback {
fun onScanStarted() {}
fun onDeviceFound(device: BluetoothDevice) {}
fun onScanFinished() {}
fun onConnected(device: BluetoothDevice) {}
fun onDisconnected(device: BluetoothDevice) {}
fun onMessageReceived(device: BluetoothDev