在Android应用开发中使用NFC功能

NFC介绍

NFC是指"近场通讯"(Near Field Communication),它是一种短距离无线通信技术,允许设备在非接触或极短距离内进行通信。NFC通常用于移动支付、门禁系统、智能标签和其他物联网应用中。

Android系统对NFC提供了广泛的支持。通过NFC技术,Android设备可以与其他NFC设备进行通信,读取NFC标签上的信息,以及进行NFC支付等操作。

要在Android应用中使用NFC功能,需要在AndroidManifest.xml文件中声明相应的权限和特性,并在应用代码中使用NFC相关的API进行操作。同时,还需要确保设备支持NFC功能,并且用户已经打开了NFC功能。

scss 复制代码
// 检查设备是否支持NFC
NfcManager nfcManager = (NfcManager) getSystemService(Context.NFC_SERVICE);
NfcAdapter nfcAdapter = nfcManager.getDefaultAdapter();
if (nfcAdapter != null && nfcAdapter.isEnabled()) {
    // NFC可用,执行相应的操作
} else {
    // NFC不可用,给出相应的提示
}

在实际应用中,可以使用NFC相关的Intent过滤器来响应NFC标签的读取、写入等操作,也可以使用NFC相关的API来进行更加灵活的操作。

Android系统对NFC提供了良好的支持,开发者可以充分利用这一功能为应用增加更多的交互和便利性。

NFC使用

如何在Android上使用NFC读取卡片信息。首先,确保你的设备支持NFC功能。

  1. 添加必要的权限到AndroidManifest.xml文件中:
ini 复制代码
 <uses-permission android:name="android.permission.NFC" />
 <uses-feature android:name="android.hardware.nfc" android:required="true" />
  1. 在你的Activity中注册NFC相关的intent过滤器:
ini 复制代码
 <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" />
  1. 创建一个NFC读取的回调函数,并在onCreate方法中初始化NFC适配器:
java 复制代码
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// 检查设备是否支持NFC,并且NFC是否已经开启
if (nfcAdapter != null && nfcAdapter.isEnabled()) {
  // 在onCreate方法中注册NFC事件处理器
  IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
  IntentFilter[] filters = new IntentFilter[]{tagDetected};

  // 创建一个PendingIntent对象,以便系统可以在检测到NFC标签时通知你的应用
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

  // 在onResume方法中启用前台调度
  nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, null);
}
  1. 处理NFC标签的读取事件,并从标签中读取信息:
java 复制代码
 @Override
 protected void onNewIntent(Intent intent) {
     if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
         Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
         // 从标签中读取信息
     }
 }
  1. 在AndroidManifest.xml文件中创建一个nfc_tech_filter.xml文件,用于指定你要处理的NFC标签类型:
xml 复制代码
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <tech-list>
         <tech>android.nfc.tech.IsoDep</tech>
         <tech>android.nfc.tech.NfcA</tech>
         <tech>android.nfc.tech.NfcB</tech>
         <tech>android.nfc.tech.NfcF</tech>
         <tech>android.nfc.tech.NfcV</tech>
         <tech>android.nfc.tech.Ndef</tech>
     </tech-list>
 </resources>

通过以上步骤,你就可以在你的Android应用中使用NFC读取卡片信息了。

使用NFC写入器类来向NFC卡片写入文本信息示例:

ini 复制代码
// 创建一个NFC写入器类
public class NFCWriter {
    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private IntentFilter[] intentFilters;
    private String[][] techLists;

    public NFCWriter(Activity activity) {
        nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        Intent intent = new Intent(activity, activity.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        intentFilters = new IntentFilter[]{ndef};
        techLists = new String[][]{new String[]{NfcF.class.getName()}};
    }

    // 写入NDEF消息到NFC卡片
    public void writeNdefMessage(Tag tag, NdefMessage message) {
        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();
                ndef.writeNdefMessage(message);
                ndef.close();
            } else {
                NdefFormatable formatable = NdefFormatable.get(tag);
                if (formatable != null) {
                    formatable.connect();
                    formatable.format(message);
                    formatable.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

总结

NFC(Near Field Communication)是一种无线技术,用于在短距离内进行数据传输和通信。在Android设备上,NFC可以用于实现多种功能,如支付、数据传输、门禁卡等。

  1. 硬件支持:确保设备支持NFC功能,并且用户已经开启了NFC功能。
  2. 权限声明:在AndroidManifest.xml文件中声明NFC权限。
ini 复制代码
<uses-permission android:name="android.permission.NFC" />
  1. 检测NFC功能:在应用中检测设备是否支持NFC功能,并且是否已经开启。
  2. 创建NFC交互:创建NFC交互的相关操作,如读取NFC标签、写入NFC标签、处理NFC数据等。
  3. 处理NFC意图:注册NFC意图过滤器,以便应用在检测到NFC标签时能够响应相应的操作。
ini 复制代码
<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="application/*" />
</intent-filter>
  1. 处理NFC数据:当应用接收到NFC意图时,处理NFC标签中的数据,并进行相应的操作。

NFC开发涉及到硬件支持、权限声明、NFC功能检测、NFC交互创建、NFC意图处理等步骤。通过合理的处理,可以实现丰富的NFC功能,为用户提供更便利的体验。

文章同步自微信公众号【沐雨花飞蝶】,每天准时分享知识,欢迎关注!

相关推荐
游戏开发爱好者81 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
王码码20352 小时前
Flutter for OpenHarmony 实战之基础组件:第三十一篇 Chip 系列组件 — 灵活的标签化交互
android·flutter·交互·harmonyos
黑码哥2 小时前
ViewHolder设计模式深度剖析:iOS开发者掌握Android列表性能优化的实战指南
android·ios·性能优化·跨平台开发·viewholder
亓才孓2 小时前
[JDBC]元数据
android
独行soc2 小时前
2026年渗透测试面试题总结-17(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮
金融RPA机器人丨实在智能2 小时前
Android Studio开发App项目进入AI深水区:实在智能Agent引领无代码交互革命
android·人工智能·ai·android studio
科技块儿2 小时前
利用IP查询在智慧城市交通信号系统中的应用探索
android·tcp/ip·智慧城市
独行soc3 小时前
2026年渗透测试面试题总结-18(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮
王码码20353 小时前
Flutter for OpenHarmony 实战之基础组件:第二十七篇 BottomSheet — 动态底部弹窗与底部栏菜单
android·flutter·harmonyos
2501_915106323 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview