如何通过Tag获取NFC中的数据
时间: 2023-08-15 21:03:23 浏览: 81
要通过 Tag 获取 NFC 中的数据,你可以使用 Android 中的 NFC API。以下是一个简单的代码片段,可以帮助你读取 NFC 标签或卡片中的文本数据:
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.text_view);
if (NfcAdapter.getDefaultAdapter(this) == null) {
textView.setText("NFC not available on this device");
} else {
Intent intent = getIntent();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messages[i] = (NdefMessage) rawMessages[i];
}
NdefRecord record = messages[0].getRecords()[0];
String text = new String(record.getPayload());
textView.setText(text);
} else {
textView.setText("No NDEF messages found.");
}
}
}
}
```
上面的代码片段先检查设备是否支持 NFC,然后在 Activity 的 `onCreate()` 方法中获取传递给这个 Activity 的 intent。如果 intent 的 action 是 `NfcAdapter.ACTION_NDEF_DISCOVERED`,则说明有一个 NDEF 类型的标签或卡片被放置在 NFC 读写器附近,并且这个标签或卡片中包含了 NDEF 消息。你可以使用 `getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)` 方法获取这个消息的数组,然后逐个读取消息中的记录(record),并将它们转换为字符串。
需要注意的是,不同的 NFC 标签或卡片可能有不同的数据格式和读取方式,因此在读取 NFC 数据时需要先了解相关的技术规范和数据格式。同时,你也可以使用其他的 NFC API,如 `NfcF`、`NfcA`、`NfcB` 等,来读取其他类型的 NFC 标签或卡片。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)