Android 低功耗蓝牙开发(数据交互)

private static final String TAG = BleCallback.class.getSimpleName();

/**

  • 连接状态改变回调

  • @param gatt gatt

  • @param status gatt连接状态

  • @param newState 新状态

*/

@Override

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

if (status == BluetoothGatt.GATT_SUCCESS) {

switch (newState) {

case BluetoothProfile.STATE_CONNECTED://连接成功

Log.d(TAG, “连接成功”);

break;

case BluetoothProfile.STATE_DISCONNECTED://断开连接

Log.e(TAG, “断开连接”);

break;

default:

break;

}

} else {

Log.e(TAG, "onConnectionStateChange: " + status);

}

}

}

为了区别于上一篇文章,我这里会新建一个DataExchangeActivity来做数据的交互,不会影响到上一篇文章的内容。然后在MainActivity,点击列表item时调用的connectDevice方法中跳转到DataExchangeActivity中,通过传递蓝牙对象过去。

在这里插入图片描述

接下来看看DataExchangeActivity中做了什么?

public class DataExchangeActivity extends AppCompatActivity {

private static final String TAG = DataExchangeActivity.class.getSimpleName();

/**

  • Gatt

*/

private BluetoothGatt bluetoothGatt;

/**

  • 设备是否连接

*/

private boolean isConnected = false;

/**

  • Gatt回调

*/

private BleCallback bleCallback;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_data_exchange);

//初始化

bleCallback = new BleCallback();

//获取上个页面传递过来的设备

BluetoothDevice device = getIntent().getParcelableExtra(“device”);

//连接gatt 设置Gatt回调

bluetoothGatt = device.connectGatt(this, false, bleCallback);

}

/**

  • 断开设备连接

*/

private void disconnectDevice() {

if (isConnected && bluetoothGatt != null) {

bluetoothGatt.disconnect();

}

}

/**

  • Toast提示

  • @param msg 内容

*/

private void showMsg(String msg) {

Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

}

}

很简单这个代码,就是接收上个页面传递过来的蓝牙对象,然后进行gatt连接。直接传入实例化之后的bleCallback即可,请注意关于gatt的处理都是在子线程中进行的,可以验证一下:

在这里插入图片描述

运行一下,进入交互页面。

在这里插入图片描述

下面进行GattCallback中的API介绍。

1. onPhyUpdate

/**

  • 物理层改变回调

  • @param gatt gatt

  • @param txPhy 发送速率 1M 2M

  • @param rxPhy 接收速率 1M 2M

  • @param status 更新操作的状态

*/

@Override

public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {

super.onPhyUpdate(gatt, txPhy, rxPhy, status);

}

通过gatt.setPreferredPhy()方法触发,例如:

//设置 2M

gatt.setPreferredPhy(BluetoothDevice.PHY_LE_2M, BluetoothDevice.PHY_LE_2M, BluetoothDevice.PHY_OPTION_NO_PREFERRED);

2. onPhyRead

/**

  • 读取物理层回调

  • @param gatt gatt

  • @param txPhy 发送速率 1M 2M

  • @param rxPhy 接收速率 1M 2M

  • @param status 更新操作的状态

*/

@Override

public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {

super.onPhyRead(gatt, txPhy, rxPhy, status);

}

通过gatt.readPhy();进行触发,该方法不需要传入参数。

3. onServicesDiscovered

/**

  • 发现服务回调

  • @param gatt gatt

  • @param status gatt状态

*/

@Override

public void onServicesDiscovered(BluetoothGatt gatt, int status) {

super.onServicesDiscovered(gatt, status);

}

通过gatt.discoverServices(); 触发,没有输入参数。

4. onCharacteristicRead

/**

  • 特性读取回调

  • @param gatt gatt

  • @param characteristic 特性

  • @param status gatt状态

*/

@Override

public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

super.onCharacteristicRead(gatt, characteristic, status);

}

通过gatt.readCharacteristic(characteristic);触发,需要构建一个BluetoothGattCharacteristic 对象,在后面的实例中会演示。

5. onCharacteristicWrite

/**

  • 特性写入回调

  • @param gatt gatt

  • @param characteristic 特性

  • @param status gatt状态

*/

@Override

public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

super.onCharacteristicWrite(gatt, characteristic, status);

}

通过gatt.writeCharacteristic(characteristic);触发,需要BluetoothGattCharacteristic 对象,在后面的实例中会演示。

6. onCharacteristicChanged

/**

  • 特性改变回调

  • @param gatt gatt

  • @param characteristic 特性

*/

@Override

public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

super.onCharacteristicChanged(gatt, characteristic);

}

此回调的触发需要远程设备特性改变,通俗的说就是,你需要给设备发送消息之后,才会触发这个回调。在后面的实例中会演示。

7. onDescriptorRead

/**

  • 描述符获取回调

  • @param gatt gatt

  • @param descriptor 描述符

  • @param status gatt状态

*/

@Override

public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {

super.onDescriptorRead(gatt, descriptor, status);

}

通过gatt.readDescriptor(descriptor);触发,需要传入BluetoothGattDescriptor对象,在后面的实例中会演示。

8. onDescriptorWrite

/**

  • 描述符写入回调

  • @param gatt gatt

  • @param descriptor 描述符

  • @param status gatt状态

*/

@Override

public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {

super.onDescriptorWrite(gatt, descriptor, status);

}

通过gatt.writeDescriptor(descriptor);触发,需要传入BluetoothGattDescriptor 对象,在后面的实例中会演示。

9. onReliableWriteCompleted

/**

  • 可靠写入完成回调

  • @param gatt gatt

  • @param status gatt状态

*/

@Override

public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {

super.onReliableWriteCompleted(gatt, status);

}

通过gatt.executeReliableWrite();触发,不需要参数,在实际中用的不是很多。

10. onReadRemoteRssi

/**

  • 读取远程设备的信号强度回调

  • @param gatt gatt

  • @param rssi 信号强度

  • @param status gatt状态

*/

@Override

public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {

super.onReadRemoteRssi(gatt, rssi, status);

}

通过gatt.readRemoteRssi();触发,无需参数,实际中使用不多。

11. onMtuChanged

/**

  • Mtu改变回调

  • @param gatt gatt

  • @param mtu new MTU size

  • @param status gatt状态

*/

@Override

public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {

super.onMtuChanged(gatt, mtu, status);

}

通过gatt.requestMtu(512);触发,需要传入请求的Mtu大小,最大是512,这里单位是字节,512是理论最大值,如果不设置就是默认23字节,而且传输本身用掉3字节,实际上携带数据只有20字节。在后面的实例中会演示。

最后的一个onConnectionUpdated回调无法进行覆写,就不介绍了,下面进入使用API环节。

二、使用


1. 连接设备

第一步是连接,代码在上面已经写好,连接上设备之后,

2. 获取MTU Size

下一步就是获取MtuSize。

在这里插入图片描述

然后会触发onMtuChanged回调,

3. 发现服务

在onMtuChanged回调中去发现服务。

在这里插入图片描述

然后就会触发onServicesDiscovered回调,在这个回调中要做的就是打开通知开关。这个在之前没有提到,因为它不在基础的回调API中,但是打开通知开关属于描述符的内容,因此当你设置了之后会触发onDescriptorWriteh回调,还是先来看这个通知怎么打开吧。

4. 打开通知

为了规范一些,将使用到的方法封装起来,这样便于管理,增加一个BleHelper类和BleConstant类。

新建一个utils包,包下建两个类,下面先看这个BleConstant类

public class BleConstant {

/**

  • 服务 UUID

*/

public static final String SERVICE_UUID = “0000ff01-0000-1000-8000-00805f9b34fb”;

/**

  • 特性写入 UUID

*/

public static final String CHARACTERISTIC_WRITE_UUID = “0000ff02-0000-1000-8000-00805f9b34fb”;

/**

  • 特性读取 UUID

*/

public static final String CHARACTERISTIC_READ_UUID = “0000ff10-0000-1000-8000-00805f9b34fb”;

/**

  • 描述 UUID

*/

public static final String DESCRIPTOR_UUID = “00002902-0000-1000-8000-00805f9b34fb”;

/**

  • 电池服务 UUID

*/

public static final String BATTERY_SERVICE_UUID = “0000180f-0000-1000-8000-00805f9b34fb”;

/**

  • 电池特征(特性)读取 UUID

*/

public static final String BATTERY_CHARACTERISTIC_READ_UUID = “00002a19-0000-1000-8000-00805f9b34fb”;

/**

  • OTA服务 UUID

*/

public static final String OTA_SERVICE_UUID = “5833ff01-9b8b-5191-6142-22a4536ef123”;

/**

  • OTA特征(特性)写入 UUID

*/

public static final String OTA_CHARACTERISTIC_WRITE_UUID = “5833ff02-9b8b-5191-6142-22a4536ef123”;

/**

  • OTA特征(特性)表示 UUID

*/

public static final String OTA_CHARACTERISTIC_INDICATE_UUID = “5833ff03-9b8b-5191-6142-22a4536ef123”;

/**

  • OTA数据特征(特性)写入 UUID

*/

public static final String OTA_DATA_CHARACTERISTIC_WRITE_UUID = “5833ff04-9b8b-5191-6142-22a4536ef123”;

}

这里面都是常规的UUID常量值,就是一些服务和特性的标识符,这个UUID常量值由SIG联盟所规定的,当然也可以根据自己的硬件去做设置,值不是固定的,请根据实际的硬件为主。

下面是BleHelper类,代码如下:

public class BleHelper {

/**

  • 启用指令通知

*/

public static boolean enableIndicateNotification(BluetoothGatt gatt) {

//获取Gatt 服务

BluetoothGattService service = gatt.getService(UUID.fromString(BleConstant.OTA_SERVICE_UUID));

if (service == null) {

return false;

}

//获取Gatt 特征(特性)

BluetoothGattCharacteristic gattCharacteristic = service.getCharacteristic(UUID.fromString(BleConstant.OTA_CHARACTERISTIC_INDICATE_UUID));

return setCharacteristicNotification(gatt, gattCharacteristic);

}

/**

  • 设置特征通知

  • return true, if the write operation was initiated successfully

*/

private static boolean setCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic gattCharacteristic) {

//如果特性具备Notification功能,返回true就代表设备设置成功

boolean isEnableNotification = gatt.setCharacteristicNotification(gattCharacteristic, true);

if (isEnableNotification) {

//构建BluetoothGattDescriptor对象

BluetoothGattDescriptor gattDescriptor = gattCharacteristic.getDescriptor(UUID.fromString(BleConstant.DESCRIPTOR_UUID));

gattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

//写入描述符

return gatt.writeDescriptor(gattDescriptor);

} else {

return false;

}

}

}

代码没有什么难度,下面就是在发现服务的回调中调用BleHelper中的方法。

在这里插入图片描述

当开启通知失败时断开gatt连接。

下面会进入onDescriptorWrite回调

在这里插入图片描述

当通知开启成功可以就可以进行数据的交互了,不过在此之前先运行一下,看程序是否按照我们所想的运行,看一下日志:

在这里插入图片描述

Very Good!

现在基本的前置工作都准备好了,下一步就是数据的读写了,首先来看看写数据到设备。

5. 写入数据

常规来说写入数据的话肯定是要对设备做点什么,列如一个蓝牙灯,控制这个灯开关,那么这就是一条指令,指令的内容是App与设备端协商好的,这个要以实际的需求为主。假设我对一个蓝牙手环要进行数据的写入,那么肯定会有很多的指令,所以可以封装一个方法集中处理,依然写在BleHelper中。方法如下:

/**

  • 发送指令

  • @param gatt gatt

  • @param command 指令

  • @param isResponse 是否响应

  • @return

*/

public static boolean sendCommand(BluetoothGatt gatt, String command, boolean isResponse) {

//获取服务

BluetoothGattService service = gatt.getService(UUID.fromString(BleConstant.OTA_SERVICE_UUID));

if (service == null) {

Log.e(“TAG”, “sendCommand: 服务未找到”);

return false;

}

//获取特性

BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(BleConstant.OTA_CHARACTERISTIC_WRITE_UUID));

if (characteristic == null) {

Log.e(“TAG”, “sendCommand: 特性未找到”);

return false;

}

//写入类型 WRITE_TYPE_DEFAULT 默认有响应, WRITE_TYPE_NO_RESPONSE 无响应。

characteristic.setWriteType(isResponse ?

BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT : BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);

//将字符串command转Byte后进行写入

characteristic.setValue(ByteUtils.hexStringToBytes(command));

boolean result = gatt.writeCharacteristic(characteristic);

Log.d(“TAG”, result ? “写入初始化成功:” + command : “写入初始化失败:” + command);

return result;

}

下面解释一下这个方法的内容,首先通过服务UUID获取到Gatt服务,然后通过写数据特性UUID从服务中获取写数据特性,这里的UUID的值请根据自己的实际情况填写,不知道就问硬件工程师。然后根据传入的isResponse去设置是否需要响应,这里要弄清楚有响应和无响应的区别,有响应的速度比无响应慢,但是有响应更安全,因为你可以对每一次发出的数据进行一个确认,是否发送到,有无丢失。不过这样的话效率会比较低,一般来说实际开发中大部分指令型消息都会选择无响应,数据型消息会选择有响应。

这里增加一个工具类,代码如下:

public class ByteUtils {

/**

  • Convert hex string to byte[]

  • @param hexString the hex string

  • @return byte[]

*/

public static byte[] hexStringToBytes(String hexString) {

结尾

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

想要拿高薪实现技术提升薪水得到质的飞跃。最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以为了大家能够顺利进阶中高级、架构师,我特地为大家准备了一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。

当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。

高级UI,自定义View

UI这块知识是现今使用者最多的。当年火爆一时的Android入门培训,学会这小块知识就能随便找到不错的工作了。

不过很显然现在远远不够了,拒绝无休止的CV,亲自去项目实战,读源码,研究原理吧!

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
际开发中大部分指令型消息都会选择无响应,数据型消息会选择有响应。

这里增加一个工具类,代码如下:

public class ByteUtils {

/**

  • Convert hex string to byte[]

  • @param hexString the hex string

  • @return byte[]

*/

public static byte[] hexStringToBytes(String hexString) {

结尾

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

想要拿高薪实现技术提升薪水得到质的飞跃。最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以为了大家能够顺利进阶中高级、架构师,我特地为大家准备了一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。

当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。

[外链图片转存中…(img-iB6S8nei-1714558914128)]

高级UI,自定义View

UI这块知识是现今使用者最多的。当年火爆一时的Android入门培训,学会这小块知识就能随便找到不错的工作了。

不过很显然现在远远不够了,拒绝无休止的CV,亲自去项目实战,读源码,研究原理吧!

[外链图片转存中…(img-G8LjKj2B-1714558914129)]

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 15
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值