一、蓝牙基础知识入门1.1 什么是蓝牙蓝牙是一种短距离无线通信技术通常10米内用于在设备间传输数据。Android设备支持蓝牙4.0及以上版本BLE低功耗蓝牙。1.2 蓝牙通信模式经典蓝牙(BR/EDR)适合大数据量传输音频、文件低功耗蓝牙(BLE)适合小数据量、低功耗场景传感器数据本文主要讲解BLE蓝牙目前主流物联网应用二、Android蓝牙开发必备知识2.1 权限声明AndroidManifest.xml!-- 蓝牙基础权限 -- uses-permission android:nameandroid.permission.BLUETOOTH / uses-permission android:nameandroid.permission.BLUETOOTH_ADMIN / !-- Android 12 新增权限 -- uses-permission android:nameandroid.permission.BLUETOOTH_SCAN android:usesPermissionFlagsneverForLocation / uses-permission android:nameandroid.permission.BLUETOOTH_CONNECT / !-- 位置权限Android 11及以下需要 -- uses-permission android:nameandroid.permission.ACCESS_FINE_LOCATION /2.2 检查设备支持// 检查是否支持蓝牙 BluetoothAdapter bluetoothAdapter BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter null) { // 设备不支持蓝牙 } // 检查蓝牙是否开启 if (!bluetoothAdapter.isEnabled()) { // 请求开启蓝牙 Intent enableBtIntent new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }三、BLE蓝牙开发全流程3.1 步骤1发现BLE设备// 创建蓝牙适配器 BluetoothManager bluetoothManager (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter bluetoothManager.getAdapter(); // 创建扫描回调 private ScanCallback scanCallback new ScanCallback() { Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); BluetoothDevice device result.getDevice(); String deviceName device.getName(); // 设备名称 String deviceAddress device.getAddress(); // MAC地址 Log.d(BLE, 发现设备: deviceName - deviceAddress); } }; // 开始扫描 ScanSettings settings new ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build(); ListScanFilter filters new ArrayList(); // 可添加过滤条件 bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, scanCallback); // 停止扫描不再需要时调用 // bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);3.2 步骤2连接BLE设备// 连接到指定设备 BluetoothDevice device ...; // 从扫描结果中获取的设备对象 // 创建连接回调 private BluetoothGattCallback gattCallback new BluetoothGattCallback() { Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState BluetoothProfile.STATE_CONNECTED) { // 连接成功发现服务 gatt.discoverServices(); } else if (newState BluetoothProfile.STATE_DISCONNECTED) { // 断开连接 } } Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status BluetoothGatt.GATT_SUCCESS) { // 获取所有服务 ListBluetoothGattService services gatt.getServices(); for (BluetoothGattService service : services) { Log.d(BLE, 服务UUID: service.getUuid()); // 遍历服务中的特征 for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) { Log.d(BLE, 特征UUID: characteristic.getUuid()); } } } } }; // 建立连接 BluetoothGatt bluetoothGatt device.connectGatt(context, false, gattCallback);3.3 步骤3理解GATT协议核心GATTGeneric Attribute Profile是BLE通信的核心协议采用服务端-客户端架构设备角色 ├── GATT Server服务端提供数据如心率传感器 └── GATT Client客户端读取/写入数据如手机APP3.3.1 GATT层级结构GATT Server ├── Service 1 (UUID: 0000180d-0000-1000-8000-00805f9b34fb) │ ├── Characteristic A (UUID: 00002a37-0000-1000-8000-00805f9b34fb) │ │ ├── Descriptor 1 │ │ └── Descriptor 2 │ └── Characteristic B └── Service 2 └── Characteristic C3.3.2 常用UUID示例服务类型UUID格式心率服务0000180d-0000-1000-8000-00805f9b34fb电池服务0000180f-0000-1000-8000-00805f9b34fb自定义服务0000xxxx-0000-1000-8000-00805f9b34fb3.4 步骤4读写特征值读取特征值// 获取特定服务和特征 BluetoothGattService service bluetoothGatt.getService(UUID.fromString(SERVICE_UUID)); BluetoothGattCharacteristic characteristic service.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID)); // 读取特征值 bluetoothGatt.readCharacteristic(characteristic); // 在回调中处理结果 Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status BluetoothGatt.GATT_SUCCESS) { byte[] data characteristic.getValue(); // 解析数据... } }写入特征值// 设置要写入的数据 byte[] value new byte[]{0x01, 0x02, 0x03}; characteristic.setValue(value); // 写入数据 bluetoothGatt.writeCharacteristic(characteristic); // 在回调中确认结果 Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status BluetoothGatt.GATT_SUCCESS) { Log.d(BLE, 写入成功); } }启用通知实时接收数据// 启用通知 bluetoothGatt.setCharacteristicNotification(characteristic, true); // 配置描述符CCCD for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) { if (descriptor.getUuid().equals(UUID.fromString(00002902-0000-1000-8000-00805f9b34fb))) { descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); bluetoothGatt.writeDescriptor(descriptor); } } // 接收通知数据 Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { byte[] data characteristic.getValue(); // 处理实时数据... }四、实战案例控制智能灯泡4.1 设备协议假设功能服务UUID特征UUID数据类型开关状态00001800-0000-1000-8000-00805f9b34fb00002a57-0000-1000-8000-00805f9b34fbBoolean亮度调节00001800-0000-1000-8000-00805f9b34fb00002a58-0000-1000-8000-00805f9b34fbByte (0-100)4.2 开关灯代码实现// 打开灯泡 private void turnOnLight() { BluetoothGattService service bluetoothGatt.getService(UUID.fromString(SERVICE_UUID)); BluetoothGattCharacteristic switchChar service.getCharacteristic(UUID.fromString(SWITCH_CHAR_UUID)); // 写入1表示开灯 switchChar.setValue(new byte[]{0x01}); bluetoothGatt.writeCharacteristic(switchChar); } // 关闭灯泡 private void turnOffLight() { // 写入0表示关灯 switchChar.setValue(new byte[]{0x00}); bluetoothGatt.writeCharacteristic(switchChar); }4.3 调节亮度private void setBrightness(int percent) { BluetoothGattCharacteristic brightnessChar ...; // 获取亮度特征 // 将百分比转换为0-255范围 byte value (byte)(percent * 255 / 100); brightnessChar.setValue(new byte[]{value}); bluetoothGatt.writeCharacteristic(brightnessChar); }五、常见问题解决5.1 连接失败常见原因设备超出信号范围10米未正确配对部分设备需先配对设备已连接其他客户端错误的MAC地址或UUID5.2 数据解析错误使用characteristic.getValue()获取原始字节数组根据设备协议文档解析数据示例解析两个字节的温度值byte[] data characteristic.getValue(); int tempRaw (data[0] 0xFF) | ((data[1] 0xFF) 8); float temperature tempRaw / 100.0f;5.3 耗电优化建议不需要时及时断开连接bluetoothGatt.disconnect()扫描间隔不宜过长建议每次扫描不超过30秒使用低功耗扫描模式ScanSettings.SCAN_MODE_LOW_POWER六、进阶学习资源官方文档Android Bluetooth GuideBluetooth Core Specification调试工具推荐nRF ConnectAndroid/iOS应用Wireshark BLE SnifferLightBlue Explorer开源库RxAndroidBle响应式编程封装FastBle国产高效BLE库七、总结流程图蓝牙开发流程 1. 权限申请 → 2. 设备扫描 → 3. 建立连接 → 4. 发现服务 → 5. 读写特征 → 6. 启用通知 → 7. 断开连接重要提示不同厂商的BLE设备协议可能不同务必获取设备的技术文档或SDK进行开发通过本指南您已掌握Android蓝牙开发的核心知识。实际开发中请结合具体设备协议进行实现遇到问题可查阅设备文档或社区资源。祝您开发顺利