如何从检测到的NFC标签(NDEF消息)中读取数据。 Android NFC

问题描述:

类似的问题 - How to read detected NFC tag (NDEF content) details in android?如何从检测到的NFC标签(NDEF消息)中读取数据。 Android NFC

我想我的android应用程序能够读取和解析检测到的NDEF消息。

我已经编辑AndroidManifest.xml中检测到NFC标签和我已经加入的意图过滤器,它看起来像这样

  <intent-filter> 
      <action android:name="android.nfc.action.TAG_DISCOVERED"/> 
      <category android:name="android.intent.category.DEFAULT"/> 
    </intent-filter> 

我相信这是罚款,当我使用随附NFCDemo示例应用程序SDK可以创建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作为一个占位符的意图具体到我的应用程序不过IM不知道我应该放在哪里。

我mainactivity启动我的应用程序看起来像这样

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的信息,并最终让应用程序中的每个选项卡访问该信息。

+0

我的问题是与代码snipets诸如 “Parcelable [] rawMsgs =意图 .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);”意图无法解决。这实际上是我应该使用的。 – curtisq 2012-07-29 02:44:26

试试这个片段从标签中提取消息:

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 Reader/Writer

要获得通过NFC标签启动活动在我的情况“nfcintent”的意图只是使用

Intent nfcintent = getIntent();