先看流程图
使用步骤:
第一步:声明权限
<!-- 允许应用程序使用NFC功能 --> <uses-permission android:name="android.permission.NFC" />
第二步:Activity设置能拦截的NFC tag,不需要拦截ACTION_NDEF_DISCOVERED类型的NDEF标签,标题说了拦截非NDEF的tag
<activity android:name="com.example.nfcdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!-- 能拦截TECH_DISCOVERED的tag --> <intent-filter> <action android:name="android.nfc.action.TECH_DISCOVERED" /> </intent-filter> <!-- TECH_DISCOVERED中哪些部分的tag,在xml文件中找 --> <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/nfc_tech_filter" /> <!-- 能拦截ACTION_TAG_DISCOVERED,好像拦截了,也没啥用,又处理不了--> <intent-filter> <action android:name="android.nfc.action.TAG_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>
其中,nfc_tech_filter.xml在res的xml文件夹中(没有该文件夹则创建该文件夹)
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <tech-list> <tech>android.nfc.tech.IsoDep</tech> </tech-list> <!-- 以下只是显示怎么添加多个nfc支持类 --> <tech-list> <tech>android.nfc.tech.NfcV</tech> </tech-list> <tech-list> <tech>android.nfc.tech.NfcF</tech> </tech-list> </resources>