进行支持NFC程序的开发时的基本步骤为:
1. 在AndroidManifest.xml中进行权限声明以及添加intent-filter过滤器进行支持。
进行权限声明:
进行intent-filter过滤器声明(以NDEF类型为例):
2. 进行定义可接收Tag的Activity,配置一下launchMode属性在AndroidManifest.xml中,例:
<activity android:name=“.Example”
android:launchMode=“singleTop”
android:label=“自动打开通讯录”>
3. 进行NFCAdapter的获取
private NfcAdapter mNfcAdapter =null;//1.声明一个nfc的Adapter
//2.检测NFC的检测函数
private void NfcCheck() {
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);//3.获取nfc适配器
if (mNfcAdapter == null) {
return; //3.如果获取的mNfcAdapter=null,则说明该手机不支持nfc功能
} else {
if (!mNfcAdapter.isEnabled()) {//4.如果手机有nfc功能,进一步判断nfc是否打开
Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivity(setNfc);//5.假如手机的nfc功能没有被打开。则跳到打开nfc功能的界面
}
}
}
4. 进行相关NFC功能操作的编写,实现具体操作,以及相关代码的编写,完成程序编写。
========================================================================
进行支持NFC程序的应用进行实战开发,本次编写的代码为对参考资料6中作者代码的借鉴,在其基础上进行修改、简化完成的。
项目结构的大致截图如下:
阅读源码时,请注意查看相应注释。
AndroidManifest.xml:为应用程序的资源配置文件,在其中定义了nfc功能需要的相关权限与实现NFC的功能类相关定义,相关代码如下:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=“http://schemas.android.com/apk/res/android”
package=“com.suxianpeng.blog_nfc”>
<application
android:allowBackup=“true”
android:icon=“@mipmap/ic_launcher”
android:label=“@string/app_name”
android:roundIcon=“@mipmap/ic_launcher_round”
android:supportsRtl=“true”
android:theme=“@style/AppTheme”>
<activity android:name=“.NFC_AutoSearch_url”
android:launchMode=“singleTop”
android:label=“自动打开百度页面”>
MainActivity类<