欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

Android NFC开发MifareClassic读写Demo实例下载

程序员文章站 2022-03-01 13:52:38
...

本例子是一个NFC读卡信息的例子源码、NFC技术由非接触式射频识别(RFID)演变而来、由飞利浦半导体(现恩智浦半导体)、诺基亚和索尼共同研制开发、其基础是RFID及互连技术、近场通信(Near Field Communication,NFC)是一种短距高频的无线电技术、在13.56MHz频率运行于20厘米距离内、其传输速度有106 Kbit/秒、212 Kbit/秒或者424 Kbit/秒三种、目前近场通信已通过成为ISO/IEC IS 18092国际标准、ECMA-340标准与ETSI TS 102 190标准、NFC采用主动和被动两种读取模

本项目默认编码GBK编译版本4.4.2、运行需要有NFC硬件支持、最近一直在研究Android NFC相关的技术、发现有两种数据格式、MifareClassic和MifareUltralight两种、不巧的是公司用的是MifareUltralight、一直没有研究出来、Android官方的文档也看过、跟文档来也没有弄出来、还是研究当中、这里先分享已经研究出来的成果、MifareClassic数据格式

Android NFC开发MifareClassic读写Demo实例下载


AndroidManifest.xml 代码

<intent-filter>  
	<action android:name="android.nfc.action.TECH_DISCOVERED" />  
</intent-filter>  
<meta-data  
	android:name="android.nfc.action.TECH_DISCOVERED"  
	android:resource="@xml/nfc_tech_filter" />  


nfc_tech_filter.xml 代码

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
       <tech>android.nfc.tech.MifareClassic</tech>
    </tech-list>
</resources>


核心代码

private void processIntent(Intent intent) {  
	//取出封装在intent中的TAG  
	Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
	for (String tech : tagFromIntent.getTechList()) {  
	  //  System.out.println(tech);  
	}  
	boolean auth = false;  
	//读取TAG  
	MifareClassic mfc = MifareClassic.get(tagFromIntent);  
	try {  
		String metaInfo = "";  
		//Enable I/O operations to the tag from this TagTechnology object.  
		mfc.connect();  
		int type = mfc.getType();//获取TAG的类型  
		int sectorCount = mfc.getSectorCount();//获取TAG中包含的扇区数  
		String 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  = "卡片类型:"   typeS   "共"   sectorCount 
			  "个扇区共"   mfc.getBlockCount() 
			  "个块存储空间: "   mfc.getSize()   "B";  
		for (int j = 0; j < sectorCount; j  ) {  
			//Authenticate a sector with key A.  
			auth = mfc.authenticateSectorWithKeyA(j, a);
			int bCount;  
			int bIndex;  
			if (auth) {  
				metaInfo  = "Sector "   j   ":验证成功";  
				// 读取扇区中的块  
				bCount = mfc.getBlockCountInSector(j);  
				bIndex = mfc.sectorToBlock(j);  
				for (int i = 0; i < bCount; i  ) {  
					byte[] data = mfc.readBlock(bIndex);  
					metaInfo  = "Block "   bIndex   " : "  
							  bytesToHexString(data)   "";  
					bIndex  ;  
				}  
			} else {  
				metaInfo  = "Sector "   j   ":验证失败";  
			}  
		}  
		promt.setText(metaInfo);  
	} catch (Exception e) {  
		e.printStackTrace();  
	}  
}  


话不多说、直接上源代码、源代码里面只有一个类、非常容易看懂的、另外如果有哥们研究出来了MifareUltralight、还希望一起分享一下

源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1pJOJ075 密码: 2zjg