下面代碼也許有助你使用cordova的NFC外掛程式功能,自己理解吧,哦,說一下,這是前端Html JavaScript方法,非java 外掛程式
前提:配置cordova的外掛程式方法,還不會就自己度娘。
HTML頁面上有個 id='state' 文字框或者label,顯示NFC狀態。
關鍵代碼在initNFC 之後,前面都是產生代碼。
var app = {// Application Constructorinitialize: 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();