
在上一篇中有介绍了Wifi与网络连接处理
Android开发之WiFi与网络连接处理
下面,来继续说说Android中蓝牙的基本使用。
Bluetooth是目前使用的最广泛的无线通讯协议之一,主要针对短距离设备通讯(10米),常用于连接耳机、鼠标和移动通讯设备等。
值得一提的是:
android42新增了部分新功能,但是对于Bluetooth熟悉的人或许开始头疼了,那就是Android42引入了一个新的蓝牙协议栈针BLE。谷歌和Broadcom之间的合作,开发新的蓝牙协议栈,取代了基于堆栈的Bluez。因此市场上出现了老设备的兼容问题,很多蓝牙设备在android42手机上不能正常使用。
BluetoothAdapter简单点来说就是代表了本设备(手机、电脑等)的蓝牙适配器对象。
first:we need permission
要 *** 作蓝牙,先要在AndroidManifestxml里加入权限
下面来看看如何使用蓝牙。 ↓↓↓
Demo已就绪:
返回值:如果设备具备蓝牙功能,返回BluetoothAdapter 实例;否则,返回null对象。
打开蓝牙设备的方式:
1直接调用函数enable()去打开蓝牙设备 ;
2系统API去打开蓝牙设备,该方式会d出一个对话框样式的Activity供用户选择是否打开蓝牙设备。
注意: 1如果蓝牙已经开启,不会d出该Activity界面。2在目前大多数Android手机中,是不支持在飞行模式下开启蓝牙的。如果蓝牙已经开启,那么蓝牙的开关 ,状态会随着飞行模式的状态而发生改变。
1 搜索蓝牙设备
使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备
startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个System Service中进行的,所以可以调用cancelDiscovery()方法来停止搜索(该方法可以在未执行discovery请求时调用)。
系统开始搜索蓝牙设备
^(  ̄(oo) ̄ ) ^ 系统会发送以下三个广播:
2扫描设备
3定义广播接收器接收搜索结果
4注册广播
获取附近的蓝牙设备
第一步建立连接:首先Android sdk(20以上版本)支持的蓝牙连接是通过BluetoothSocket建立连接,服务端BluetoothServerSocket和客户端(BluetoothSocket)需指定同样的UUID,才能建立连接,因为建立连接的方法会阻塞线程,所以服务器端和客户端都应启动新线程连接。
(这里的服务端和客户端是相对来说的)
两个蓝牙设备之间的连接,则必须实现服务端与客户端的机制。
当两个设备在同一个RFCOMM channel下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。
服务端设备与客户端设备获取BluetoothSocket的途径是不同的。
1,服务端设备是通过accepted一个incoming connection来获取的,
2,客户端设备则是通过打开一个到服务端的RFCOMM channel来获取的。
服务端
通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务端之间的配对)
客户端
调用BluetoothService的createRfcommSocketToServiceRecord(UUID)方法获取BluetoothSocket(该UUID应该同于服务端的UUID)。
调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务端的UUID匹配,并且连接被服务端accept,则connect()方法返回。
数据传递,通过以上 *** 作,就已经建立的BluetoothSocket连接了,数据传递无非是通过流的形式
获取流
该类就是关于远程蓝牙设备的一个描述。通过它可以和本地蓝牙设备---BluetoothAdapter连接通信。
好多东西我也不知道怎么描述,下面给出Demo:
刚好有刚学习的小伙伴问我ListView怎么用,那我就用ListView。
源码:
RairDemo
GitHub: >
openBluetoothAdapter() {
uniopenBluetoothAdapter({
success: e => {
// consolelog('初始化蓝牙成功:' + eerrMsg);
thisonBluetoothDeviceFound()
unigetBluetoothAdapterState({
success: function(res) {
// 初始化完毕开始搜索
if (resavailable) {
if (resdiscovering) {
// consolelog('停止连接');
thiscloseBluetooth()
}
unistartBluetoothDevicesDiscovery({
success: res => {
},
fail: res => {
onsolelog("查找设备失败!");
unishowToast({
icon: "none",
title: "查找设备失败!",
duration: 3000,
})
}
})
} else {
consolelog('本机蓝牙不可用')
}
}
})
},
fail: e => {
if (eerrCode == 10001) {
unishowModal({
title: "提示",
content: "您的蓝牙没有打开,请打开蓝牙",
success: function(res) {
if (resconfirm == true) {
if (unigetSystemInfoSync()platform == 'ios') {
} else if (unigetSystemInfoSync()platform === 'android') {
}
} else {
uninavigateBack({
url: '//detail3/detail3'
})
}
},
});
}
consolelog('初始化蓝牙失败,错误码:' + (eerrCode || eerrMsg));
}
});
},
onBluetoothDeviceFound() {
// consolelog("监听寻找新设备");
unionBluetoothDeviceFound(devices => {
// consolelog('开始监听寻找到新设备的事件');
// consolelog(deviceslength);
thisgetBluetoothDevices();
});
},
getBluetoothDevices() {
// consolelog("获取蓝牙设备");
unigetBluetoothDevices({
success: res => {
// consolelog('获取蓝牙设备');
thisresdic = res
// consolelog(res)
// consolelog('deviceslength===='+thisresdicdeviceslength);
for (let i = 0; i < thisresdicdeviceslength; i++) {
let devicesDic = thisresdicdevices[i];
if (devicesDicname && devicesDicname == '<Dobiy>' && devicesDicadvertisServiceUUIDs) {
thisdeviceIdStr = devicesDicdeviceId
thisstopBluetooth()
thiscreateBLEConnection(devicesDicdeviceId)
}
}
}
});
},
createBLEConnection(deviceIds) {
consolelog("连接蓝牙---------------" + deviceIds)
// setTimeout(function(){
// thatcloseBLEConnection();
// thatcreateBLEConnection(deviceIds)
// },5000)
unicreateBLEConnection({
deviceId: deviceIdstoString(),
success: (res) => {
consolelog('蓝牙连接成功');
// thisgetBLEDeviceServices(deviceIds)
thisstopBluetooth()
var that = this
unigetSystemInfo({
success(res) {
if (resplatform == 'ios') {
setTimeout(() => {
thatgetBLEDeviceServices(deviceIds)
}, 2000)
} else {
setTimeout(() => {
thatnogetBLEDeviceServices(deviceIds)
}, 3000)
}
},
fail(res) {
consolelog(777777777777777)
}
})
},
fail: (res) => {
consolelog('蓝牙连接失败:' + reserrCode)
thatcloseBLEConnection();
thatcreateBLEConnection(deviceIds)
},
});
},
async getBLEDeviceServices(deviceIds) {
var that = this
let deviceServices = await unigetBLEDeviceServices({
deviceId: deviceIds
})
if (deviceServices[0] == null) {
let services = deviceServices[1]services
if (serviceslength == 0) {
setTimeout(() => {
thatgetBLEDeviceServices(deviceIds)
}, 1500)
} else {
consolelog(services, 88888888888)
for (let i = 0; i < serviceslength; i++) {
let serviceId = services[i]uuid
// consolelog('serviceId====' + serviceId);
let characteristicsDic = await unigetBLEDeviceCharacteristics({
deviceId: deviceIds,
serviceId: serviceId,
})
then(data => {
// consolelog(JSONstringify(data))
if (data[0] == null) {
let characteristicsArr = data[1]characteristics
let properties = characteristicsArr[0]properties
consolelog(properties)
if (propertieswrite == true) {
thatserviceIdStr = serviceId;
thatcharacteristicsIdStr = data[1]characteristics[0]uuid;
thatnotifyBLECharacteristicValueChange(thatcharacteristicsIdStr)
// consolelog(deviceIds)
// consolelog(thatserviceIdStr)
// consolelog(thatcharacteristicsIdStr)
thatwriteBLECharacteristic(deviceIds, serviceId, thatcharacteristicsIdStr)
} else {
consolelog('不可编辑', data[1]characteristics[0]uuid)
}
}
})
}
}
} else {
unishowModal({
title: "提示",
content: "获取设备服务信息失败,请重新获取",
showCancel: false,
success(res) {
uninavigateBack({
url: '/uploadImg/uploadImg'
})
}
})
}
},
nogetBLEDeviceServices(deviceIds) {
var that = this
consolelog(777777)
unigetBLEDeviceServices({
deviceId: deviceIds,
success(res) {
let services = resservices
consolelog(services, 55555)
if (serviceslength == 0) {
setTimeout(() => {
thatnogetBLEDeviceServices(deviceIds)
}, 3000)
} else {
for (let i = 0; i < serviceslength; i++) {
let serviceId = services[i]uuid
//这个比对serviceId,设备厂家会告诉,因为安卓获取特征值都是不可写入的,iOS 的可以写入的,所以安卓直接判断serviceId是不是厂家发的serviceId
if (serviceId == '') {
unigetBLEDeviceCharacteristics({
deviceId: deviceIds,
serviceId: serviceId,
success(result) {
let propertiesDic = resultcharacteristics[0]
consolelog(propertiesDic, 55555)
// if (propertiesDicpropertieswrite == true) {
thatserviceIdStr = serviceId;
thatcharacteristicsIdStr = propertiesDicuuid;
thatnotifyBLECharacteristicValueChange(thatcharacteristicsIdStr)
setTimeout(() =>{
thatwriteBLECharacteristic(deviceIds, serviceId, thatcharacteristicsIdStr)
}, 2000)
// } else {
// consolelog('不可编辑', propertiesDicuuid)
// }
},
fail(result) {
consolelog(result, 2222222)
}
})
}
}
}
},
fail(res) {
consolelog(res, 8888888)
}
})
},
一定要调用这个方法,否则无法监听设备返回的数据,之前一直以为在uniwriteBLECharacteristicValue的回调里能得到返回的值,这个方法没有用,结果试了几天都不行,
notifyBLECharacteristicValueChange(characteristicId) {
consolelog(characteristicId, 'characteristicId')
uninotifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId: thisdeviceIdStr,
serviceId: thisserviceIdStr,
characteristicId: thischaracteristicsIdStr,
success: (res) => {
// consolelog(res)
// consolelog(thischaracteristicId)
consolelog('notifyBLECharacteristicValueChange success', res)
// thatwriteBLECharacteristic(deviceIds, serviceId, thatcharacteristicsIdStr)
thisonBLECharacteristicValue()
},
fail: (res) => {
consolelog('notifyBLECharacteristicValueChange success2', reserrMsg)
}
})
},
onBLECharacteristicValue() {
var that = this
unionBLECharacteristicValueChange(function(res) {
// consolelog(`characteristic ${rescharacteristicId} has changed, now is ${resvalue}`)
let resultStr = thatbufferString(resvalue)
// consolelog(resultStr,111)
if (resultStr && resultStr != '') {
//resultStr就是设备上返回的数据,根据设备不同,获取的设备格式也就不同,自己筛选吧
}
})
},
writeBLECharacteristic(deviceId, serviceId, characteristicId) {
var that = this
consolelog(1111111111)
let sgInt = thatstring2buffer('<sAg>')
// consolelog(sgIntbyteLength)
uniwriteBLECharacteristicValue({
deviceId: thatdeviceIdStr,
serviceId: thatserviceIdStr,
characteristicId: thatcharacteristicsIdStr,
value: sgInt,
success: function(res) {
consolelog(typeof(res))
consolelog('writeBLECharacteristicValue success', reserrMsg)
// thatcloseBluetooth()
},
fail: function(res) {
consolelog(typeof(res))
consolelog('writeBLECharacteristicValue fail==', reserrCode, reserrMsg)
}
})
},
//字符串转arraybuffer
string2buffer: function(str) {
// 首先将字符串转为16进制
let val = ""
for (let i = 0; i < strlength; i++) {
if (val === '') {
val = strcharCodeAt(i)toString(16)
} else {
val += ',' + strcharCodeAt(i)toString(16)
}
}
// consolelog(val)
// 将16进制转化为ArrayBuffer
return new Uint8Array(valmatch(/[\da-f]{2}/gi)map(function(h) {
return parseInt(h, 16)
}))buffer
},
//arraybuffer 转字符串
bufferString: function(str) {
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
const hexArr = Arrayprototypemapcall(
new Uint8Array(buffer),
function(bit) {
return ('00' + bittoString(16))slice(-2)
}
)
return hexArrjoin('')
}
//16进制
let systemStr = ab2hex(str)
// consolelog(hexCharCodeToStr(systemStr),99)
function hexCharCodeToStr(hexCharCodeStr) {
var trimedStr = hexCharCodeStrtrim();
var rawStr =
trimedStrsubstr(0, 2)toLowerCase() === "0x"
trimedStrsubstr(2) :
trimedStr;
var len = rawStrlength;
if (len % 2 !== 0) {
alert("Illegal Format ASCII Code!");
return "";
}
var curCharCode;
var resultStr = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStrsubstr(i, 2), 16); // ASCII Code Value
let str5 = StringfromCharCode(curCharCode)
if (str5startsWith('\n') == false) {
resultStrpush(StringfromCharCode(curCharCode));
}
}
return resultStrjoin("");
}
// consolelog(hexCharCodeToStr(systemStr),888)
return hexCharCodeToStr(systemStr)
},
//监听低功耗蓝牙连接状态的改变事件
onBLEConnectionStateChange() {
unionBLEConnectionStateChange(function(res) {
if (!resconnected) {
// consolelog('蓝牙断开链接')
thiscloseBluetooth()
}
})
},
stopBluetooth() {
unistopBluetoothDevicesDiscovery({
success: e => {
// consolelog('停止搜索蓝牙设备:' + eerrMsg);
},
fail: e => {
// consolelog('停止搜索蓝牙设备失败,错误码:' + eerrCode);
}
});
},
//关闭蓝牙模块
closeBluetooth() {
unicloseBluetoothAdapter({
success(res) {
consolelog(res)
}
})
}
},
我是手机和电脑连,你看看:
前提是你有蓝牙适配器,并且要安装好相应的驱动(如果计算机提示无法识别设备的话),然后还要装一个软件,我的电脑上是安装了“BlueSoleil”这个软件,这是蓝牙适配器自带光盘里的~~
这里还有一步是必要的,就是把手机蓝牙“设置”中的“文件传输设置”下的“目录权限”设置为“可自由存取”(若设置为“只允许读取”的话,只能从手机向电脑传文件)
下面是传输的方法了~
首先手机与电脑通过蓝牙链接~~
然后点击文件传输服务,在手机上会收到一个确认信息,点击确定后电脑上会d出一个窗口,这个窗口就是你手机的共享目录(该目录可以在手机“蓝牙”的“设置”下的“文件传输设置”中进行更改),然后你就可以从这个目录里自由的存取了~~
这个是我的使用经验,希望对你有所帮助~
Android 开发SPP经典蓝牙。
1、传统蓝牙采用的是SPP(Serial Port Profile)协议进行数据传输。
2、SPP的UUID:00001101-0000-1000-8000-00805F9B34FB
3、手机一般以客户端的角色主动连接SPP协议设备
概念:
BluetoothAdapter:
本地蓝牙适配器,是所有蓝牙交互的入口,表示蓝牙设备自身的一个蓝牙适配器,整个系统只有一个蓝牙适配器,通过他可以发现其他蓝牙设备,查询绑定(配对)设备列表,使用MAC地址实例化BluetoothDevice以及创建BluetoothServerSocket用来侦听来自其他设备的通信。
myBluetoothAdapter = BluetoothAdaptergetDefaultAdapter();//获取默认的蓝牙Adapter
BluetoothDevice:
远程的蓝牙设备。
private static BluetoothDevice myDevice;
myDevice = myBluetoothAdaptergetRemoteDevice(BDAddr);//获取远程设备,通过蓝牙的MAC地址来获取一个远程对象
两种连接方式
BluetoothSocket
客户端:调用BluetoothDevice的createRfcommSocketToServiceRecord()可以获取该对象;调用connect()方法可以建立连接。
private static BluetoothSocket mySocket = null;
private static final UUID SPP_UUID = UUIDfromString("00001101-0000-1000-8000-00805F9B34FB");
Method m = myDevicegetClass()getMethod("createRfcommSocket", new Class[] {intclass});//由BluetoothDevice衍生出BluetoothSocket, createRfcommSocket来选择连接的服务和协议
mySocket = (BluetoothSocket) minvoke(myDevice, 1);
BluetoothServerSocket:
服务端:通过BluetoothServerSocket对象可以创建BluetoothSocket对象,调用BluetoothServerSocket的accept()的方法可以得到改对象。
开发流程:
1:声明权限:
<uses-permission android:name="androidpermissionBLUETOOTH"/>
<uses-permission android:name="androidpermissionBLUETOOTH_ADMIN"/>
2:启动和关闭蓝牙
获取蓝牙适配器,使用close()接口可以关闭蓝牙适配器
myBluetoothAdapter = BluetoothAdaptergetDefaultAdapter();//获取默认的蓝牙Adapter
启动蓝牙
if (!blueadapterisEnabled())
//判断本机蓝牙是否打开
{//如果没打开,则打开蓝牙
blueadapterenable();
}
3使用BlueAdatper搜索
使用bluetoothAdapter搜索设备,bluetoothAdapterstartDiscovery()在搜索过程中,系统会发出三个广播信息:
ACTION_DISCOVERY_START:开始搜索
ACTION_DISCOVERY_FINISHED:搜索结束
ACTION_FOUND:找到设备
if (bluetoothAdapterisDiscovering()) {
bluetoothAdaptercancelDiscovery();//如果蓝牙设备未连接则取消搜索
}
bluetoothAdapterstartDiscovery();
}
4:(1)通过注册广播获取搜索到的设备。
IntentFilter intentFilter = new IntentFilter();
intentFilteraddAction(BluetoothDeviceACTION_FOUND);//找到设备广播
intentFilteraddAction(BluetoothAdapterACTION_DISCOVERY_FINISHED);//搜索完成广播
registerReceiver(receiver, intentFilter);//注册广播接收器
// receiver
private final BroadcastReceiver receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intentgetAction();
if (BluetoothDeviceACTION_FOUNDequals(action)) {
// find a device
BluetoothDevice device = intent getParcelableExtra(BluetoothDeviceEXTRA_DEVICE);
if (devicegetBondState() != BluetoothDeviceBOND_BONDED) {
//未配对设备
newDeviceArrayAdapteradd(devicegetName() + "\n" + devicegetAddress());
}else {
//已经配对过的设备
TextView tvPaired = (TextView)findViewById(Ridtv_paired);
tvPairedsetVisibility(ViewVISIBLE);
lvPairedDevicessetVisibility(ViewVISIBLE);
pairedDeviceArrayAdapteradd(devicegetName() + "\n" + devicegetAddress());
}
Logi(TAG,"name:" + devicegetName() + " address"+ devicegetAddress());
} else if (BluetoothAdapterACTION_DISCOVERY_FINISHEDequals(action){
// search finish
Logi(TAG, "search finish!");
}
}
};
(2),直接得到当前的蓝牙设备后,就可用通过遍历pairedDevices ,得到当前手机已经配对过的蓝牙设备。
Set<BluetoothDevice> pairedDevices = myBluetoothAdaptergetBondedDevices();//获取当前蓝牙设备
if (pairedDevicessize() <= 0) return false;
for (BluetoothDevice device : pairedDevices) {
Map<String, String> map = new HashMap<String, String>();
mapput("DeviceName", devicegetName());
mapput("BDAddress", devicegetAddress());
listadd(map);
5建立连接
private static final UUID SPP_UUID = UUIDfromString("00001101-0000-1000-8000-00805F9B34FB");
Method m = myDevicegetClass()getMethod("createRfcommSocket", new Class[] {intclass});//由BluetoothDevice衍生出BluetoothSocket, createRfcommSocket来选择连接的服务和协议
mySocket = (BluetoothSocket) minvoke(myDevice, 1);
mySocketconnect();//使用BluetoothSocket来连接设备
6把得到的蓝牙设备给通过点击ListView选择设备。
listViewsetOnItemClickListener(new ListViewOnItemClickListener() {
public void onItemClick(AdapterView<> arg0, View arg1, int arg2, long arg3) {
SelectedBDAddress = listget(arg2)get("BDAddress");
if (((ListView) arg0)getTag() != null) {
((View) ((ListView) arg0)getTag())setBackgroundDrawable(null);
}
((ListView) arg0)setTag(arg1);
arg1setBackgroundColor(ColorBLUE);
myDevice = myBluetoothAdaptergetRemoteDevice(SelectedBDAddress);
}
});
7客户端发送数据
当两个设备成功连接之后,双方都会有一个BluetoothSocket对象,这时,就可以在设备之间传送数据了。
1使用getOutputStream()方法来获取输出流来处理传输。
2调用write()。
os = socketgetOutputStream();//获取输出流
if (os != null) {//判断输出流是否为空
oswrite(messagegetBytes("UTF-8"));
}
osflush();//将输出流的数据强制提交
osclose();//关闭输出流
}
将输出流中的数据提交后,要记得关闭输出流,否则,可能会造成只能发送一次数据。
8服务端接收数据
1使用getInputStream()方法来获取输入流来处理传输。
2调用read()。
InputStream im=null;
im=bluetoothSocketgetInputStream();
byte buf[] = new byte[1024];
if (is != null) {
isread(buf, 0, buflength);//读取发来的数据
String message = new String(buf);//把发来的数据转化为String类型
BuletoothMainActivityUpdateRevMsg(message);//更新信息在显示文本框
isclose();//关闭输入流
使用服务端接收数据时,要先从客户端向服务端发起连接,只有接收到连接请求之后,才会返回一个BluetoothSocket对象。有BluetoothSocket对象才能获取到输入流。
我实现的小程序模块自动连接(根据需要,可改手动),是在小程序初始化完成时开始自动调用执行。
大致流程:
开启蓝牙适配;
获取蓝牙适配器状态,判断设备蓝牙是否可用;
判断蓝牙适配器可用时开启扫描蓝牙设备和开启获取已连接的蓝牙设备;
如果开启扫描蓝牙设备失败 5 s 后,自动再次开启扫描;
开启扫描蓝牙设备成功后,开启监听已扫描的设备;
如果已扫描到的新设备,包含特定名称规律,则开始连接该设备;
开启获取已连接蓝牙设备,成功后,连接包含特定名称规律的设备;
两者都无法搜索到相应设备,则等待 5 s,重新搜索;
开始连接某设备时停止扫描设备,停止循环获取已连接设备;
连接成功后停止扫描设备,停止循环获取已连接设备。
下面,我们一步步来完成这个流程。
开始连接蓝牙设备
1 开启连接
appjs的onLaunch()方法里中,我们调用thisstartConnect();来开启连接,d出提示框,进行配对。如果失败,则提示设备蓝牙不可用,同时开启蓝牙适配器状态监听。
2 获取本机蓝牙状态
调用thisgetBluetoothAdapterState()获取本机蓝牙适配器状态,判断是否可用。若available为false,则为用户没有开启系统蓝牙。
同时,判断程序还没有开始搜索蓝牙设备,调用thisstartBluetoothDevicesDiscovery()开始扫描附近的蓝牙设备,以及thisgetConnectedBluetoothDevices(),获取本机已配对的蓝牙设备。
3 开始搜索新设备
开始搜索蓝牙设备startBluetoothDevicesDiscovery(),提示蓝牙搜索。
4 获取已配对的蓝牙设备
需要注意的是,参数services(Array)是必填的,但是官方示例中以及各种坑爹 demo 里从没见过有谁填写。不填写这个属性此方法,将无法获取到任何已配对设备。
如果要调用此方法,则代表需要连接特定设备,并且知道该设备的一个主服务serviceId。
如暂时不知道这个 ID,可以先手动连接一次想要连接的设备,然后获取service列表,记录属性primary为true的值至少一个。5 处理搜索功能开启失败的情况
如果搜索功能启动失败,回到第 2 步,重新检查蓝牙适配器。如果可用,开启蓝牙搜索功能并开启发现附近蓝牙设备事件监听:thisonBluetoothDeviceFound()。
此方法可自定义过滤一些无效的蓝牙设备,比如name为空的,或是产品开发中,需要过滤设备名称不含有特定规律字符串的设备。
6 自动配对设备
在第 5 步中发现了某个想配对的设备,则获取到该设备的deviceId,然后用thisstartConnectDevices()接口,开始配对该设备。
开启连接后,为了避免出现冲突,一旦开启连接,则需要终止扫描附近蓝牙设备、终止读取本机已配对设备
7 连接成功后握手
连接成功后,使用thisgetService(deviceId)接口,获取设备的所有服务。
8 读取服务的特征值
9 意外处理
如果扫描到的设备中没有想要连接的设备,可以尝试使用系统蓝牙手动配对,然后再小程序中调用getConnectedBluetoothDevices()获取本机已配对的蓝牙设备,然后过滤设备(可能获取多个已配对的蓝牙设备)。
然后,将已获取的蓝牙设备deviceId列表放入到一个数组中,然后调用自定义方法thisloopConnect();
思路:通过递归调用获取已配对蓝牙设备的,如果获取到了就去连接,如果devicesId[x]为空,说明上传调用时,获取到的已配对设备全部连接失败了。
这时候,我们需要则开启重新获取已配对蓝牙设备,并开启扫描附近蓝牙设备。
10 自动循环重试
startConnectDevices('loop', array)方法,是当获取已配对蓝牙设备进行连接时调用。
其中的处理逻辑上文已经贴出,意思就是在连接失败后fail方法里累加一个全局变量,然后回调loopConnect(array)方法。
11 手动连接
上文介绍的方法是为了直接自动连接,如果不需要自动连接,可使用方法getBluetoothDevices(),获取已扫描到的蓝牙设备的列表。
开发者可以做个页面显示出设备名,用户点击某个设备后,才开始连接。
需要注意的事项
thatserviceId是在初始化时设置的,由于对需要连接设备的主服务serivceId和各种特征值都是已知的,因此可以这样做。如果不可知,可以做一个扫描方法自己检查特征值的用途。
连接成功后的writeBLECharacteristicValue和openNotifyService *** 作需要注意,如果同时开启这两项 *** 作要先调用wirte再开启notify(原因未知,个人心得)。
3、经提醒,我发现还可以再完善一下在onBlueToothAdapterStateChange()监听蓝牙适配器状态,以此判断连接过程中、连接后用户开关了设备蓝牙。如果判断到关了蓝牙,发出开启蓝牙的提示;如果监听到开启了,就重新回到第 1 步。
厂商获取。
1、一般蓝牙设备数据的读取和写入都需要通过UUID找到对应服务和特征值下的Value值。
2、发送指令需要用到wxgetBLEDeviceCharacteristics发送密钥(密钥是从厂商获取到的)指令给门锁。
以上就是关于Android开发之蓝牙(Bluetooth)全部的内容,包括:Android开发之蓝牙(Bluetooth)、ios 智能电表蓝牙连接、uniapp 通过蓝牙连接设备并发送命令等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)