安卓BLE低功耗蓝牙通信工具类封装

一、前言

在物联网设备开发中,蓝牙通信(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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值