![](/img/trans.png)
[英]How to read detected NFC tag (NDEF content) details in android?
[英]How to read from detected NFC tag (NDEF message). Android NFC
类似的问题 - 如何在Android中读取检测到的NFC标签(NDEF内容)细节?
我希望我的Android应用程序能够读取和解析检测到的NDEF消息。
我已经编辑了AndroidManifest.xml来检测nfc标签,我添加了它看起来像这样的intent过滤器
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
我相信这很好,因为当我使用SDK附带的NFCDemo示例应用程序来创建MockNDEFtags时,我可以选择处理这些生成的应用程序的应用程序列表我的应用程序出现。 然后我点击我的应用程序,它打开没有问题,我只需要一种方法来读取在NDEF消息中传递给它的数据。 代码:
Tag myTag = (Tag) nfcintent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// get NDEF tag details
Ndef ndefTag = Ndef.get(myTag);
...
NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
在类似的问题中提出了建议,在整个网络上我找到了许多类似的答案。 我的问题在于代码行
"Tag myTag = (Tag) nfcintent.getParcelableExtra(NfcAdapter.EXTRA_TAG);"
我得到错误“nfcintent无法解决”我意识到代码的作者可能会将nfcintent作为占位符以获取特定于我的应用程序的意图但是我不确定我应该放在哪里。
启动我的应用程序的主要活动看起来像这样
public class TabsActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
// Tab for Graph
TabSpec graphspec = tabHost.newTabSpec("Graph");
// setting Title and Icon for the Tab
graphspec.setIndicator("Graph");
Intent graphIntent = new Intent(this, GraphActivity.class);
graphspec.setContent(graphIntent);
// Tab for Intro
TabSpec introspec = tabHost.newTabSpec("Intro");
introspec.setIndicator("Intro");
Intent introIntent = new Intent(this, IntroActivity.class);
introspec.setContent(introIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(introspec); // Adding intro tab
tabHost.addTab(graphspec); // Adding graph tab
}
}
我假设这启动了应用程序,它必须处理NFC标签。 如果我可以从标签访问NDEFMessage,我已经能够使用Android示例应用程序中的NdefMessageParser解析它。 我想解析来自NDEFmessage的信息,并最终通过应用程序中的每个选项卡访问该信息。
尝试使用此代码段从Tag中提取邮件:
Parcelable[] rawMsgs = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
extractMessage(msg);
private void extractMessage(NdefMessage msg) {
byte[] array = null;
array = msg.getRecords()[0].getPayload();
}
另请查看此NFC读取器/写入器示例
为了获得通过NFC标签的意图,在我的情况下启动活动“nfcintent”只需使用
Intent nfcintent = getIntent();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.