本章节主要介绍微信硬件jsapi连接设备接口disconnectWXDevice,咱们还是首先看看微信官方文档关于此接口的介绍,如下图所示
根据官方文档说明,调用此接口的入参为:
deviceId(必填):设备id
connType:要连接的设备类型,值为blue或者lan或者为空。如果为空,默认为blue。
blue表示蓝牙设备,
lan表示局域网设备
咱们首先看看第一个参数,deviceId(必填):设备id,关于设备ID的获取,请参考getWXDeviceInfos(获取设备信息)接口,这篇博文,在这里不在累述。
第二个参数为设备类型,本案例基于蓝牙,所以我们这里传入的值为blue。
下面呢,我再次晒出整体实现此功能的代码流程。本代码基于springMVC框架内
一)springMVC controller方法
/****
www.vxzsk.com原创
****/
@RequestMapping
(value=
"/wxlanya"
)
public
ModelAndView wxJsSdkConfig(HttpServletRequest request,HttpServletResponse response){
String url=
null
;
if
(StringUtils.isNotEmpty(request.getQueryString())){
url = request.getRequestURL()+
"?"
+request.getQueryString();
}
else
{
url = request.getRequestURL()+
""
;
}
System.out.println(
"请求地址"
+url);
//1,获取access_token
AccessToken accessToken = WeixinUtil.getAccessToken(AppConst.APP_ID, AppConst.APPSECRET);
String access_token=accessToken.getToken();
String ticket = WeixinUtil.getJsapiTicket(access_token);
Map<String,String> map = WeixinUtil.sign(ticket, url);
request.setAttribute(
"timestamp"
, map.get(
"timestamp"
));
request.setAttribute(
"nonceStr"
, map.get(
"nonceStr"
));
request.setAttribute(
"signature"
, map.get(
"signature"
));
request.setAttribute(
"appId"
, AppConst.APP_ID);
return
new
ModelAndView(
"/weixin/nfc/wxlanya"
);
}
1,变量jsapiTicket的获取请参考https://www.vxzsk.com/298.html
2,access_token的获取方法请参考https://www.vxzsk.com/28.html
3,WeixinUtil中的sign方法如下:
/***
* 获取界面调用jsapi的所需参数
* @param jsapi_ticket 凭据
* @param url 界面请求地址
* @return V型知识库 www.vxzsk.com
*/
public
static
Map<String, String> sign(String jsapi_ticket, String url) {
Map<String, String> ret =
new
HashMap<String, String>();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature =
""
;
//注意这里参数名必须全部小写,且必须有序
string1 =
"jsapi_ticket="
+ jsapi_ticket +
"&noncestr="
+ nonce_str +
"×tamp="
+ timestamp +
"&url="
+ url;
System.out.println(string1);
try
{
MessageDigest crypt = MessageDigest.getInstance(
"SHA-1"
);
crypt.reset();
crypt.update(string1.getBytes(
"UTF-8"
));
signature = byteToHex(crypt.digest());
}
catch
(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch
(UnsupportedEncodingException e)
{
e.printStackTrace();
}
ret.put(
"url"
, url);
ret.put(
"jsapi_ticket"
, jsapi_ticket);
ret.put(
"nonceStr"
, nonce_str);
ret.put(
"timestamp"
, timestamp);
ret.put(
"signature"
, signature);
return
ret;
}
private
static
String byteToHex(
final
byte
[] hash) {
Formatter formatter =
new
Formatter();
for
(
byte
b : hash)
{
formatter.format(
"%02x"
, b);
}
String result = formatter.toString();
formatter.close();
return
result;
}
private
static
String create_nonce_str() {
return
UUID.randomUUID().toString();
}
private
static
String create_timestamp() {
return
Long.toString(System.currentTimeMillis() /
1000
);
}
4, AppConst.APP_ID,AppConst.APPSECRET的值其实是一个固定值,替换为自己公众号中的appid即可。
二)新建wxlanya.jsp页面
在controller中返回界面为wxlanya.jsp 其实本界面就是H5界面,界面中有两个按钮,一个是获取设备ID按钮,另一个是断开设备连接按钮 点击获取设备按钮会触发下面js代码
2.1 获取设备ID按钮
//点击获取设备按钮的函数 开始 V型知识库 www.vxzsk.com $("#CallGetWXrefresh").on("click",function(e){ //1. 打开微信设备 my_openWXDeviceLib(); //2. 获取设备信息 my_getWXDeviceInfos(); }); //点击获取设备按钮的函数 结束
一共触发了两个方法,my_openWXDeviceLib()和my_getWXDeviceInfos(),他们实现的代码分别为:
my_getWXDeviceInfos()
/********************************************************* * 打开微信设备 * 作者:vxzsk.com V型知识库 * my_openWXDeviceLib * 入口参数:无 * 出口参数:0表示打开成功;1表示打开失败 *********************************************************/ 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表示失败 }
my_getWXDeviceInfos()
/********************************************** * 取得微信设备信息 * 作者:V型知识库 www.vxzsk.com * my_getWXDeviceInfos * 入口参数:无 * 出口参数:返回一个已经链接的设备的ID **********************************************/ 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") { alert(C_DEVICEID); C_DEVICEID = res.deviceInfos[i].deviceId; $("#lbInfo").html("2.设备已成功连接"); $("#lbInfo").css({color:"green"}); break; } } }); return; }
2.2 断开设备连接按钮,实现disconnectWXDevice接口
/*** author V型知识库 www.vxzsk.com 断开设备连接 ****/ function disconnectWXDevice(){ WeixinJSBridge.invoke('disconnectWXDevice', {'deviceId':C_DEVICEID, 'connType':'blue'}, function(res) { mlog("断开设备连接返回:"+res.err_msg); }); }
参数C_DEVICEID在获取设备ID方法中获得,connType设置为blue(蓝牙设备)
三)测试
打开蓝牙设备,连接上微信,操作断开设备按钮,效果如下
四)完整jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; session.setAttribute("basePath",basePath); %> <!DOCTYPE html> <html class="ie"><!--<![endif]--> <head> <meta charset="utf-8"> <title>微信蓝牙设备-V型知识库www.vxzsk.com</title> <meta name="viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <link rel="stylesheet" href="<%=basePath %>/resource/device/weui.min.css?what=0"> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"> </script> </head> <body ontouchstart> <!--标题行--> <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;">当前设备: </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;">状态信息: </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">获取设备ID</button><br> <!-- <button class="weui_btn weui_btn weui_btn_warn" id="stopScanWXDevice">停止扫描设备</button><br> --> <!-- <button class="weui_btn weui_btn weui_btn_warn" onclick="connectWXDevice()">连接设备</button><br> --> <button class="weui_btn weui_btn weui_btn_warn" onclick="disconnectWXDevice()">断开设备连接</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> </body> <script type="text/javascript"> var C_DEVICEID=null; jQuery(document).ready(function(){ //初始化库 loadXMLDoc(); //初始化库结束 //点击获取设备按钮的函数 开始 $("#CallGetWXrefresh").on("click",function(e){ //1. 打开微信设备 my_openWXDeviceLib(); //2. 获取设备信息 my_getWXDeviceInfos(); //2. 扫描设备 //my_startScanWXDevice(); }); //点击获取设备按钮的函数 结束 jQuery("#stopScanWXDevice").click(function(){ //3. 停止扫描设备 my_stopScanWXDevice(); }); }); //初始化 微信硬件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("初始化库结束"); } //判断调用jsapi返回状态 true表示成功 wx.error(function (res) { alert("调用微信jsapi返回的状态:"+res.errMsg); }); /******************************分割线************************************************/ /********************************************************* * 打开微信设备 * 作者:vxzsk.com 2016-04-04 * my_openWXDeviceLib * 入口参数:无 * 出口参数:0表示打开成功;1表示打开失败 *********************************************************/ 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表示失败 } /********************************************** * 扫描设备 * 作者:2017-02-14 * my_getWXDeviceInfos * 入口参数:无 * 出口参数:返回一个已经链接的设备的ID **********************************************/ function my_startScanWXDevice(){ WeixinJSBridge.invoke('startScanWXDevice', {}, function(res){ mlog("扫描设备返回:"+res.err_msg); }); return; } /*** 停止扫描设备 ****/ function my_stopScanWXDevice(){ WeixinJSBridge.invoke('stopScanWXDevice', {}, function(res){ mlog("停止扫描设备返回:"+res.err_msg); }); return; } /********************************************** * 取得微信设备信息 * 作者:V型知识库 www.vxzsk.com * my_getWXDeviceInfos * 入口参数:无 * 出口参数:返回一个已经链接的设备的ID **********************************************/ 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") { alert(C_DEVICEID); C_DEVICEID = res.deviceInfos[i].deviceId; $("#lbInfo").html("2.设备已成功连接"); $("#lbInfo").css({color:"green"}); break; } } }); return; } /*** author V型知识库 www.vxzsk.com 连接设备 ****/ function connectWXDevice(){ WeixinJSBridge.invoke('connectWXDevice', {'deviceId':C_DEVICEID, 'connType':'blue'}, function(res) { mlog("连接设备返回:"+res.err_msg); }); } /*** author V型知识库 www.vxzsk.com 断开设备连接 ****/ function disconnectWXDevice(){ WeixinJSBridge.invoke('disconnectWXDevice', {'deviceId':C_DEVICEID, 'connType':'blue'}, function(res) { mlog("断开设备连接返回:"+res.err_msg); }); } //打印日志 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(); }); } </script> </html>
感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程