微信监听蓝牙设备连接状态变化接口onWXDeviceStateChange(第10篇)

2017年08月25日 15:12 | 9011次浏览 作者原创 版权保护

完整微信硬件接入案例源码:点我下载案例源码

我们在开发微信硬件蓝牙设备的时候,对于监听蓝牙设备连接状态是有必要的,因为我们无法预测到用户在用蓝牙设备的时候是处于怎么样的环境状态下,必须时时刻刻监听手机微信和蓝牙设备之间的连接状态,以便我们在数据交互的时候提醒用户注意蓝牙连接,否则数据交互会因为蓝牙断开导致中断。

首先看微信硬件jsapi接口介绍

其实微信的官方文档说的不是很清楚,这里的参数并不是入参,而是调用这个接口后返回的参数。微信到处给挖坑。

第一、新建jsp界面,引入微信硬件js库和jquery库,weui库

<script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"> </script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>

weui.min.css文件请网友自行百度下载,之所以在这里提微信的weui库是因为使得界面看起来美观一些

第二,<body></body>之间的html代码

<!--标题行-->
<h2 style="color: white;background-color: green;text-align: center;background-position: center;">蓝牙设备</h2>
  

<div class="page">
    <div class="bd spacing">
        <div class="weui_cells weui_cells_form">
             	
            <div class="weui_cell">
                <div class="weui_cell_hd"><label class="weui_label" style="width: auto;">当前设备:&nbsp</label></div>
                <div class="weui_cell_bd weui_cell_primary">
                   <label id="lbdeviceid" class="weui_label" style="width: auto;"></label>
                </div>
            </div>
            <div class="weui_cell">
                <div class="weui_cell_hd"><label class="weui_label" style="width: auto;">状态信息:&nbsp</label></div>
                <div class="weui_cell_bd weui_cell_primary">
                    <label id="lbInfo" class="weui_label" style="width: auto;"></label>
                </div>
            </div> 
            <div class="weui_cell" >
            	<div class="weui_cell_hd"><label class="weui_label">日志:  </label></div>
                <div class="weui_cell_bd weui_cell_primary">
                    <textarea id="logtext" class="weui_textarea" placeholder="日志" rows="5"></textarea>
                </div>
            </div>
            
          
            
        </div>
        
      
      
        <div class="weui_btn_area weui">
	        
            <button class="weui_btn weui_btn weui_btn_warn" id="CallGetWXrefresh">获取设备</button><br>
            
            
        </div>
       
        
    </div>
    
    
    <div class="weui_dialog_alert" id="Mydialog" style="display: none;">
    <div class="weui_mask"></div>
    <div class="weui_dialog">
        <div class="weui_dialog_hd" id="dialogTitle"><strong class="weui_dialog_title">着急啦</strong></div>
        <div class="weui_dialog_bd" id="dialogContent">亲,使用本功能,请先打开手机蓝牙!</div>
        <div class="weui_dialog_ft">
            <a href="#" class="weui_btn_dialog primary">确定</a>
        </div>
    </div>
    </div>
    
    
    <!--BEGIN toast-->
    <div id="toast" style="display: none;">
        <div class="weui_mask_transparent"></div>
        <div class="weui_toast">
            <i class="weui_icon_toast"></i>
            <p class="weui_toast_content" id="toast_msg">已完成</p>
        </div>
    </div>
    <!--end toast-->

    <!-- loading toast -->
    <div id="loadingToast" class="weui_loading_toast" style="display:none;">
        <div class="weui_mask_transparent"></div>
        <div class="weui_toast">
            <div class="weui_loading">
                <div class="weui_loading_leaf weui_loading_leaf_0"></div>
                <div class="weui_loading_leaf weui_loading_leaf_1"></div>
                <div class="weui_loading_leaf weui_loading_leaf_2"></div>
                <div class="weui_loading_leaf weui_loading_leaf_3"></div>
                <div class="weui_loading_leaf weui_loading_leaf_4"></div>
                <div class="weui_loading_leaf weui_loading_leaf_5"></div>
                <div class="weui_loading_leaf weui_loading_leaf_6"></div>
                <div class="weui_loading_leaf weui_loading_leaf_7"></div>
                <div class="weui_loading_leaf weui_loading_leaf_8"></div>
                <div class="weui_loading_leaf weui_loading_leaf_9"></div>
                <div class="weui_loading_leaf weui_loading_leaf_10"></div>
                <div class="weui_loading_leaf weui_loading_leaf_11"></div>
            </div>
            <p class="weui_toast_content" id="loading_toast_msg">数据加载中</p>
        </div>
    </div>
    <!-- End loading toast -->
    
    <!--BEGIN dialog1-->
    <div class="weui_dialog_confirm" id="dialog1" style="display: none;">
        <div class="weui_mask"></div>
        <div class="weui_dialog">
            <div class="weui_dialog_hd"><strong class="weui_dialog_title">弹窗标题</strong></div>
            <div class="weui_dialog_bd">自定义弹窗内容,居左对齐显示,告知需要确认的信息等</div>
            <div class="weui_dialog_ft">
                <a href="javascript:;" class="weui_btn_dialog default" id="qxBtn">取消</a>
                <a href="javascript:;" class="weui_btn_dialog primary" id="okBtn">确定</a>
            </div>
        </div>
    </div>
    <!--END dialog1-->
    <!--BEGIN dialog2-->
    <div class="weui_dialog_alert" id="dialog2" style="display: none;">
        <div class="weui_mask"></div>
        <div class="weui_dialog">
            <div class="weui_dialog_hd"><strong class="weui_dialog_title">弹窗标题</strong></div>
            <div class="weui_dialog_bd">弹窗内容,告知当前页面信息等</div>
            <div class="weui_dialog_ft">
                <a href="javascript:;" class="weui_btn_dialog primary">确定</a>
            </div>
        </div>
    </div>
    <!--END dialog2-->
</div>

<div id="myparams" style="display: none">
 <span id="timestamp">${timestamp }</span>
 <span id="nonceStr">${nonceStr }</span>
 <span id="signature">${signature }</span>
 <span id="appId">${appId }</span>
</div>

上述最后四行html代码是调用微信硬件jsapi的四个参数凭证,具体如何初始化四个参数,请参考https://www.vxzsk.com/79.html 

第三、javascript代码编写

jQuery(document).ready(function(){
  //初始化库	
 loadXMLDoc();
 //初始化库结束
 
 $("#CallGetWXrefresh").on("click",function(e){  
    //showdialog();
    
     //1. 打开微信设备 
     my_openWXDeviceLib();
     
     //2. 安装设备事件
     my_installwxEvents();
     
     //2.1安装状态改变事件 
      my_onWXDeviceStateChange(); 
    //3. 安装接收到数据事件 
     my_onReceiveDataFromWXDevice();
     
    //4. 刷新设备信息
     my_getWXDeviceInfos();
     
   });
  });

1):首先是loadXMLDoc();方法,首先必须初始化微信硬件jsapi库,库里面包含了各种调用微信硬件jsapi接口方法。而初始化这个库需要四个参数,分别为appId,timestamp,nonceStr,signature,其中appid是我们的应用id,其它三个参数是在我们点击微信菜单请求java方法生成的,此方法跳转到jsp界面。

loadXMLDoc()方法如下:

//微信硬件jsapi库
function loadXMLDoc()
{
	var appId =jQuery("#appId").text();
	var timestamp=jQuery("#timestamp").text();
	var nonceStr =jQuery("#nonceStr").text();
	var signature=jQuery("#signature").text();
	wx.config({
		 	  beta: true,
		      debug: true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
		      appId: appId, 
		      timestamp: timestamp,
		      nonceStr: nonceStr,
		      signature: signature,
		      jsApiList: [
		        'openWXDeviceLib',
		        'closeWXDeviceLib',
		        'getWXDeviceInfos',
		        'getWXDeviceBindTicket',
		        'getWXDeviceUnbindTicket',
		        'startScanWXDevice',
		        'stopScanWXDevice',
		        'connectWXDevice',
		        'disconnectWXDevice',
		        'sendDataToWXDevice',
		        'onWXDeviceBindStateChange',
		        'onWXDeviceStateChange',
		        'onScanWXDeviceResult',
		        'onReceiveDataFromWXDevice',
		        'onWXDeviceBluetoothStateChange',
		      ]
		  });
             alert("初始化库结束");
}

2):my_openWXDeviceLib()方法打开微信设备,此方法用来判断手机蓝牙或者设备蓝牙是否打开

function my_openWXDeviceLib(){
   var x=0; 
   WeixinJSBridge.invoke('openWXDeviceLib', {}, 
   function(res){
	   mlog("打开设备返回:"+res.err_msg);
      if(res.err_msg=='openWXDeviceLib:ok')
        {
          if(res.bluetoothState=='off')
            {    
              showdialog("太着急啦","亲,使用前请先打开手机蓝牙!");  
              $("#lbInfo").innerHTML="1.请打开手机蓝牙";
              $("#lbInfo").css({color:"red"});
              x=1;
              isOver();
            };
          if(res.bluetoothState=='unauthorized')
            {
              showdialog("出错啦","亲,请授权微信蓝牙功能并打开蓝牙!");    
              $("#lbInfo").html("1.请授权蓝牙功能");
              $("#lbInfo").css({color:"red"});
              x=1;
              isOver();
            }; 
          if(res.bluetoothState=='on')
            {
        	  //showdialog("太着急啦","亲,请查看您的设备是否打开!");   
              $("#lbInfo").html("1.蓝牙已打开,未找到设备");
              $("#lbInfo").css({color:"red"});
              //$("#lbInfo").attr(("style", "background-color:#000");
              x=0;
              //isOver();
            };      
        }
      else
        {
          $("#lbInfo").html("1.微信蓝牙打开失败");
          x=1; 
          showdialog("微信蓝牙状态","亲,请授权微信蓝牙功能并打开蓝牙!");   
        }
    });
   return x;  //0表示成功 1表示失败
}

3):my_installwxEvents();安装设备事件

/**V型知识库 www.vxzsk.com****/
function my_installwxEvents(){
   //1. 安装微信绑定事件
   WeixinJSBridge.on('onWXDeviceBindStateChange', function(argv) {
       //todo
		}); 
   //2. 扫描到某个设备      
   WeixinJSBridge.on('onScanWXDeviceResult', function(argv) {
        //todo
	    });
   //3. 手机蓝牙状态改变事件    
   WeixinJSBridge.on('onWXDeviceBluetoothStateChange', function(argv) {
	    //todo
        });         
 }

4):my_onWXDeviceStateChange()监听设备状态变化

var C_DEVICEID=null;
function my_onWXDeviceStateChange(){
    
    WeixinJSBridge.on('onWXDeviceStateChange', 
    function(argv) 
     {
        
        var deviceStatus=argv.state;
        
        if(deviceStatus==="connected")
          { 
			//$("#lbdeviceid").html(res.deviceInfos[i].deviceId); 
            C_DEVICEID = res.deviceInfos[i].deviceId;
            $("#lbInfo").html("x.蓝牙设备已连接");	  
            //$("#BLEState").val("connected");
          }
        if(deviceStatus==="connecting")
          {
            //$("#lbdeviceid").html(res.deviceInfos[i].deviceId); 
            C_DEVICEID = res.deviceInfos[i].deviceId;
            $("#lbInfo").html("x.蓝牙设备正连接...");
            //$("#BLEState").val("connecting");	
          }
        if(deviceStatus==="disconnected")
          {
           // $("#lbdeviceid").html(''); 
            C_DEVICEID = "";
            $("#lbInfo").html("x.蓝牙设备已断开");	
            
            
          }	  			
	  });
 }

5):my_getWXDeviceInfos()获取蓝牙设备信息

function my_getWXDeviceInfos(){
   
    WeixinJSBridge.invoke('getWXDeviceInfos', {}, function(res){
        var len=res.deviceInfos.length;  //绑定设备总数量
		for(i=0; i<=len-1;i++)
         {
           //alert(i + ' ' + res.deviceInfos[i].deviceId + ' ' +res.deviceInfos[i].state); 
           if(res.deviceInfos[i].state==="connected")
            {
              $("#lbdeviceid").html(res.deviceInfos[i].deviceId); 
              C_DEVICEID = res.deviceInfos[i].deviceId;
              $("#lbInfo").html("2.设备已成功连接");
              $("#lbInfo").css({color:"green"});
             
              break;   
            }  
         }
         	
    }); 
  return;    
}

第四、my_onReceiveDataFromWXDevice();接收设备返回的数据

之所以把这个函数单独列出来是因为这个函数比较重要,手机微信和蓝牙设备通信交互数据的返回都靠这个函数来接收。

function my_onReceiveDataFromWXDevice(){
	
    WeixinJSBridge.on('onReceiveDataFromWXDevice', function(argv) {
    mlog("接收的数据-->"+argv.base64Data);
		
	  });
}

第五、日志打印mlog函数 和错误提示函数showdialog

function mlog(m){
	var log=$('#logtext').val();
	//log=log+m;
    log = m;
	$('#logtext').val(log);
}
function showdialog(DialogTitle,DialogContent){
   var $dialog = $("#Mydialog");
   $dialog.find("#dialogTitle").html(DialogTitle);
   $dialog.find("#dialogContent").html(DialogContent);
   $dialog.show();
   $dialog.find(".weui_btn_dialog").one("click", function(){
        $dialog.hide();
   });
}

第六、效果图


程序运行后,连接状态为设备已连接成功,等我们把蓝牙设备断开后,发现监听设备连接状态的函数已被触发,并返回设备已断开的状态。


小说《我是全球混乱的源头》
此文章本站原创,地址 https://www.vxzsk.com/142.html   转载请注明出处!谢谢!

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程