手机蓝牙app开发教程(微信小程序蓝牙教程--完整版亲测)

本文目录
微信小程序蓝牙教程--完整版亲测
#使用mpvue 开发小程序过程中 简单介绍一下微信小程序蓝牙连接过程
#在蓝牙连接的过程中部分api需要加定时器延时1秒到2秒左右再执行,原因为何不知道,小程序有这样的要求
#1.首先是要初始化蓝牙:openBluetoothAdapter()
```js
if (wx.openBluetoothAdapter) {
wx.openBluetoothAdapter({
success: function(res) {
/* 获取本机的蓝牙状态 */
setTimeout(() =》 {
getBluetoothAdapterState()
}, 1000)
},
fail: function(err) {
// 初始化失败
}
})
} else {
}
```
#2.检测本机蓝牙是否可用:
# 要在上述的初始化蓝牙成功之后回调里调用
```js
getBluetoothAdapterState() {
var that= this;
that.toastTitle= ’检查蓝牙状态’
wx.getBluetoothAdapterState({
success: function(res) {
startBluetoothDevicesDiscovery()
},
fail(res) {
console.log(res)
}
})
}
```
#3. 开始搜索蓝牙设备:
```js
startBluetoothDevicesDiscovery() {
var that= this;
setTimeout(() =》 {
wx.startBluetoothDevicesDiscovery({
success: function(res) {
/* 获取蓝牙设备列表 */
that.getBluetoothDevices()
},
fail(res) {
}
})
}, 1000)
}
```
#4. 获取搜索到的蓝牙设备列表
# /* that.deviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的,所以根据设备名称匹配蓝牙*/
```js
getBluetoothDevices() {
var that= this;
setTimeout(() =》 {
wx.getBluetoothDevices({
services: ,
allowDuplicatesKey: false,
interval: 0,
success: function(res) {
if (res.devices.length》 0) {
if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {
for (let i = 0; i 《 res.devices.length; i++) {
if (that.deviceName === res.devices.name) {
/* 根据指定的蓝牙设备名称匹配到deviceId */
that.deviceId = that.devices.deviceId;
setTimeout(() =》 {
that.connectTO();
}, 2000);
};
};
} else {
}
} else {
}
},
fail(res) {
console.log(res, ’获取蓝牙设备列表失败=====’)
}
})
}, 2000)
},
```
#5.连接蓝牙
# 匹配到的蓝牙设备ID 发送连接蓝牙的请求, 连接成功之后 应该断开蓝牙搜索的api,然后去获取所连接蓝牙设备的service服务
```js
connectTO() {
wx.createBLEConnection({
deviceId: deviceId,
success: function(res) {
that.connectedDeviceId = deviceId;
/* 4.获取连接设备的service服务 */
that.getBLEDeviceServices();
wx.stopBluetoothDevicesDiscovery({
success: function(res) {
console.log(res, ’停止搜索’)
},
fail(res) {
}
})
},
fail: function(res) {
}
})
}
```
#6. 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值
```js
getBLEDeviceServices() {
setTimeout(() =》 {
wx.getBLEDeviceServices({
deviceId: that.connectedDeviceId,
success: function(res) {
that.services= res.services
/* 获取连接设备的所有特征值 */
that.getBLEDeviceCharacteristics()
},
fail: (res) =》 {
}
})
}, 2000)
},
```
#7.获取蓝牙设备特征值
# 获取到的特征值有多个,最后要用的事能读,能写,能监听的那个值的uuid作为特征值id,
```js
getBLEDeviceCharacteristics() {
setTimeout(() =》 {
wx.getBLEDeviceCharacteristics({
deviceId: connectedDeviceId,
serviceId: services.uuid,
success: function(res) {
for (var i = 0; i 《 res.characteristics.length; i++) {
if ((res.characteristics.properties.indicate) &&
(res.characteristics.properties.write)) {
console.log(res.characteristics.uuid, ’蓝牙特征值 ==========’)
/* 获取蓝牙特征值 */
that.notifyCharacteristicsId = res.characteristics.uuid
// 启用低功耗蓝牙设备特征值变化时的 notify 功能
that.notifyBLECharacteristicValueChange()
}
}
},
fail: function(res) {
}
})
}, 1000)
},
```
#8.启动notify 蓝牙监听功能 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据
#接收到的数据和发送的数据必须是二级制数据, 页面展示的时候需要进行转换
```js
notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能
var that= this;
console.log(’6.启用低功耗蓝牙设备特征值变化时的 notify 功能’)
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: that.connectedDeviceId,
serviceId: that.notifyServicweId,
characteristicId: that.notifyCharacteristicsId,
complete(res) {
/*用来监听手机蓝牙设备的数据变化*/
wx.onBLECharacteristicValueChange(function(res) {
/**/
that.balanceData += that.buf2string(res.value)
that.hexstr += that.receiveData(res.value)
})
},
fail(res) {
console.log(res, ’启用低功耗蓝牙设备监听失败’)
that.measuringTip(res)
}
})
},
/*转换成需要的格式*/
buf2string(buffer) {
var arr = Array.prototype.map.call(new Uint8Array(buffer), x =》 x)
return arr.map((char, i) =》 {
return String.fromCharCode(char);
}).join(’’);
},
receiveData(buf) {
return this.hexCharCodeToStr(this.ab2hex(buf))
},
/*转成二进制*/
ab2hex (buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer), function (bit) {
return (’00’ + bit.toString(16)).slice(-2)
}
)
return hexArr.join(’’)
},
/*转成可展会的文字*/
hexCharCodeToStr(hexCharCodeStr) {
var trimedStr = hexCharCodeStr.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === ’0x’ ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
var curCharCode;
var resultStr= ;
for (var i = 0; i 《 len; i = i+ 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join(’’);
},
```
# 向蓝牙设备发送数据
```js
sendData(str) {
let that= this;
let dataBuffer = new ArrayBuffer(str.length)
let dataView = new DataView(dataBuffer)
for (var i = 0; i 《 str.length; i++) {
dataView.setUint8(i, str.charAt(i).charCodeAt())
}
let dataHex = that.ab2hex(dataBuffer);
this.writeDatas = that.hexCharCodeToStr(dataHex);
wx.writeBLECharacteristicValue({
deviceId: that.connectedDeviceId,
serviceId: that.notifyServicweId,
characteristicId: that.notifyCharacteristicsId,
value: dataBuffer,
success: function (res) {
console.log(’发送的数据:’ + that.writeDatas)
console.log(’message发送成功’)
},
fail: function (res) {
},
complete: function (res) {
}
})
},
```
# 当不需要连接蓝牙了后就要关闭蓝牙,并关闭蓝牙模块
```js
// 断开设备连接
closeConnect() {
if (that.connectedDeviceId) {
wx.closeBLEConnection({
deviceId: that.connectedDeviceId,
success: function(res) {
that.closeBluetoothAdapter()
},
fail(res) {
}
})
} else {
that.closeBluetoothAdapter()
}
},
// 关闭蓝牙模块
closeBluetoothAdapter() {
wx.closeBluetoothAdapter({
success: function(res) {
},
fail: function(err) {
}
})
},
```
#在向蓝牙设备传递数据和接收数据的过程中,并未使用到read的API 不知道有没有潜在的问题,目前线上运行为发现任何的问题
#今天的蓝牙使用心得到此结束,谢谢
如何开始蓝牙软件开发(蓝牙app开发教程)
蓝牙是一套通讯标准,你上面说的配置、协议都是蓝牙协议的一部分,协议内部的术语而已,某些部分能改某些不能,简单来说,如果你拿到一个芯片,芯片厂商会给你一些软件固件,这些固件里面就实现了蓝牙相关的(你上面说的)配置和协议等。
android蓝牙开发,PC端模拟串口接收字符,该如何编程
您好,android蓝牙这方面还是很好搞的,因为大家的方式都是差不多的。先说说如何开启蓝牙设备和设置可见时间:
private void search() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
adapter.enable();
}
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600为蓝牙设备可见时间
startActivity(enable);
Intent searchIntent = new Intent(this, ComminuteActivity.class);
startActivity(searchIntent);
}
首先,需要获得一个BluetoothAdapter,可以通过getDefaultAdapter()获得系统默认的蓝牙适配器,当然我们也可以自己指定,但这个真心没有必要,至少我是不需要的。然后我们检查手机的蓝牙是否打开,如果没有,通过enable()方法打开。接着我们再设置手机蓝牙设备的可见,可见时间可以自定义。
完成这些必要的设置后,我们就可以正式开始与蓝牙模块进行通信了:
public class ComminuteActivity extends Activity {
private BluetoothReceiver receiver;
private BluetoothAdapter bluetoothAdapter;
private List《String》 devices;
private List《BluetoothDevice》 deviceList;
private Bluetooth client;
private final String lockName = "BOLUTEK";
private String message = "000001";
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
listView = (ListView) this.findViewById(R.id.list);
deviceList = new ArrayList《BluetoothDevice》();
devices = new ArrayList《String》();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BluetoothReceiver();
registerReceiver(receiver, filter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView《?》 parent, View view, int position, long id) {
setContentView(R.layout.connect_layout);
BluetoothDevice device = deviceList.get(position);
client = new Bluetooth(device, handler);
try {
client.connect(message);
} catch (Exception e) {
Log.e("TAG", e.toString());
}
}
});
}
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Bluetooth.CONNECT_FAILED:
Toast.makeText(ComminuteActivity.this, "连接失败", Toast.LENGTH_LONG).show();
try {
client.connect(message);
} catch (Exception e) {
Log.e("TAG", e.toString());
}
break;
case Bluetooth.CONNECT_SUCCESS:
Toast.makeText(ComminuteActivity.this, "连接成功", Toast.LENGTH_LONG).show();
break;
case Bluetooth.READ_FAILED:
Toast.makeText(ComminuteActivity.this, "读取失败", Toast.LENGTH_LONG).show();
break;
case Bluetooth.WRITE_FAILED:
Toast.makeText(ComminuteActivity.this, "写入失败", Toast.LENGTH_LONG).show();
break;
case Bluetooth.DATA:
Toast.makeText(ComminuteActivity.this, msg.arg1 + "", Toast.LENGTH_LONG).show();
break;
}
}
};
private class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (isLock(device)) {
devices.add(device.getName());
}
deviceList.add(device);
}
showDevices();
}
}
private boolean isLock(BluetoothDevice device) {
boolean isLockName = (device.getName()).equals(lockName);
boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
return isLockName && isSingleDevice;
}
private void showDevices() {
ArrayAdapter《String》 adapter = new ArrayAdapter《String》(this, android.R.layout.simple_list_item_1,
devices);
listView.setAdapter(adapter);
}
}
如何使用android原生BLE蓝牙进行操作
之前的涉及的物联网项目中使用的: BLE 低功耗蓝牙(蓝牙4.0), 支持android 4.3以上的手机
主从关系: BLE低功耗蓝牙只能做从端设备 ,一个蓝牙主端设备,可同时与7个蓝牙从端设备进行通讯
1)低功耗
低功耗的原理:
1\低功耗蓝牙仅使用了3个广播通道,传统蓝牙技术采用 16~32 个频道
2\每次广播开启时间也由传统的 22.5ms 减少到 0.6~1.2ms(毫秒)
2)传输距离极大提高
传统蓝牙传输距离为 2~10m,而蓝牙4.0的有效传输距离可达到 60~100m
3)安全性
使用AES-128 CCM加密算法进行数据包加密和认证。
更多BLE蓝牙的解析参考博客 : BLE4.0教程一 蓝牙协议连接过程与广播分析
添加权限
打开蓝牙
1.先拿到BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
2.再拿到BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
判断是否打开蓝牙
未打开弹出 系统弹框 ,除了 魅族手机 是打开系统设置
设备/手机都是蓝牙信号
在回调方法中:
一般在扫描的过程中,我们还会设置 设备过滤原则 (因为我只想要搜索到我们想要的设备,忽略无关设备)
如:从 scanRecord -- beacon -- beacon.type == 0xFF代表Manufacture,通过与嵌入式软件定义 自己的 Manufacture值即可
用BluetoothDevice得到BluetoothGatt:
断连:
关键问题:连接后一般要做什么事?
( 必须在刚连接成功后2秒内app写一个值给设备,否则会被设备断开连接)
主要是读写 characteristic
gatt.wirteCharacteristic(mCurrentcharacteristic);
gatt.readCharacteristic(characteristic);
bluetoothGatt.setCharacteristicNotification(data, true);
真实工作中使用的蓝牙库BlueToothKit请参考我的另一篇博客:
android蓝牙入门知识和优秀蓝牙第三方库BluetoothKit的使用

本文相关文章:
小程序商城定制开发(做一个微信小程序商城开发大概多少钱(多少费用))
2026年10月12日 23:20
昆明小程序定制开发(云南昆明小程序定制怎么样我怕我自己的小程序功能实现不了!)
2026年9月17日 09:20
更多文章:
备案域名购买平台(如何在阿里云域名交易平台低价购买各种廉价已备案域名)
2026年11月3日 18:30







