NFC(Near Field Communication,近场通信)卡贴通常用于存储简短的信息,如文本、联系方式或URL等,并通过NFC功能快速读取。要编写一个程序来操作NFC卡贴,你需要了解如何使用NFC API,并且可能需要使用特定的开发工具或库。以下是一些基本步骤和代码示例,用于在Android设备上使用NFC功能将数据写入NFC标签。
准备工作
确保设备支持NFC:
进入手机的系统设置,找到并启用NFC功能。
获取NFC权限:
在AndroidManifest.xml文件中添加NFC权限。
```xml
```
创建NFC适配器:
在Activity中获取NFC适配器实例。
```java
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
```
处理NFC事件:
设置一个IntentFilter来监听NFC标签的接近事件。
```java
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException(e);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
```
写入数据到NFC标签
连接到NFC标签:
使用MifareClassic类连接到NFC标签。
```java
MifareClassic mfc = MifareClassic.get(tag);
try {
mfc.connect();
boolean auth = mfc.authenticateSectorWithKeyA(sectorAddress, MifareClassic.KEY_DEFAULT);
if (auth) {
// 授权成功,可以进行数据写入
}
} catch (IOException e) {
e.printStackTrace();
}
```
写入数据:
将数据写入NFC标签的指定扇区。
```java
byte[] data = "Hello, NFC!".getBytes();
int sectorIndex = 0;
int blockIndex = 0;
mfc.writeBlock(sectorIndex, blockIndex, data);
```
读取NFC标签上的数据
读取数据:
使用MifareClassic类读取NFC标签上的数据。
```java
byte[] readData = mfc.readBlock(sectorIndex, blockIndex);
String text = new String(readData);
```
示例代码