一篇了解 BLE 蓝牙开发详解

移动开发 Android
Android 4.3(API Level 18)开始引入Bluetooth Low Energy(BLE,低功耗蓝牙)的核心功能并提供了相应的 API, 应用程序通过这些 API 扫描蓝牙设备、查询 services、读写设备的 characteristics(属性特征)等操作。

[[432207]]

前言

有老铁们私信,要讲解下蓝牙开发,那么今天来了;

Android 4.3(API Level 18)开始引入Bluetooth Low Energy(BLE,低功耗蓝牙)的核心功能并提供了相应的 API, 应用程序通过这些 API 扫描蓝牙设备、查询 services、读写设备的 characteristics(属性特征)等操作。

BLE低功耗蓝牙,主要特点是快速搜索,快速连接,超低功耗保持连接和数据传输;

一、BLE开发流程

1、申请权限

安卓手机涉及蓝牙权限问题,蓝牙开发需要在AndroidManifest.xml文件中添加权限声明:

  1. <!-- 蓝牙权限 --> 
  2. <uses-permission android:name="android.permission.BLUETOOTH" /> 
  3. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
  4. 为适配安卓6.0以及以上版本需要添加一个模糊定位的权限 
  5.  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
  6. 手机权限管理中允许此权限,否则会出现无法搜索到设备的情况; 

为适配安卓6.0以及以上版本需要添加一个模糊定位的权限

手机权限管理中允许此权限,否则会出现无法搜索到设备的情况;

2、打开蓝牙

在搜索设备之前需要询问打开手机蓝牙:

  1. //获取系统蓝牙适配器管理类 
  2.     private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter 
  3.             .getDefaultAdapter(); 
  4.     // 询问打开蓝牙 
  5.     if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) { 
  6.             Intent enableBtIntent = new Intent( 
  7.                     BluetoothAdapter.ACTION_REQUEST_ENABLE); 
  8.             startActivityForResult(enableBtIntent, 1); 
  9.     } 
  10.       // 申请打开蓝牙请求的回调 
  11.     @Override 
  12.     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
  13.         // TODO Auto-generated method stub 
  14.         super.onActivityResult(requestCode, resultCode, data); 
  15.         if (requestCode == 1) { 
  16.             if (resultCode == RESULT_OK) { 
  17.                 Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show(); 
  18.             } else if (resultCode == RESULT_CANCELED) { 
  19.                 Toast.makeText(this, "没有蓝牙权限", Toast.LENGTH_SHORT).show(); 
  20.                 finish(); 
  21.             } 
  22.         } 
  23.     } 

3、搜索设备

  1. mBluetoothAdapter.startLeScan(callback); 
  2. private LeScanCallback callback = new LeScanCallback() { 
  3.     @Override 
  4.     public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) { 
  5.         //device为扫描到的BLE设备 
  6.         if(device.getName() == "目标设备名称"){ 
  7.             //获取目标设备 
  8.             targetDevice = device; 
  9.         } 
  10.     } 
  11. }; 

4、连接设备

通过扫描BLE设备,根据设备名称区分出目标设备targetDevice,下一步实现与目标设备的连接,在连接设备之前要停止搜索蓝牙;

mBluetoothAdapter.stopLeScan(callback);

停止搜索一般需要一定的时间来完成,最好调用停止搜索函数之后加以100ms的延时,保证系统能够完全停止搜索蓝牙设备。停止搜索之后启动连接过程;

BLE蓝牙的连接方法相对简单只需调用connectGatt方法;

  1. mBluetoothAdapter.startLeScan(callback); 
  2. private LeScanCallback callback = new LeScanCallback() { 
  3.     @Override 
  4.     public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) { 
  5.         //device为扫描到的BLE设备 
  6.         if(device.getName() == "目标设备名称"){ 
  7.             //获取目标设备 
  8.             targetDevice = device; 
  9.         } 
  10.     } 
  11. }; 

参数说明

返回值 BluetoothGatt: BLE蓝牙连接管理类,主要负责与设备进行通信;

boolean autoConnect:建议置为false,能够提升连接速度;

BluetoothGattCallback callback 连接回调,重要参数,BLE通信的核心部分;

5、设备通信

与设备建立连接之后与设备通信,整个通信过程都是在BluetoothGattCallback的异步回调函数中完成;

BluetoothGattCallback中主要回调函数如下:

  1. private BluetoothGattCallback gattCallback = new BluetoothGattCallback() { 
  2.         @Override 
  3.         public void onConnectionStateChange(BluetoothGatt gatt, int status, 
  4.                 int newState) { 
  5.         } 
  6.         @Override 
  7.         public void onCharacteristicWrite(BluetoothGatt gatt, 
  8.                 BluetoothGattCharacteristic characteristic, int status) { 
  9.             super.onCharacteristicWrite(gatt, characteristic, status); 
  10.         } 
  11.         @Override 
  12.         public void onDescriptorWrite(BluetoothGatt gatt, 
  13.                 BluetoothGattDescriptor descriptor, int status) { 
  14.         }; 
  15.         @Override 
  16.         public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
  17.         } 
  18.         @Override 
  19.         public void onCharacteristicChanged(BluetoothGatt gatt, 
  20.                 BluetoothGattCharacteristic characteristic) { 
  21.         } 
  22.     }; 

上述几个回调函数是BLE开发中不可缺少的;

6、等待设备连接成功

当调用targetdDevice.connectGatt(context, false, gattCallback)后系统会主动发起与BLE蓝牙设备的连接,若成功连接到设备将回调onConnectionStateChange方法,其处理过程如下:

  1. @Override 
  2. public void onConnectionStateChange(BluetoothGatt gatt, int status, 
  3.                 int newState) { 
  4.             if (newState == BluetoothGatt.STATE_CONNECTED) { 
  5.                 Log.e(TAG, "设备连接上 开始扫描服务"); 
  6.                 // 开始扫描服务,安卓蓝牙开发重要步骤之一 
  7.                 mBluetoothGatt.discoverServices(); 
  8.             } 
  9.             if (newState == BluetoothGatt.STATE_DISCONNECTED) { 
  10.                 // 连接断开 
  11.                 /*连接断开后的相应处理*/       
  12.             } 
  13. }; 

判断newState == BluetoothGatt.STATE_CONNECTED表明此时已经成功连接到设备;

7、开启扫描服务

mBluetoothGatt.discoverServices();

扫描BLE设备服务是安卓系统中关于BLE蓝牙开发的重要一步,一般在设备连接成功后调用,扫描到设备服务后回调onServicesDiscovered()函数,函数原型如下:

  1. @Override 
  2. public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
  3.     private List<BluetoothGattService> servicesList; 
  4.     //获取服务列表 
  5.     servicesList = mBluetoothGatt.getServices(); 
  • BLE蓝牙协议下数据的通信方式采用BluetoothGattService、BluetoothGattCharacteristic和BluetoothGattDescriptor三个主要的类实现通信;
  • BluetoothGattService 简称服务,是构成BLE设备协议栈的组成单位,一个蓝牙设备协议栈一般由一个或者多个BluetoothGattService组成;
  • BluetoothGattCharacteristic 简称特征,一个服务包含一个或者多个特征,特征作为数据的基本单元;
  • 一个BluetoothGattCharacteristic特征包含一个数据值和附加的关于特征的描述
  • BluetoothGattDescriptor:用于描述特征的类,其同样包含一个value值;

8、获取负责通信的BluetoothGattCharacteristic

BLE蓝牙开发主要有负责通信的BluetoothGattService完成的。当且称为通信服务。通信服务通过硬件工程师提供的UUID获取。获取方式如下:

  • BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("蓝牙模块提供的负责通信UUID字符串"));
  • 通信服务中包含负责读写的BluetoothGattCharacteristic,且分别称为notifyCharacteristic和writeCharacteristic。其中notifyCharacteristic负责开启监听,也就是启动收数据的通道,writeCharacteristic负责写入数据;

具体操作方式如下:

  1. BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("蓝牙模块提供的负责通信服务UUID字符串")); 
  2.    // 例如形式如:49535343-fe7d-4ae5-8fa9-9fafd205e455 
  3.   notifyCharacteristic = service.getCharacteristic(UUID.fromString("notify uuid")); 
  4.   writeCharacteristic =  service.getCharacteristic(UUID.fromString("write uuid")); 

9、开启监听

开启监听,即建立与设备的通信的首发数据通道,BLE开发中只有当上位机成功开启监听后才能与下位机收发数据。开启监听的方式如下:

  1. mBluetoothGatt.setCharacteristicNotification(notifyCharacteristic, true
  2. BluetoothGattDescriptor descriptor = characteristic 
  3.                             .getDescriptor(UUID 
  4.                                     .fromString 
  5. ("00002902-0000-1000-8000-00805f9b34fb")); 
  6. descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); 

若开启监听成功则会回调BluetoothGattCallback中的onDescriptorWrite()方法,处理方式如下:

  1. @Override 
  2. public void onDescriptorWrite(BluetoothGatt gatt, 
  3.                 BluetoothGattDescriptor descriptor, int status) { 
  4.         if (status == BluetoothGatt.GATT_SUCCESS) { 
  5.             //开启监听成功,可以像设备写入命令了 
  6.             Log.e(TAG, "开启监听成功"); 
  7.         } 
  8. }; 

10、写入数据

监听成功后通过向 writeCharacteristic写入数据实现与下位机的通信。写入方式如下:

  1. //value为上位机向下位机发送的指令 
  2. writeCharacteristic.setValue(value); 
  3. mBluetoothGatt.writeCharacteristic(writeCharacteristic) 

其中:value一般为Hex格式指令,其内容由设备通信的蓝牙通信协议规定;

11、接收数据

若写入指令成功则回调BluetoothGattCallback中的onCharacteristicWrite()方法,说明将数据已经发送给下位机;

  1. @Override 
  2. public void onCharacteristicWrite(BluetoothGatt gatt, 
  3.             BluetoothGattCharacteristic characteristic, int status) { 
  4.             if (status == BluetoothGatt.GATT_SUCCESS) { 
  5.                 Log.e(TAG, "发送成功"); 
  6.             }    
  7.             super.onCharacteristicWrite(gatt, characteristic, status); 

若发送的数据符合通信协议,则下位机会向上位机回复相应的数据。发送的数据通过回调onCharacteristicChanged()方法获取,其处理方式如下:

  1. @Override 
  2. public void onCharacteristicChanged(BluetoothGatt gatt, 
  3.                 BluetoothGattCharacteristic characteristic) { 
  4.             // value为设备发送的数据,根据数据协议进行解析 
  5.             byte[] value = characteristic.getValue(); 

通过向下位机发送指令获取下位机的回复数据,即可完成与设备的通信过程;

12、断开连接

当与设备完成通信之后之后一定要断开与设备的连接。调用以下方法断开与设备的连接:

  1. mBluetoothGatt.disconnect(); 
  2.  
  3. mBluetoothGatt.close(); 

二、蓝牙操作的注意事项

  • 蓝牙的写入操作, 读取操作必须序列化进行. 写入数据和读取数据是不能同时进行的, 如果调用了写入数据的方法, 马上调用又调用写入数据或者读取数据的方法,第二次调用的方法会立即返回 false, 代表当前无法进行操作;
  • Android 连接外围设备的数量有限,当不需要连接蓝牙设备的时候,必须调用 BluetoothGatt#close 方法释放资源;
  • 蓝牙 API 连接蓝牙设备的超时时间大概在 20s 左右,具体时间看系统实现。有时候某些设备进行蓝牙连接的时间会很长,大概十多秒。如果自己手动设置了连接超时时间在某些设备上可能会导致接下来几次的连接尝试都会在 BluetoothGattCallback#onConnectionStateChange 返回 state == 133;
  • 所有的蓝牙操作使用 Handler 固定在一条线程操作,这样能省去很多因为线程不同步导致的麻烦;

总结

 

蓝牙开发中有很多问题,要静下心分析问题,肯定可以解决的,一起加油;

 

责任编辑:武晓燕 来源: Android开发编程
相关推荐

2015-09-22 11:04:24

蓝牙4.0开发

2022-12-19 08:14:30

注解开发配置

2022-10-26 07:39:36

MVCC数据库RR

2021-05-20 06:57:16

RabbitMQ开源消息

2022-01-25 16:54:14

BLE操作系统鸿蒙

2023-03-08 21:30:33

2021-07-14 10:08:30

责任链模式加工链

2021-10-28 19:15:02

IPUARM

2021-07-10 09:02:42

编程语言 TypeScript

2020-10-09 08:15:11

JsBridge

2023-05-12 08:19:12

Netty程序框架

2021-12-30 09:38:51

DDoS攻击防范

2021-07-28 10:02:54

建造者模式代码

2021-06-30 00:20:12

Hangfire.NET平台

2021-07-14 08:24:23

TCPIP 通信协议

2022-06-08 00:10:33

数据治理框架

2021-08-11 07:02:21

npm包管理器工具

2021-11-24 08:51:32

Node.js监听函数

2021-08-02 06:34:55

Redis删除策略开源

2021-11-08 08:42:44

CentOS Supervisor运维
点赞
收藏

51CTO技术栈公众号