NfcMifare Android NFC与Mifare Classic卡读写实现
在Android平台上,NFC(近场通信)技术允许设备间进行短距离的数据交换,而Mifare Classic是一种广泛应用的RFID(无线频率识别)卡片,常用于门禁、公交卡等场景。本项目NfcMifare正是针对这种卡片进行读写操作的实现,主要使用Java语言编写。以下将详细介绍如何使用Android NFC API与Mifare Classic卡进行交互,并探讨相关技术点。
要进行NFC读写操作,我们需要在AndroidManifest.xml文件中声明相应的权限:
<uses-permission android:name='\"android.permission.NFC\"'>uses-permission>
<uses-feature android:name='\"android.hardware.nfc.hce\"' android:required='\"false\"'>uses-feature>
同时,为了在活动中监听NFC事件,我们需要在活动的onCreate()
方法中注册一个NFC的意图过滤器:
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[] { filter }, null);
当用户将Mifare Classic卡靠近设备时,系统会通过ACTION_TAG_DISCOVERED
触发我们的活动。此时,我们可以通过NfcAdapter获取到Tag对象,进一步识别出Mifare Classic卡:
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
MifareClassic mifareCard = MifareClassic.get(tag);
Mifare Classic卡有多种类型(如1K、4K),分为多个扇区(通常16个)和每个扇区下的4块(16个字节)。在进行读写操作前,需要先建立连接:
mifareCard.connect();
然后可以进行读扇区、写扇区的操作。例如,读取第0扇区的键A(Key A):
byte[] key = { (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78, (byte)0x90, (byte)0xAB };
byte[] sectorData = new byte[16];
try {
mifareCard.authenticateSectorWithKeyA(0, key);
mifareCard.readBlock(0 * 4, sectorData);
} catch (IOException e) {
e.printStackTrace();
}
同样,写扇区也需要先验证键,然后使用writeBlock()
方法:
try {
mifareCard.authenticateSectorWithKeyA(0, key);
byte[] dataToWrite = { ... }; //新的数据
mifareCard.writeBlock(0 * 4, dataToWrite);
} catch (IOException e) {
e.printStackTrace();
}
注意,写入数据时需要确保符合Mifare Classic的格式要求,如字节顺序、数据类型等。在完成读写操作后,记得关闭连接以释放资源:
mifareCard.close();
下载地址
用户评论