承接上一篇文章http://t.csdnimg.cn/pAwZE讲解怎么简单方便的使用:
首先我们先定义一个基类,将常用的方法放到公共的类中,这样我们使用起来就比较方便,例如:
abstract fun connect() abstract fun initNotiy() abstract fun initWrite(cmd: ByteArray)
在使用中我们就可以创建一个类继承基类:在使用的类中具体使用如下:
先将对应的服务、读、写的UUID添加上:
var uuid_service = "蓝牙服务UUID" var uuid_notify = "蓝牙读数据的UUID" var uuid_write = "蓝牙写入数据的UUID"
然后,进行连接蓝牙的操作:具体使用如下:
BleManager.getInstance().connect(bleDevice, object : BleGattCallback() {
override fun onStartConnect() {
//可以做开始连接蓝牙的操作
}
override fun onConnectFail(bleDevice: BleDevice, exception: BleException) {
//可以做蓝牙连接失败的操作
}
override fun onConnectSuccess(bleDevice: BleDevice, gatt: BluetoothGatt, status: Int) {
//获取蓝牙服务
var serviceList = BleManager.getInstance().getBluetoothGatt(bleDevice).getServices()
//获取当前环境搜索到的蓝牙地址的集合,然后进行循环找出我们需要的蓝牙设备进行连接、读写数据等操作
for (service in serviceList) {
val characteristicList = service.characteristics
for (e in characteristicList) {
var uuid = e.uuid.toString()
}
}
}
override fun onDisConnected(
isActiveDisConnected: Boolean,
device: BleDevice,
gatt: BluetoothGatt,
status: Int
) {
//可以做蓝牙连接失败的操作
}
})
下面进行蓝牙读写的操作:
打开通知:bleDevice:蓝牙设备地址 uuid_service:服务UUID uuid_notify:读的UUID
BleManager.getInstance().notify(bleDevice, uuid_service, uuid_notify,
object : BleNotifyCallback() {
override fun onNotifySuccess() {
// initWrites(BleCmd.collection2())
// 打开通知操作成功
}
override fun onNotifyFailure(exception: BleException) {
LogeUtils.e("失败: " + exception.description)
}
override fun onCharacteristicChanged(data: ByteArray) {
// 打开通知后,设备发过来的数据将在这里出现
//将接受到的数据转为16进制,方便我们做后续的处理
val hexStr = formatHexString(data)
}
})
写入数据的操作:其中cmd是我们写入蓝牙的指令
bleDevice:蓝牙设备地址 uuid_service:服务UUID uuid_write:写的UUID
override fun initWrite(cmd: ByteArray) {
BleManager.getInstance().write(
bleDevice,
characteristic.getService().getUuid().toString(),
uuid_write,
cmd,
object : BleWriteCallback() {
override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray) {
initNotiy()
}
override fun onWriteFailure(exception: BleException) {
LogeUtils.e(exception.description)
}
})
}
其中用到的formatHexString这个方法如下:
public static String formatHexString(byte[] data) {
return formatHexString(data, false);
}
public static String formatHexString(byte[] data, boolean addSpace) {
if (data == null || data.length < 1)
return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
String hex = Integer.toHexString(data[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex);
if (addSpace)
sb.append("-");
}
return sb.toString().trim();
}
以上就是讲解的低功耗蓝牙的具体使用,具体的原生使用方式待续。
本文介绍了如何在Android中通过定义基类和抽象方法,实现低功耗蓝牙的连接、服务查找、读取数据(通过通知)和写入数据的过程,包括BleManager和BluetoothGatt的使用实例。
的详解二&spm=1001.2101.3001.5002&articleId=134965521&d=1&t=3&u=bb60dffa5bf942aa9a35a3f58b41433b)
2091

被折叠的 条评论
为什么被折叠?



