1. Android NFC开发入门:从零开始的环境配置
如果你刚接触Android NFC开发,可能会觉得各种协议和技术名词有点吓人。别担心,我刚开始接触NFC时也是一头雾水,但实际用起来就会发现它并没有想象中那么复杂。NFC(近场通信)技术让手机能够与标签、卡片或其他设备在近距离内进行数据交换,这在门禁系统、移动支付、智能海报等场景中非常实用。
在开始编码之前,我们需要先检查设备是否支持NFC功能。这个步骤很关键,因为不是所有Android设备都具备NFC硬件。我记得第一次测试时忘了做这个检查,结果在模拟器上调试了半天都没反应,后来才发现问题所在。通过NfcAdapter.getDefaultAdapter()方法可以获取设备的NFC适配器,如果返回null就说明设备不支持NFC。
接下来需要在AndroidManifest.xml中声明NFC权限。这里有个小细节需要注意:除了添加<uses-permission android:name="android.permission.NFC" />权限外,还需要在配置文件中指定支持的NFC技术类型。我一般会在res目录下创建xml文件夹,然后新建一个nfc_tech_filter.xml文件,里面列出应用需要处理的所有NFC协议类型。
<!-- res/xml/nfc_tech_filter.xml -->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.Ndef</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcB</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcF</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcV</tech>
</tech-list>
</resources>
这样配置后,当设备检测到符合这些技术类型的NFC标签时,就会自动唤醒我们的应用。还有一个容易忽略的点是Activity的启动模式设置,需要将处理NFC的Activity的launchMode设置为singleTop,这样可以避免每次扫描标签时都创建新的Activity实例。
2. 深入理解NFC协议类型与技术特点
NFC技术包含多种协议类型,每种类型都有其特定的应用场景和技术特点。理解这些差异对于选择合适的技术方案至关重要。我在实际项目中接触过各种NFC标签,发现不同协议的兼容性和性能特点确实有很大差异。
Ndef(NFC Data Exchange Format) 是最常用的协议类型,它定义了一种标准的数据交换格式。Ndef消息可以包含多种类型的记录,如文本、URI、智能海报等。这种协议的优点是通用性强,几乎所有支持NFC的设备都能读取Ndef格式的数据。我经常用它来存储简单的配置信息或链接。
NfcA(ISO14443-3A) 基于ISO14443 Type A标准,常见于Mifare Classic和Mifare Ultralight标签。这种协议在门禁系统和交通卡中应用广泛,读写速度较快,但存储容量一般较小。我记得有一次做门禁项目时,就是使用NfcA协议与Mifare Classic卡片进行通信。
NfcB(ISO14443-3B) 同样基于ISO14443标准,但使用Type B协议。它在国内身份证和部分学生证中有应用,安全性相对较高,但兼容性不如NfcA。
NfcF(FeliCa) 是索尼开发的协议标准,在日本市场很常见。它的通信速度较快,支持加密功能。我在一个日本客户的项目中接触过这种协议,需要特别注意设备兼容性问题。
NfcV(ISO15693) 适用于远距离读取场景,读取距离可达1米左右。这种协议在物流管理和资产跟踪中很实用,但数据传输速率较低。
在实际开发中,我建议先明确应用场景需求,再选择合适的协议类型。如果只是简单的数据存储和读取,Ndef是最安全的选择;如果需要与现有卡片系统兼容,就要根据卡片类型选择对应的协议。
3. 实战NFC数据读取与处理
现在让我们进入最实用的部分:如何读取和处理NFC标签数据。这个过程就像是在解谜,每个标签都藏着不同的信息,我们需要用正确的方式去解读它们。
首先需要在Activity中初始化NFC适配器,并设置PendingIntent。这个Intent会在检测到NFC标签时被触发,相当于给系统一个回调通知。我通常会在onCreate和onResume方法中都进行初始化,确保NFC功能在Activity可见时处于活跃状态。
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "设备不支持NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
当检测到NFC标签时,系统会调用onNewIntent方法。在这里我们可以获取到Tag对象,它包含了标签的所有技术信息和数据。我习惯先获取标签的技术列表,判断支持哪些协议类型,然后再用对应的技术类进行数据读取。
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
private void processIntent(Intent intent) {
if (intent == null) return;
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) ||
NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag == null) return;
// 获取标签技术列表
String[] techList = tag.getTechList();
byte[] id = tag.getId();
String tagInfo = "标签ID: " + bytesToHexString(id) + "\n";
// 分析支持的技术类型
for (String tech : techList) {
tagInfo += "支持技术: " + tech + "\n";
}
// 根据技术类型选择处理方式
if (hasTech(techList, "android.nfc.tech.Ndef")) {
processNdefTag(tag);
} else if (hasTech(techList, "android.nfc.tech.NfcA")) {
processNfcATag(tag);
}
}
}
数据处理过程中最常遇到的是字节数组与十六进制字符串的转换。我整理了一个工具类来处理这些转换,这在调试和日志输出时特别有用。
public class NfcUtils {
public static String bytesToHexString(byte[] bytes) {
if (bytes == null || bytes.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.isEmpty()) return null;
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i+1), 16));
}
return data;
}
private static boolean hasTech(String[] techList, String tech) {
for (String t : techList) {
if (t.equals(tech)) return true;
}
return false;
}
}
4. 不同协议类型的详细处理方案
在实际项目中,我们需要针对不同的NFC协议类型采用不同的处理方式。这部分内容是我通过多次实践总结出来的经验,希望能帮你少走弯路。
处理Ndef标签是最常见的情况。Ndef标签存储结构化的数据,读取起来相对简单。首先需要获取Ndef对象,然后读取NdefMessage中的各个记录。
private void processNdefTag(Tag tag) {
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
Toast.makeText(this, "不是NDEF标签", Toast.LENGTH_SHORT).show();
return;
}
try {
ndef.connect();
NdefMessage ndefMessage = ndef.getNdefMessage();
if (ndefMessage == null) {
Toast.makeText(this, "标签中没有NDEF数据", Toast.LENGTH_SHORT).show();
return;
}
// 处理NDEF记录
processNdefRecords(ndefMessage.getRecords());
} catch (IOException | FormatException e) {
Toast.makeText(this, "读取NDEF数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
try {
ndef.close();
} catch (IOException e) {
// 忽略关闭异常
}
}
}
private void processNdefRecords(NdefRecord[] records) {
for (NdefRecord record : records) {
short tnf = record.getTnf();
byte[] type = record.getType();
byte[] payload = record.getPayload();
if (tnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(type, NdefRecord.RTD_TEXT)) {
// 处理文本记录
String text = parseTextRecord(payload);
Log.d("NFC", "文本内容: " + text);
} else if (tnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(type, NdefRecord.RTD_URI)) {
// 处理URI记录
String uri = parseUriRecord(payload);
Log.d("NFC", "URI内容: " + uri);
}
}
}
处理NfcA标签需要更底层的操作。NfcA协议通常用于Mifare Classic等标签,读写操作需要处理扇区和块的概念。
private void processNfcATag(Tag tag) {
NfcA nfca = NfcA.get(tag);
if (nfca == null) return;
try {
nfca.connect();
byte[] atqa = nfca.getAtqa();
int sak = nfca.getSak();
Log.d("NFC", "ATQA: " + bytesToHexString(atqa));
Log.d("NFC", "SAK: " + sak);
// 读取特定块的数据
byte[] blockData = nfca.transceive(new byte[] {
(byte) 0x30, // READ命令
(byte) 0x00 // 块号
});
Log.d("NFC", "块数据: " + bytesToHexString(blockData));
} catch (IOException e) {
Toast.makeText(this, "NfcA通信失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
try {
nfca.close();
} catch (IOException e) {
// 忽略关闭异常
}
}
}
处理NfcV标签(ISO15693)时需要注意,这种协议的通信距离较远,但数据传输速率较低。它通常用于资产管理和物流跟踪。
private void processNfcVTag(Tag tag) {
NfcV nfcv = NfcV.get(tag);
if (nfcv == null) return;
try {
nfcv.connect();
byte[] dsfid = nfcv.getDsfId();
byte[] responseFlags = nfcv.getResponseFlags();
// 读取单个块
byte[] readCommand = new byte[] {
(byte) 0x60, // 标志位
(byte) 0x20, // 读取单个块命令
(byte) 0x00 // 块号
};
byte[] response = nfcv.transceive(readCommand);
if (response != null && response.length > 0) {
// 解析响应数据
byte[] blockData = Arrays.copyOfRange(response, 1, response.length);
Log.d("NFC", "块数据: " + bytesToHexString(blockData));
}
} catch (IOException e) {
Toast.makeText(this, "NfcV通信失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
try {
nfcv.close();
} catch (IOException e) {
// 忽略关闭异常
}
}
}
每种协议类型都有其特定的命令集和响应格式,在实际开发中最好准备相应的协议文档以备查阅。我在处理不同协议时发现,虽然底层实现不同,但基本的连接、通信、关闭流程是相似的,掌握这个模式后学习新的协议类型就会容易很多。
5. 设备兼容性与调试技巧
NFC开发的另一个重要方面是设备兼容性处理。不同厂商的Android设备对NFC的支持程度有所差异,这在实践中是需要特别注意的。
首先要注意的是Android版本兼容性。虽然NFC API从Android 2.3开始引入,但某些高级功能需要更高版本的系统支持。我建议在代码中添加版本检查,确保应用在旧版本设备上也能正常运行。
// 检查NFC功能可用性
private boolean isNfcSupported() {
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
if (adapter == null) {
// 设备不支持NFC
return false;
}
// 检查Android版本
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// 某些功能需要API level 16或更高
return false;
}
return true;
}
不同设备对NFC协议的支持程度也不尽相同。有些设备可能只支持部分协议类型,或者在某些模式下性能表现不佳。我建议在应用启动时检测设备的具体能力,并据此调整应用行为。
// 检测设备支持的NFC技术类型
private void checkSupportedTechnologies() {
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
if (adapter == null) return;
PackageManager pm = getPackageManager();
String[] features = pm.getSystemAvailableFeatures();
List<String> supportedTechs = new ArrayList<>();
if (pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
supportedTechs.add("基础NFC功能");
}
if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) {
supportedTechs.add("主机卡模拟");
}
if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_HCE)) {
supportedTechs.add("HCE功能");
}
Log.d("NFC", "设备支持的NFC功能: " + supportedTechs);
}
调试NFC应用时,日志记录非常重要。由于N通信是瞬间完成的,没有详细的日志很难定位问题。我习惯在关键操作处添加详细的日志输出,包括标签ID、协议类型、操作结果等信息。
private void logTagInfo(Tag tag) {
if (tag == null) return;
StringBuilder log = new StringBuilder();
log.append("标签ID: ").append(bytesToHexString(tag.getId())).append("\n");
String[] techList = tag.getTechList();
for (String tech : techList) {
log.append("支持技术: ").append(tech).append("\n");
}
Log.d("NFC_DEBUG", log.toString());
}
在实际测试中,我发现不同设备的NFC天线位置有所差异。这会影响标签的读取距离和成功率。建议在应用中添加提示,告诉用户大致的NFC感应区域位置。
遇到读取失败的情况时,不要立即报错,可以尝试重试机制。NFC通信容易受到环境干扰,适当的重试可以提高成功率。
private byte[] transceiveWithRetry(NfcTechnology tech, byte[] command, int maxRetries) {
IOException lastException = null;
for (int i = 0; i < maxRetries; i++) {
try {
if (!tech.isConnected()) {
tech.connect();
}
return tech.transceive(command);
} catch (IOException e) {
lastException = e;
try {
Thread.sleep(100); // 短暂延迟后重试
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
throw new RuntimeException("通信失败 after " + maxRetries + "次重试", lastException);
}
6. 实战案例:完整的NFC数据读取应用
让我们通过一个完整的示例来整合前面介绍的知识点。这个示例应用能够读取多种类型的NFC标签,并显示标签的详细信息和数据内容。
首先设置AndroidManifest.xml,声明必要的权限和Activity配置:
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<activity
android:name=".NfcReaderActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<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" />
</activity>
创建主Activity处理NFC相关逻辑:
public class NfcReaderActivity extends AppCompatActivity {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_reader);
resultTextView = findViewById(R.id.result_text);
initNfc();
// 处理从NFC标签启动的情况
if (getIntent() != null &&
(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()) ||
NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction()) ||
NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction()))) {
processIntent(getIntent());
}
}
private void initNfc() {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
resultTextView.setText("设备不支持NFC功能");
return;
}
if (!nfcAdapter.isEnabled()) {
resultTextView.setText("请先启用NFC功能");
return;
}
pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
private void processIntent(Intent intent) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag == null) return;
StringBuilder result = new StringBuilder();
result.append("标签ID: ").append(NfcUtils.bytesToHexString(tag.getId())).append("\n\n");
String[] techList = tag.getTechList();
result.append("支持的技术:\n");
for (String tech : techList) {
result.append("• ").append(tech).append("\n");
}
result.append("\n");
// 根据技术类型处理标签
try {
if (hasTech(techList, "android.nfc.tech.Ndef")) {
result.append(processNdefTag(tag));
} else if (hasTech(techList, "android.nfc.tech.NfcA")) {
result.append(processNfcATag(tag));
} else if (hasTech(techList, "android.nfc.tech.NfcV")) {
result.append(processNfcVTag(tag));
}
} catch (Exception e) {
result.append("处理失败: ").append(e.getMessage());
}
resultTextView.setText(result.toString());
}
// 具体的标签处理方法(前面已经介绍过)
private String processNdefTag(Tag tag) { ... }
private String processNfcATag(Tag tag) { ... }
private String processNfcVTag(Tag tag) { ... }
}
布局文件简单显示读取结果:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/result_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="14sp"
android:text="请将NFC标签靠近设备背面..."/>
</ScrollView>
这个示例应用涵盖了NFC开发的主要环节:设备兼容性检查、标签类型判断、数据读取和结果显示。在实际使用中,你可能还需要添加错误处理、数据解析、文件操作等更多功能。
记得在真机上测试时,不同设备的NFC天线位置可能不同,一般位于设备背部上方区域。测试时要确保标签与设备天线位置对齐,并保持稳定直到读取完成。
892




被折叠的 条评论
为什么被折叠?



