600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Android BLE低功耗蓝牙开发

Android BLE低功耗蓝牙开发

时间:2022-07-13 01:28:27

相关推荐

Android BLE低功耗蓝牙开发

啦啦啦在上一个项目中有用到BLE低功耗蓝牙开发,当时baidu google了很多资料,但大多数都是千篇一律,英文文档我这种渣渣又看不懂。。。总之刚开始查的很痛苦。所以要把自己的踩坑之路写下来记录下,,,或许能帮到后来人呢?

概念

这是低功耗蓝牙的官方文档,英文好的同学可以直接看看这个:https://developer./guide/topics/connectivity/bluetooth-le.html

低功耗蓝牙是android4.3(API level18)之后才支持的.

一个低功耗蓝牙终端包含多个Service,而Service中又包含多个Characteristic,一个Characteristic又包含一个Value和多个Descriptor.Characteristic是手机和BLE终端交换数据的关键.

这三部分都是通过UUID来获取,UUID是他们的唯一标识.

链接

扫描的部分我们就不多说了,参考官方Demo写的很详细.主要说一说链接及发送消息等.

参考官方Demo,所有的链接等操作都是放在一个service中进行的,通过在service中发送广播来通知activity来处理相关的数据.很简单呦!我们先来看看service中都做了什么~

这是初始化蓝牙适配器的方法,在开启服务时调用.

/*** Initializes a reference to the local Bluetooth adapter.* 初始化一个蓝牙适配器 里面会判断系统版本,如果低于18则返回false(低于18不支持低功耗蓝牙)** @return Return true if the initialization is successful.* 返回true表示初始化成功*/public boolean initialize() {// For API level 18 and above, get a reference to BluetoothAdapter through// BluetoothManager.if (mBluetoothManager == null) {mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);if (mBluetoothManager == null) {//无法初始化蓝牙管理器Log.e(TAG, "Unable to initialize BluetoothManager.");return false;}}mBluetoothAdapter = mBluetoothManager.getAdapter();if (mBluetoothAdapter == null) {//无法获取蓝牙适配器Log.e(TAG, "Unable to obtain a BluetoothAdapter.");return false;}return true;}

这是连接蓝牙设备的方法,address就是蓝牙设备的MAC地址,如果是扫描的则可以通过device.getAddress()来获取到这个address.

/*** Connects to the GATT server hosted on the Bluetooth LE device.** 连接成功返回true 异步返回** @param address The device address of the destination device.** @return Return true if the connection is initiated successfully. The connection result* is reported asynchronously through the* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}* callback.*/public boolean connect(final String address) {if (mBluetoothAdapter == null || address == null) {//还没有初始化或者指定地址Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");return false;}// Previously connected device. Try to reconnect. 以前连接的设备 尝试重新连接if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)&& mBluetoothGatt != null) {Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");if (mBluetoothGatt.connect()) {mConnectionState = STATE_CONNECTING;return true;} else {return false;}}//根据mac地址获取设备final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);//如果设备为null则表示未获取到设备if (device == null) {Log.w(TAG, "Device not found. Unable to connect.");return false;}// We want to directly connect to the device, so we are setting the autoConnect//我们要直接连接到设备,所以我们设置自动连接// parameter to false.mBluetoothGatt = device.connectGatt(this, false, mGattCallback);//试图创建一个新的连接Log.d(TAG, "Trying to create a new connection.");mBluetoothDeviceAddress = address;mConnectionState = STATE_CONNECTING;return true;}

在调用connectGatt(context,autoConnect,callback)方法进行连接时,我们需要传入一个context,一个boolean值,该参数表示以后是否需要自动连接到该设备,最后一个是蓝牙连接的监听回调对象BluetoothGattCallback,我们需要new 出来这个对象,重写他的几个方法,如下:

蓝牙连接状态改变的回调:在连接成功之后需要调用discoverServices方法来找服务,只有找到了服务才算是真正的连接成功.

@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {super.onConnectionStateChange(gatt, status, newState);if (newState == BluetoothProfile.STATE_CONNECTED) {mConnectionState = STATE_CONNECTING;//开始找服务,只有找到服务才算是真正的连接上了mBluetoothGatt.discoverServices();} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//发送广播通知activity连接已断开broadcastUpdate(ACTION_GATT_DISCONNECTED);mConnectionState = STATE_DISCONNECTED;} else {//发送广播通知activity连接已断开broadcastUpdate(ACTION_GATT_DISCONNECTED);mConnectionState = STATE_DISCONNECTED;}}

发现服务的回调:

在找到服务之后就是真正的连接成功了,我在这里设置了对返回数据的监听,后面具体说

@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {super.onServicesDiscovered(gatt, status);if (status == BluetoothGatt.GATT_SUCCESS) {//找到了服务,此时才是真正的连接上了设备mConnectionState = STATE_CONNECTED;//设置监听返回数据enableTXNotification();//发送广播通知activity连接成功了broadcastUpdate(ACTION_GATT_CONNECTED);} else {broadcastUpdate(ACTION_GATT_DISCONNECTED);mConnectionState = STATE_DISCONNECTED;}}

Characteristic写操作的结果回调:

这个监听在分包发送的时候需要用到,在里面判断的发送结果是否成功,成功的话则发送下一条数据,这样可以保证分包发送的顺序不会错误.

@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicWrite(gatt, characteristic, status);if (status == BluetoothGatt.GATT_SUCCESS) {//发送下一条数据}}

Characteristic状态改变的回调:

这个方法挺重要的,蓝牙广播(是指蓝牙设备本身发出的数据)出来的数据在这里获取,发送指令后蓝牙的回应也是在这里获取.当然要走这个回调必须先设置相关的characteristic的监听.

@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {super.onCharacteristicChanged(gatt, characteristic);//蓝牙状态 发送广播byte[] value = characteristic.getValue();broadcastUpdate(ACTION_GATT_UPDATE, value);}

以上就是BluetoothGattCallback对象中要重写的几个方法,下面我们说一说characteristic的监听设置

/*** 设置特征监听*/public void enableTXNotification() {BluetoothGattService RxService = mBluetoothGatt.getService(SERVICE_UUID);if (RxService == null) {L.e("未找到蓝牙中的对应服务");return;}BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(RX_UUID);if (RxChar == null) {L.e("未找到蓝牙中的对应特征");return;}//设置true为启用通知,false反之mBluetoothGatt.setCharacteristicNotification(RxChar, true);//下面为开启蓝牙notify功能,向CCCD中写入值1BluetoothGattDescriptor descriptor = RxChar.getDescriptor(CCCD);descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(descriptor);List<BluetoothGattDescriptor> descriptors = RxChar.getDescriptors();for (BluetoothGattDescriptor dp : descriptors) {dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(dp);}}

先通过Service的UUID找到对应的Service对象,再通过我们想要设置监听的Characteristic的UUID找到相应的Characteristic对象,UUID都是蓝牙设备厂商在文档中提供的.找到相应的特征后调用setCharacteristicNotification方法开启监听,就可以在该特征状态发生改变后走到onCharacteristicChanged方法中.而蓝牙的notify功能需要向CCCD中写入值1才能开启,CCCD值为:`public static final UUID CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");`

往Characteristic中写入数据:

我们知道低功耗蓝牙的特点就是快速连接,超低功耗保持连接和传输数据,其缺点是传输速率很低,每次最多向Characteristic中写入20字节的内容.因此当我们需要写入的数据过大时就要使用分包发送.

先来看看如何往Characteristic中写入数据吧

/*** 往Characteristic中写入数据* @param value 写入的数据*/public void writeRXCharacteristic(byte[] value) {if (mBluetoothGatt == null) {return;}BluetoothGattService RxService = mBluetoothGatt.getService(SERVICE_UUID);if (RxService == null) {// broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);return;}BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(TX_UUID);if (RxChar == null) {// broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);return;}RxChar.setValue(value);mBluetoothGatt.writeCharacteristic(RxChar);}

还是要先获取到Characteristic对象,然后调用setValue方法设置我们需要写入的数据,该方法接受byte[]和String,我们一般都是写入byte[].基本都要求是十六进制byte[],很多同学会在这里纠结十六进制的转换、数组中有些数据超出byte取值范围了等问题,这些你其实完全不用考虑…不用非要写成0x00这样的形式,因为对于计算机来说都是一样的,超出byte取值范围也不用担心,没有什么影响的.不过如果可以的话最好还是能和你们的硬件工程师沟通一下.

分包发送的话还是需要与硬件工程师沟通具体的分包方法,写入数据是延时多少毫秒,然后在上面onCharacteristicWrite方法中判断写入状态,成功的话则写入下一条数据,这样来保证分包数据的顺序不会错乱.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。