如何在android中读取Nfc标签?

时间:2011-09-26 08:15:21

标签: android nfc

如何从NFC标签中读取和显示NDEF消息?请帮我。任何人都可以提供示例源代码来读取Nfc标签吗?

2 个答案:

答案 0 :(得分:11)

1)Android上NFC的一般描述是here
2)NFCDemo是here
3)非常好的信息也是here
4)“Zigurd Mednieks”中的“Programming Android”一书中有一章关于NFC
BR
斯登

答案 1 :(得分:6)

我们有两个阅读nfc卡的选项。

  1. 从缓存中读取

       Ndef ndef = Ndef.get(tag);
        if (ndef == null) {
            // NDEF is not supported by this Tag. 
            return null;
        }
    
        NdefMessage ndefMessage = ndef.getCachedNdefMessage();
    
        if (ndefMessage == null) {
            mTextView.setText("The tag is empty !");
            return null;
        }
    
        NdefRecord[] records = ndefMessage.getRecords();
        for (NdefRecord ndefRecord : records) {
            if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                try {
                    return readText(ndefRecord);
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "Unsupported Encoding", e);
                }
            }
        }
    
  2. 使用

  3. 直接阅读
    public void readFromTag(Intent intent){
    
        Ndef ndef = Ndef.get(detectedTag);
    
    
        try{
            ndef.connect();
    
            txtType.setText(ndef.getType().toString());
            txtSize.setText(String.valueOf(ndef.getMaxSize()));
            txtWrite.setText(ndef.isWritable() ? "True" : "False");
            Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    
            if (messages != null) {
                NdefMessage[] ndefMessages = new NdefMessage[messages.length];
                for (int i = 0; i < messages.length; i++) {
                    ndefMessages[i] = (NdefMessage) messages[i];
                }
                NdefRecord record = ndefMessages[0].getRecords()[0];
    
                byte[] payload = record.getPayload();
                String text = new String(payload);
                txtRead.setText(text);
    
    
                ndef.close();
    
            }
        }
        catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Cannot Read From Tag.", Toast.LENGTH_LONG).show();
        }
    }