下面代码也许有助你使用cordova的NFC插件功能,自己理解吧,哦,说一下,这是前端Html JavaScript方法,非java 插件
前提:配置cordova的插件方法,还不会就自己度娘。
HTML页面上有个 id='state' 文本框或者label,显示NFC状态。
关键代码在initNFC 之后,前面都是生成代码。
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
function failure(reason) {
console.log("启动错误");
$("#state").text("启动错误" + reason);
}
console.log("启动成功");
//按钮事件
document.addEventListener("backbutton", eventBackButton, false); //返回键
document.addEventListener("menubutton", eventMenuButton, false); //菜单键
document.addEventListener("searchbutton", eventSearchButton, false); //搜索键
initNFC();
},
};
//返回键
function eventBackButton() {
window.location.href = "indexList.html";
}
//菜单键
function eventMenuButton() {
//window.plugins.ToastPlugin.show_short('点击了 菜单 按钮!');
}
//搜索键
function eventSearchButton() {
//window.plugins.ToastPlugin.show_short('点击了 搜索 按钮!');
}
function initNFC() {
console.log("NFC初始化");
if (typeof(nfc) == "undefined") {
$("#state").text("您的机器没有NFC功能,或者NFC功能没有打开");
} else {
//旧系统使用监听
nfc.addTagDiscoveredListener(nfccallback, nfconSuccesscallback, nfcerrorcallback);
//新系统使用监听
nfc.addNdefFormatableListener(nfccallback, nfconSuccesscallback, nfcerrorcallback);
}
}
function nfccallback(nfcEvent) {
$("#state").text("NFC已经读取");
var tag = nfcEvent.tag,
o_rfid = nfc.bytesToHexString(tag.id),
rfid = o_rfid.toUpperCase();
checkform(rfid);
//$("#state").text('rfid=' + rfid);
};
function nfconSuccesscallback() { // error callback
$("#state").text("NFC已经打开");
};
function nfcerrorcallback(error) { // error callback
$("#state").text("NFC功能错误!" + error);
};
function checkform(ID) {
//读卡和校验
}
app.initialize();