html
<div >
<p>输入要写入的内容:</p>
<textarea id="text" />
<button onclick="writeData()">写入</button>
<button onclick="readData()">读取</button><br/>
<p>读取的内容: </p>
<div id="content"> </div>
</div>
js
var NfcAdapter;
var NdefRecord;
var NdefMessage;
function listenNFCStatus() {
try{
var main = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var Activity = plus.android.importClass('android.app.Activity');
var PendingIntent = plus.android.importClass('android.app.PendingIntent');
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
var nfcAdapter = NfcAdapter.getDefaultAdapter(main);
var intent = new Intent(main, main.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
var pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
var ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
ndef.addDataType("*/*");
var intentFiltersArray = [ndef];
var techListsArray = [
["android.nfc.tech.IsoDep"],
["android.nfc.tech.NfcA"],
["android.nfc.tech.NfcB"],
["android.nfc.tech.NfcF"],
["android.nfc.tech.Nfcf"],
["android.nfc.tech.NfcV"],
["android.nfc.tech.NdefFormatable"],
["android.nfc.tech.MifareClassi"],
["android.nfc.tech.MifareUltralight"]
];
document.addEventListener("newintent",
function() {
console.error('newintent');
setTimeout(handle_nfc_data1, 1000);
}, false);
document.addEventListener("pause", function(e) {
if (nfcAdapter) {
nfcAdapter.disableForegroundDispatch(main);
console.log('pause');
}
}, false);
document.addEventListener("resume", function(e) {
if (nfcAdapter) {
console.log('resume');
nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
}
}, false);
nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
}catch(e){
console.error(e);
}
}
function handle_nfc_data1()
{
NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
var main = plus.android.runtimeMainActivity();
var intent = main.getIntent();
console.log("action type:" + intent.getAction());
if("android.nfc.action.TECH_DISCOVERED" == intent.getAction()){
if(readyWriteData){
__write(intent);
readyWriteData = false;
}else if(readyRead){
__read(intent);
readyRead = false;
}
}
}
function showToast(msg){
plus.nativeUI.toast(msg);
}
function __write(intent){
try{
waiting.setTitle('请勿移开标签\n正在写入...');
var text = document.getElementById('text').value;
console.log("text=" + text);
var textBytes = plus.android.invoke(text,"getBytes");
// image/jpeg text/plain
var textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
plus.android.invoke("text/plain","getBytes"), plus.android.invoke("","getBytes"), textBytes);
var message = new NdefMessage([textRecord]);
var Ndef = plus.android.importClass('android.nfc.tech.Ndef');
var NdefFormatable = plus.android.importClass('android.nfc.tech.NdefFormatable');
var tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
var ndef = Ndef.get(tag);
if (ndef != null) {
var size = message.toByteArray().length;
console.log("size=" + size);
ndef.connect();
if (!ndef.isWritable()) {
showToast("tag不允许写入");
waiting.close();
return ;
}
if (ndef.getMaxSize() < size) {
showToast("文件大小超出容量");
waiting.close();
return ;
}
ndef.writeNdefMessage(message);
waiting.close();
showToast("写入数据成功.");
return ;
} else {
var format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
showToast("格式化tag并且写入message");
waiting.close();
return ;
} catch (e) {
showToast("格式化tag失败.");
waiting.close();
return ;
}
} else {
showToast("Tag不支持NDEF");
waiting.close();
return ;
}
}
}catch(e){
console.log("error=" + e);
waiting.close();
alert('写入失败');
}
}
document.addEventListener('plusready',listenNFCStatus,false);
var waiting ;
var readyWriteData = false;
var readyRead = false;
function writeData(){
var textEle = document.getElementById('text');
if(!textEle.value){
alert('请输入要写入的内容');
return;
}
readyWriteData = true;
waiting = plus.nativeUI.showWaiting("请将NFC标签靠近!");
}
function readData(){
readyRead = true;
waiting = plus.nativeUI.showWaiting("请将NFC标签靠近!");
}
function __read(intent){
handle_nfc_data(intent)
waiting.setTitle('请勿移开标签\n正在读取数据...');
var Parcelable = plus.android.importClass("android.os.Parcelable");
var rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
records = rawmsgs[0].getRecords();
var result = records[0].getPayload();
var s = plus.android.newObject("java.lang.String",result);
document.getElementById('content').textContent = s;
waiting.close();
}
function handle_nfc_data(intent) {
try {
var content = "";
//plus.nativeUI.showWaiting('正在读取数据,请勿移开卡');
var tag = plus.android.importClass("android.nfc.Tag");
var MifareClassic = plus.android.importClass('android.nfc.tech.MifareClassic')
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
var bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
//plus.nativeUI.closeWaiting();
content += "卡片字节数组ID:" + tag.getId() + "<br/>";
content += "卡片16进制ID:" + bytesToHexString(tag.getId()) + "<br/>";
var tagid = reverseTwo(bytesToHexString(tag.getId()));
content += "卡片16进制翻转ID:" + tagid + "<br/>";
content += "卡片10进制卡号:" + parseInt(tagid, 16) + "<br/>";
console.log(content)
var mfc = MifareClassic.get(tag)
var metaInfo='';
//读扇区内容
try{
mfc.connect();
var type =mfc.getType();
var sectorCount = mfc.getSectorCount();
var typeS = "";
switch (type) {
case MifareClassic.TYPE_CLASSIC:
typeS = "TYPE_CLASSIC";
break;
case MifareClassic.TYPE_PLUS:
typeS = "TYPE_PLUS";
break;
case MifareClassic.TYPE_PRO:
typeS = "TYPE_PRO";
break;
case MifareClassic.TYPE_UNKNOWN:
typeS = "TYPE_UNKNOWN";
break;
}
metaInfo += "\n卡片类型:" + typeS + "\n共" + sectorCount + "个扇区\n共"
+ mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize() + "B\n";
console.log(metaInfo)
var pass = [];
var pass = bytesFun('000000000000');
console.log(pass)
for (var j = 0; j < sectorCount; j++) {
// authenticateSectorWithKeyB
var auth = mfc.authenticateSectorWithKeyA(j,pass);//密码MifareClassic.KEY_DEFAULT 出厂默认 j为扇区 pass为扇区密码 byte格式
var bCount;
var bIndex;
if (auth) {
metaInfo += "Sector " + j + ":验证成功\n";
//读取扇区中的块
bCount = mfc.getBlockCountInSector(j);
bIndex = mfc.sectorToBlock(j);
for (var i = 0; i < bCount; i++) {
var data = mfc.readBlock(bIndex);
metaInfo += "Block " + bIndex + " : "
+ bytesToHexString(data) + "\n";
bIndex++;
}
} else {
metaInfo += "Sector " + j + ":验证失败\n";
}
}
console.log(metaInfo)
}catch(e){
console.log(e)
//TODO handle the exception
}
var cardId = parseInt(tagid, 16);
if(cardId){
}
window.localStorage.setItem('cardIdNum',cardId);
return;
} catch(e) {
console.log(e)
//TODO handle the exception
}
}
function bytesFun(str){
var ch, st, re = [];
for (var i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i);
st = [];
do {
st.push( ch & 0xFF );
ch = ch >> 8;
}
while ( ch );
re = re.concat( st.reverse() );
}
return re;
}
function handle() {
var main = plus.android.runtimeMainActivity();
var runtimeIntent = main.getIntent();
var b = runtimeIntent.getExtras();
plus.android.importClass(b);
var set = b.keySet();
plus.android.importClass(set);
var sb;
var i = set.iterator();
plus.android.importClass(i);
var hasNest = i.hasNext();
var NfcA = plus.android.importClass("android.nfc.tech.NfcA");
var IsoDep = plus.android.importClass("android.nfc.tech.IsoDep");
var Tag = plus.android.importClass("android.nfc.Tag");
while (hasNest) {
var key = i.next();
var v = b.get(key);
if (v instanceof NfcA) {
var atqa = v.getAtqa();
var sak = v.getSak();
var tag = g.getTag();
plus.android.importClass(tag);
var techList = tag.getTechList();
console.log('NfcA Atqa=' + atqa + ";Sak=" + sak + ";techList=" + techList);
} else if (v instanceof IsoDep) {
var tag = g.getTag();
plus.android.importClass(tag);
var techList = tag.getTechList();
console.log('IsoDep techList=' + techList);
} else if (v instanceof Tag) {
var tag = v;
var techList = tag.getTechList();
console.log('Tag techList=' + techList);
}
console.log(key + ';v=' + v);
sb = key + "=" + v + "\n";
hasNest = i.hasNext();
console.log('hasNest=' + hasNest);
}
}
//16进制转换
function bytesToHexString(inarray) {
var i, j, x;
var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
"B", "C", "D", "E", "F"
];
var out = "";
for(j = 0; j < inarray.length; ++j) {
x = parseInt(inarray[j]) & 0xff;
i = (x >> 4) & 0x0f;
out += hex[i];
i = x & 0x0f;
out += hex[i];
}
return out;
}
//16进制翻转
function reverseTwo(str) {
var str1 = "";
for(var i = 1; i <= str.length; i++) {
str1 += str[i - 1];
if(i % 2 == 0) {
if(i == str.length) {
break;
}
str1 += ":";
}
}
var str2 = "";
for(var i = str1.split(":").length - 1; i >= 0; i--) {
str2 += str1.split(":")[i];
}
return str2;
}