Android examples for Network:NFC Message
Parse an intent for non-empty strings within an NDEF message
//package com.java2s; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Parcelable; import android.text.TextUtils; public class Main { /**/* w ww . j av a 2 s . com*/ * Parse an intent for non-empty strings within an NDEF message * * @param intent * @return an empty list if the payload is empty */ public static List<String> getStringsFromNfcIntent(Intent intent) { List<String> payloadStrings = new ArrayList<String>(); for (NdefMessage message : getMessagesFromIntent(intent)) { for (NdefRecord record : message.getRecords()) { byte[] payload = record.getPayload(); String payloadString = new String(payload); if (!TextUtils.isEmpty(payloadString)) payloadStrings.add(payloadString); } } return payloadStrings; } /** * Parses an intent for NDEF messages, returns all that are found * * @param intent * @return an empty list if there are no NDEF messages found */ public static List<NdefMessage> getMessagesFromIntent(Intent intent) { List<NdefMessage> intentMessages = new ArrayList<NdefMessage>(); String action = intent.getAction(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { // Log.i(LOG_TAG, "Reading from NFC " + action); Parcelable[] rawMsgs = intent .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { for (Parcelable msg : rawMsgs) { if (msg instanceof NdefMessage) { intentMessages.add((NdefMessage) msg); } } } else { // Unknown tag type byte[] empty = new byte[] {}; final NdefRecord record = new NdefRecord( NdefRecord.TNF_UNKNOWN, empty, empty, empty); final NdefMessage msg = new NdefMessage( new NdefRecord[] { record }); intentMessages = new ArrayList<NdefMessage>() { { add(msg); } }; } } return intentMessages; } }