如何在NFC校验条件不满足时终止读取流程并展示TextView
修复方案
现有代码问题
- 缺少文本空值校验:直接调用
text.charAt(0)时,如果解析到的文本为空会触发越界崩溃 - 控件逻辑反向:当前代码在首字符非'S'时隐藏提示控件,与你需要展示对应提示的需求相反
- 无流程中断逻辑:仅修改控件状态,没有退出当前方法,后续NFC处理逻辑仍会正常执行,达不到中断效果
修正后的核心代码
在文本校验分支补充return中断方法执行,修正控件展示逻辑:
private void buildTagViews(NdefMessage[] msgs) { if (msgs == null || msgs.length == 0) return; String text = ""; byte[] payload = msgs[0].getRecords()[0].getPayload(); String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; int languageCodeLength = payload[0] & 0063; try { text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding); } catch (UnsupportedEncodingException e) { Log.e("UnsupportedEncoding", e.toString()); } // 补充空文本校验,避免越界异常 if (text.isEmpty()) { Alerte.setText("标签内容为空"); Alerte.setVisibility(View.VISIBLE); // 直接退出方法,终止后续处理 return; } // 首字符非'S'的处理分支 if (text.charAt(0) != 'S') { // 展示对应提示文本 Alerte.setText("标签格式不符合要求"); Alerte.setVisibility(View.VISIBLE); // 中断当前读取全流程 return; } // 首字符为'S'的正常业务逻辑 Alerte.setText("标签校验通过"); Alerte.setVisibility(View.VISIBLE); }
全量NFC流程中断补充说明
如果需要彻底停止应用对NFC标签的感应(而非仅退出当前读取方法),可在非'S'的判断分支中补充关闭前台调度的代码,避免标签反复触发读取:
// 首字符非'S'分支内补充 if (text.charAt(0) != 'S') { Alerte.setText("标签格式不符合要求"); Alerte.setVisibility(View.VISIBLE); // 彻底关闭前台NFC感应,中断全流程 NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this); return; }
注意:若后续需要恢复NFC读取功能,需手动调用
enableForegroundDispatch()重新激活前台调度。
内容的提问来源于stack exchange,提问作者Antoine
相关产品推荐
相关产品推荐

