本篇将介绍微信小程序初始化蓝牙模块的相关代码
一、首先页面要引用 蓝牙调用公共方法 Bluetooth.js
index.js 文件顶部加上如下代码:
import Bluetooth from '../../utils/Bluetooth.js'
二、data 里面定义两个参数:isBluetoothAdapterInit : false, //是否初始化蓝牙模块
isBluetoothAdapterState: false, //手机蓝牙状态 是否开启
三、onload 中自定义蓝牙状态改变事件代码
let that = this;
//蓝牙状态改变回调事件
Bluetooth.onBluetoothAdapterStateChangeCallback = function(res){
console.log('手机蓝牙状态', res)
that.setData({
isBluetoothAdapterState:res.available
});
};
四、onShow 中实现初始化蓝牙模块
let that=this;
//初始化蓝牙
Bluetooth.openBluetoothAdapter().then(
function(res) {
if(res)
{
that.setData({
isBluetoothAdapterInit:true,
isBluetoothAdapterState:true
});
Bluetooth.CheckSystemInfo().then(res=>{
if(res)
{
}
});
}
//监听蓝牙状态改变事件
Bluetooth.onBluetoothAdapterStateChange();
},
function(err) {
console.log(err);
//当前蓝牙适配器不可用
if(err.errCode=='10001')
{
that.setData({
isBluetoothAdapterInit:true,
isBluetoothAdapterState:false
});
//监听蓝牙状态改变事件
Bluetooth.onBluetoothAdapterStateChange();
Bluetooth.CheckSystemInfo().then(res=>{
if(res)
{
}
});
}
else
{
that.setData({
isBluetoothAdapterInit:false,
isBluetoothAdapterState:false
});
}
}
);
五、页面及样式代码
<!--index.wxml-->
<navigation-bar title="蓝牙连接" back="{{false}}" color="black" background="#FFF"></navigation-bar>
<scroll-view type="list" class="scroll_view" scroll-y="true">
<view class="content" list-item>
<text class="status">蓝牙适配器状态:{{ isBluetoothAdapterState?'可用':'不可用' }}</text>
</view>
</scroll-view>
/**index.wxss**/
page {
color: #333;
background-color: #f7f7f7;
display: flex;
flex-direction: column;
}
.scroll_view {
display: flex;
flex-direction: column;
flex: 1;
width: 100%;
overflow: auto;
}
.content{
display: flex;
flex-flow: nowrap;
justify-content: center;
padding-top: 10rpx;
padding-bottom: 10rpx;
}
注意:小程序页面初次打开会有 小程序使用蓝牙的弹窗,一般都选择允许,如果选择拒绝的话,我可以找到小程序右上方三个点——设置——蓝牙(选择使用小程序时允许)。我的程序可以不用设置,在onshow里面有判断会有弹窗提示直接去开启小程序的蓝牙使用权限。
下一篇 将继续介绍 微信小程序搜索蓝牙设备。