android nfc功能 简单实现。
时间: 2023-08-25 08:02:26 浏览: 134
Android的NFC(近场通信)功能可以通过以下简单的步骤来实现。
首先,确保你的Android设备支持NFC功能。大多数现代Android设备都已经内置了NFC芯片。
接下来,在你的Android应用程序中添加必要的权限。在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.NFC" />
```
然后,在你的MainActivity类中添加以下代码来检查设备是否支持NFC功能:
```java
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// 设备不支持NFC
} else {
// 设备支持NFC
}
```
接下来,你可以在你的应用程序中监听NFC事件。首先,在AndroidManifest.xml文件中添加一个.intent-filter元素,以便你的应用可以接收到NFC相关的Intent:
```xml
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
```
然后,在你的MainActivity类中重写onNewIntent方法,以便在设备接收到NFC标签时进行处理:
```java
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
// 处理NFC标签数据
}
}
```
最后,你可以使用NFC相关的API来读取和写入NFC标签的数据。例如,你可以使用以下代码来读取NFC标签的文本数据:
```java
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 = message[0].getRecords()[0];
String textData = new String(record.getPayload());
// 处理文本数据
}
```
通过以上步骤,你可以在你的Android应用程序中简单地实现NFC功能。你可以根据自己的需求扩展这些代码,例如添加写入NFC标签数据的功能或处理其他类型的NFC标签。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)