cordova NFC讀卡(javascript)
阿新 • • 發佈:2019-01-03
下面程式碼也許有助你使用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();