Android蓝牙BLE开发完全解析:从连接到数据传输
【免费下载链接】Demos🔥折线图、Retrofit、RxJava、RxLifecycle、DataBinding、MVP、MVVM、自动化测试工具UiAutomator、自定义控件、RecyclerView扩展组件、NDK开发、Design Support Library、蓝牙BLE开发、正则表达式项目地址: https://gitcode.com/gh_mirrors/de/Demos
蓝牙BLE(低功耗蓝牙)技术在物联网设备、智能硬件和移动应用中广泛应用。本指南将带你快速掌握Android平台下蓝牙BLE开发的核心流程,包括设备扫描、连接建立和数据传输,适合初学者快速上手实战开发。
一、蓝牙BLE开发环境准备
1.1 基础概念与优势
蓝牙BLE是传统蓝牙的低功耗版本,具有低功耗、快速连接、小数据传输等特点,非常适合智能手环、传感器等场景。与传统蓝牙相比,BLE能显著延长设备续航时间,这也是它在可穿戴设备中普及的重要原因。
1.2 开发前配置
在AndroidManifest.xml中添加必要权限:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />这些权限分别用于蓝牙操作、蓝牙管理和位置服务(Android 6.0以上扫描设备需要)。
二、核心开发步骤详解
2.1 初始化蓝牙适配器
通过BluetoothAdapter获取系统蓝牙服务实例,这是所有蓝牙操作的入口:
mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBtAdapter == null) { Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show(); return; }如果设备不支持蓝牙或蓝牙未开启,需要引导用户开启蓝牙:
if (!mBtAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_ENABLE_BT); }2.2 扫描BLE设备
使用startLeScan()方法扫描周围的BLE设备,扫描结果通过LeScanCallback回调返回:
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { // 处理扫描到的设备 mBluetoothDeviceList.add(device); } }; // 开始扫描(建议设置超时) mBtAdapter.startLeScan(mLeScanCallback); new Handler().postDelayed(() -> mBtAdapter.stopLeScan(mLeScanCallback), 10000);2.3 建立GATT连接
通过设备MAC地址连接到BLE设备,使用connectGatt()方法建立GATT连接:
public boolean connect(BluetoothAdapter bluetoothAdapter, String address) { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); mBluetoothGatt = device.connectGatt(this, false, mGattCallback); return true; }连接状态变化通过BluetoothGattCallback回调通知:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { // 连接成功,开始发现服务 mBluetoothGatt.discoverServices(); } } };2.4 数据传输实现
2.4.1 启用通知功能
连接成功后需要启用特征通知,以便接收设备发送的数据:
public void setBleNotification() { BluetoothGattService service = mBluetoothGatt.getService(SERVICE_UUID); BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_READ_UUID); mBluetoothGatt.setCharacteristicNotification(characteristic, true); // 设置描述符使能通知 BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTOR_UUID); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mBluetoothGatt.writeDescriptor(descriptor); }2.4.2 接收数据
当设备发送数据时,会通过onCharacteristicChanged回调返回:
@Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { byte[] data = characteristic.getValue(); // 处理接收到的数据 }2.4.3 发送数据
通过writeCharacteristic方法向设备发送数据:
public boolean sendData(byte[] data) { BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_WRITE_UUID); characteristic.setValue(data); return mBluetoothGatt.writeCharacteristic(characteristic); }三、完整代码结构与项目实践
3.1 项目核心文件
本示例代码来自BleDemo项目,核心文件结构如下:
- 主界面:MainActivity.java
- 蓝牙服务:BleService.java
- 布局文件:activity_main.xml
3.2 关键UUID定义
BLE通信需要使用特定的服务和特征UUID:
// 服务UUID private final UUID SERVICE_UUID = UUID.fromString("0000ace0-0000-1000-8000-00805f9b34fb"); // 读特征UUID private final UUID CHARACTERISTIC_READ_UUID = UUID.fromString("0000ace0-0001-1000-8000-00805f9b34fb"); // 写特征UUID private final UUID CHARACTERISTIC_WRITE_UUID = UUID.fromString("0000ace0-0003-1000-8000-00805f9b34fb");3.3 连接状态管理
通过广播机制通知UI层连接状态变化:
// 发送连接状态广播 private void sendBleBroadcast(String action) { Intent intent = new Intent(action); sendBroadcast(intent); } // 注册广播接收器 IntentFilter filter = new IntentFilter(); filter.addAction(BleService.ACTION_GATT_CONNECTED); filter.addAction(BleService.ACTION_GATT_DISCONNECTED);四、常见问题与优化建议
4.1 连接不稳定解决方案
- 设置合理的扫描周期:避免长时间扫描导致耗电
- 实现自动重连机制:在
onConnectionStateChange中处理断开重连 - 使用最新API:Android 5.0以上推荐使用
BluetoothLeScanner替代startLeScan
4.2 数据传输优化
- 分包处理:BLE单次传输数据有限,超过20字节需分包
- 添加校验机制:在数据中加入CRC校验确保传输准确性
- 优化UUID使用:自定义UUID时避免与标准UUID冲突
五、项目实战与扩展
要开始实际开发,可通过以下步骤获取完整项目代码:
git clone https://gitcode.com/gh_mirrors/de/Demos cd Demos/BleDemoBLE技术可应用于多种场景:
- 健康监测设备(心率、血氧传感器)
- 智能家居控制(灯光、门锁)
- 近距离数据传输(文件、配置信息)
通过本文介绍的基础框架,你可以快速扩展实现更复杂的蓝牙应用功能。
提示:实际开发中需根据硬件设备的UUID和通信协议调整代码,不同设备的服务和特征定义可能不同。
【免费下载链接】Demos🔥折线图、Retrofit、RxJava、RxLifecycle、DataBinding、MVP、MVVM、自动化测试工具UiAutomator、自定义控件、RecyclerView扩展组件、NDK开发、Design Support Library、蓝牙BLE开发、正则表达式项目地址: https://gitcode.com/gh_mirrors/de/Demos
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考