Java Code Examples for android.nfc.NdefMessage#getRecords()

The following examples show how to use android.nfc.NdefMessage#getRecords() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Message.java    From effective_android_sample with Apache License 2.0 7 votes vote down vote up
/**
 * {@link Parcelable} array constructor. If multiple messages, records are added in natural order.
 * 
 * @param messages {@link NdefMessage}s in {@link Parcelable} array.
 * @throws FormatException if known record type cannot be parsed
 */

public Message(Parcelable[] messages) throws FormatException {
    for (int i = 0; i < messages.length; i++) {
    	NdefMessage message = (NdefMessage) messages[i];
        
		for(NdefRecord record : message.getRecords()) {
			add(Record.parse(record));
		}
    }
}
 
Example 2
Source File: AddFriendQRActivity.java    From NaviBee with GNU General Public License v3.0 6 votes vote down vote up
private void handleNfcIntent(Intent NfcIntent) {
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(NfcIntent.getAction())) {
        Parcelable[] receivedArray =
                NfcIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

        if(receivedArray != null) {
            NdefMessage receivedMessage = (NdefMessage) receivedArray[0];
            NdefRecord[] attachedRecords = receivedMessage.getRecords();

            for (NdefRecord record: attachedRecords) {
                String string = new String(record.getPayload());
                // Make sure we don't pass along our AAR (Android Application Record)
                if (string.equals(getPackageName())) continue;
                addFriend(string);
            }
        }
    }
}
 
Example 3
Source File: BeamActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_beam);

  // Listing 18-24: Extracting the Android Beam payload
  Parcelable[] messages
    = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
  if (messages != null) {
    NdefMessage message = (NdefMessage) messages[0];
    if (message != null) {
      NdefRecord record = message.getRecords()[0];
      String payload = new String(record.getPayload());
      Log.d(TAG, "Payload: " + payload);
    }
  }
}
 
Example 4
Source File: BlogViewer.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void processIntent(Intent intent) {
  // Listing 18-18: Extracting NFC tag payloads
  String action = intent.getAction();

  if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
    Parcelable[] messages = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    if (messages != null) {
      for (Parcelable eachMessage : messages) {
        NdefMessage message = (NdefMessage) eachMessage;
        NdefRecord[] records = message.getRecords();

        if (records != null) {
          for (NdefRecord record : records) {
            String payload = new String(record.getPayload());
            Log.d(TAG, payload);
          }
        }
      }
    }
  }
}
 
Example 5
Source File: NfcUtils.java    From WiFiKeyShare with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parse an NDEF message and return the corresponding Wi-Fi configuration
 *
 * Source: http://androidxref.com/6.0.1_r10/xref/packages/apps/Nfc/src/com/android/nfc/NfcWifiProtectedSetup.java
 *
 * @param message the NDEF message to parse
 * @return a WifiConfiguration extracted from the NDEF message
 */
private static WifiConfiguration parse(NdefMessage message) {
    NdefRecord[] records = message.getRecords();
    for (NdefRecord record : records) {
        if (new String(record.getType()).equals(NFC_TOKEN_MIME_TYPE)) {
            ByteBuffer payload = ByteBuffer.wrap(record.getPayload());
            while (payload.hasRemaining()) {
                short fieldId = payload.getShort();
                short fieldSize = payload.getShort();
                if (fieldId == CREDENTIAL_FIELD_ID) {
                    return parseCredential(payload, fieldSize);
                } else {
                    payload.position(payload.position() + fieldSize);
                }
            }
        }
    }
    return null;
}
 
Example 6
Source File: NfcTypeConverter.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Converts android.nfc.NdefMessage to mojo NfcMessage
 */
public static NfcMessage toNfcMessage(NdefMessage ndefMessage)
        throws UnsupportedEncodingException {
    NdefRecord[] ndefRecords = ndefMessage.getRecords();
    NfcMessage nfcMessage = new NfcMessage();
    List<NfcRecord> nfcRecords = new ArrayList<NfcRecord>();

    for (int i = 0; i < ndefRecords.length; i++) {
        if ((ndefRecords[i].getTnf() == NdefRecord.TNF_EXTERNAL_TYPE)
                && (Arrays.equals(ndefRecords[i].getType(), WEBNFC_URN.getBytes("UTF-8")))) {
            nfcMessage.url = new String(ndefRecords[i].getPayload(), "UTF-8");
            continue;
        }

        NfcRecord nfcRecord = toNfcRecord(ndefRecords[i]);
        if (nfcRecord != null) nfcRecords.add(nfcRecord);
    }

    nfcMessage.data = new NfcRecord[nfcRecords.size()];
    nfcRecords.toArray(nfcMessage.data);
    return nfcMessage;
}
 
Example 7
Source File: MainActivity.java    From QuickLyric with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(14)
private Lyrics getBeamedLyrics(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    if (rawMsgs != null && rawMsgs.length > 0) {
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        NdefRecord[] records = msg.getRecords();
        if (records.length > 0) {
            try {
                return Lyrics.fromBytes(records[0].getPayload());
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
 
Example 8
Source File: Record.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
/**
 * Parse single record.
 * 
    * @param record record to parse
    * @return corresponding {@link Record} subclass - or null if not known
    * @throws FormatException if known record type cannot be parsed
 * @throws IllegalArgumentException if zero or more than one record
 */

protected static Record parse(byte[] record) throws FormatException {
	NdefMessage message = new NdefMessage(record);
	if(message.getRecords().length != 1) {
		throw new IllegalArgumentException("Single record expected");
	}
	return Record.parse(message.getRecords()[0]);
}
 
Example 9
Source File: OtpParser.java    From yubikit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Parses nfc tag and extracts otp credential from it
 * @param ndefMessage an NDEF message from tag
 * @return OTP data
 */
public static @Nullable String parseNdefMessage(NdefMessage ndefMessage) {
    for (NdefRecord record : ndefMessage.getRecords()) {
        String parsedData = parseNdefRecord(record);
        if (parsedData != null) {
            return parsedData;
        }
    }
    return null;
}
 
Example 10
Source File: Message.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
/**
 * {@link NdefMessage} constructor.
 * 
 * @param ndefMessage
 * @throws FormatException if known record type cannot be parsed
 */

public Message(NdefMessage ndefMessage) throws FormatException {
	for(NdefRecord record : ndefMessage.getRecords()) {
		add(Record.parse(record));
	}
}
 
Example 11
Source File: NfcReaderActivity.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
@Override
public void nfcIntentDetected(Intent intent, String action) {
	Log.d(TAG, "nfcIntentDetected: " + action);
	
	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];
	    }
	    
	    if(ndefMessages.length > 0) {
	    	// read as much as possible
			Message message = new Message();
			for (int i = 0; i < messages.length; i++) {
		    	NdefMessage ndefMessage = (NdefMessage) messages[i];
		        
				for(NdefRecord ndefRecord : ndefMessage.getRecords()) {
					try {
						message.add(Record.parse(ndefRecord));
					} catch (FormatException e) {
						// if the record is unsupported or corrupted, keep as unsupported record
						message.add(UnsupportedRecord.parse(ndefRecord));
					}
				}
		    }
			readNdefMessage(message);
	    } else {
	    	readEmptyNdefMessage();
	    }
	} else  {
		readNonNdefMessage();
	}
}
 
Example 12
Source File: NfcReadUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Iterator<Byte> retrieveMessageTypes(NdefMessage record) {
    Collection<Byte> list = new ArrayList<Byte>();
    for (NdefRecord ndefRecord : record.getRecords()) {
        list.add(retrieveTypeByte(ndefRecord.getPayload()));
    }
    return list.iterator();
}
 
Example 13
Source File: CardboardDeviceParams.java    From Cardboard with Apache License 2.0 5 votes vote down vote up
public static CardboardDeviceParams createFromNfcContents(
		NdefMessage tagContents) {
	if (tagContents == null) {
		Log.w("CardboardDeviceParams",
				"Could not get contents from NFC tag.");
		return null;
	}
	CardboardDeviceParams deviceParams = new CardboardDeviceParams();
	for (NdefRecord record : tagContents.getRecords()) {
		if (deviceParams.parseNfcUri(record)) {
			break;
		}
	}
	return deviceParams;
}
 
Example 14
Source File: NFCReader.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * NdefMessage の情報を指定したリストに格納します.
 *
 * @param message NFCに格納されたメッセージ
 * @param tagList 情報を格納するリスト
 */
private void readNdefMessage(final NdefMessage message, final List<Map<String, Object>> tagList) {
    if (message != null && message.getRecords() != null) {
        for (NdefRecord record : message.getRecords()) {
            tagList.add(readRecord(record));
        }
    }
}
 
Example 15
Source File: NfcReadUtilityImpl.java    From android-nfc-lib with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String retrieveMessage(NdefMessage message) {
    return message.getRecords()[0] != null ? parseAccordingToHeader(message.getRecords()[0].getPayload()) : null;
}
 
Example 16
Source File: HandoverCarrierRecord.java    From effective_android_sample with Apache License 2.0 4 votes vote down vote up
public static HandoverCarrierRecord parseNdefRecord(NdefRecord ndefRecord) throws FormatException {
	
	byte[] payload = ndefRecord.getPayload();
	
	CarrierTypeFormat carrierTypeFormat = CarrierTypeFormat.toCarrierTypeFormat((byte)(payload[0] & 0x7));
	
	HandoverCarrierRecord handoverCarrierRecord = new HandoverCarrierRecord();
	handoverCarrierRecord.setCarrierTypeFormat(carrierTypeFormat);

	int carrierTypeLength = (int)(payload[1] & 0xFF);

	switch (carrierTypeFormat) {
		case WellKnown: {
			// NFC Forum well-known type [NFC RTD]
			
			// parse records 'manually' here, so that we can check the tnf type instead of the class type
			byte[] recordsPayload = new byte[carrierTypeLength];
			System.arraycopy(payload, 2, recordsPayload, 0, carrierTypeLength);
			NdefMessage message = new NdefMessage(recordsPayload);
			
			NdefRecord[] records = message.getRecords();
			if(records.length != 1) {
				throw new IllegalArgumentException();
			}
			if(records[0].getTnf() != NdefRecord.TNF_WELL_KNOWN) {
				throw new IllegalArgumentException("Expected well-known type carrier type");
			}
			
			handoverCarrierRecord.setCarrierType(Record.parse(records[0]));

			break;
		}
		case Media: {

			// Media-type as defined in RFC 2046 [RFC 2046]
			handoverCarrierRecord.setCarrierType(new String(payload, 2, carrierTypeLength, Charset.forName("US-ASCII")));

			break;
		}
		case AbsoluteURI: {
			// Absolute URI as defined in RFC 3986 [RFC 3986]
			handoverCarrierRecord.setCarrierType(new String(payload, 2, carrierTypeLength, Charset.forName("US-ASCII")));

			break;
		}
		case External: {
			// NFC Forum external type [NFC RTD]

			Record record = Record.parse(payload, 2, carrierTypeLength);

			if (record instanceof ExternalTypeRecord) {
				handoverCarrierRecord.setCarrierType(record);
			}
			else {
				throw new IllegalArgumentException("Expected external type carrier type, not " + record.getClass().getSimpleName());
			}
		}
		default: {
			throw new RuntimeException();
		}

	}

	// The number of CARRIER_DATA octets is equal to the NDEF record PAYLOAD_LENGTH minus the CARRIER_TYPE_LENGTH minus 2.		
	int carrierDataLength = payload.length - 2 - carrierTypeLength;

	byte[] carrierData;
	if (carrierDataLength > 0) {
		carrierData = new byte[carrierDataLength];
		System.arraycopy(payload, 2 + carrierTypeLength, carrierData, 0, carrierDataLength);
	}
	else {
		carrierData = null;
	}
	handoverCarrierRecord.setCarrierData(carrierData);

	return handoverCarrierRecord;
}
 
Example 17
Source File: AppRunnerActivity.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Listen to NFC incomming data
 */
@Override
public void onNewIntent(Intent intent) {
    MLog.d(TAG, "New intent " + intent);

    if (intent.getAction() != null) {
        MLog.d(TAG, "Discovered tag with intent: " + intent);

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String nfcID = StrUtils.bytetostring(tag.getId());

        // if there is a message waiting to be written
        if (PNfc.nfcMsg != null) {
            MLog.d(TAG, "->" + PNfc.nfcMsg);
            PNfc.writeTag(this, tag, PNfc.nfcMsg);
            if (onNFCWrittenListener != null) onNFCWrittenListener.onNewTag();
            onNFCWrittenListener = null;
            PNfc.nfcMsg = null;

            // read the nfc tag info
        } else {
            // get NDEF tag details
            Ndef ndefTag = Ndef.get(tag);
            if (ndefTag == null) {
                return;
            }

            int size = ndefTag.getMaxSize(); // tag size
            boolean writable = ndefTag.isWritable(); // is tag writable?
            String type = ndefTag.getType(); // tag type

            String nfcMessage = "";

            // get NDEF message details
            NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
            if (ndefMesg != null) {
                NdefRecord[] ndefRecords = ndefMesg.getRecords();
                int len = ndefRecords.length;
                String[] recTypes = new String[len]; // will contain the
                // NDEF record types
                String[] recPayloads = new String[len]; // will contain the
                // NDEF record types
                for (int i = 0; i < len; i++) {
                    recTypes[i] = new String(ndefRecords[i].getType());
                    recPayloads[i] = new String(ndefRecords[i].getPayload());
                }
                nfcMessage = recPayloads[0];
            }
            if (onNFCListener != null) onNFCListener.onNewTag(nfcID, nfcMessage);
        }
    }
}
 
Example 18
Source File: TabbedMainActivity.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
private void onBitcoinUri() {

        Uri uri = null;
        if (!NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
            uri = getIntent().getData();
        else {
            final Parcelable[] rawMessages;
            rawMessages = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            for (final Parcelable parcel : rawMessages) {
                final NdefMessage ndefMsg = (NdefMessage) parcel;
                for (final NdefRecord record : ndefMsg.getRecords())
                    if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN &&
                        Arrays.equals(record.getType(), NdefRecord.RTD_URI))
                        uri = record.toUri();
            }
        }
        if (uri == null)
            return;

        final Intent intent = new Intent(this, SendAmountActivity.class);
        final String text = uri.toString();
        try {
            final int subaccount = getActiveAccount();
            final GDKTwoFactorCall call = getSession().createTransactionFromUri(null, text, subaccount);
            final ObjectNode transactionFromUri = call.resolve(null, new HardwareCodeResolver(this));
            final String error = transactionFromUri.get("error").asText();
            if ("id_invalid_address".equals(error)) {
                UI.toast(this, R.string.id_invalid_address, Toast.LENGTH_SHORT);
                return;
            }
            removeUtxosIfTooBig(transactionFromUri);
            intent.putExtra(PrefKeys.INTENT_STRING_TX, transactionFromUri.toString());
        } catch (final Exception e) {
            e.printStackTrace();
            if (e.getMessage() != null)
                UI.toast(this, e.getMessage(), Toast.LENGTH_SHORT);
            return;
        }
        intent.putExtra("internal_qr", getIntent().getBooleanExtra("internal_qr", false));
        startActivityForResult(intent, REQUEST_BITCOIN_URL_SEND);
    }
 
Example 19
Source File: NfcUtil.java    From zap-android with MIT License 4 votes vote down vote up
/**
 * This function reads the content of an NFC Ndef Tag.
 * As we want to read all NFC Tags while zap is open and a specific Activities (done with ForegroundDispatch),
 * we have to make sure that we validate the tag type properly in this function.
 * The filters from the manifest only apply to a tag that is read while the app is not in foreground
 * or at an activity that does not do any foreground dispatching.
 *
 * @param ctx      Context.
 * @param intent   The Intent
 * @param listener listener which provides the payload in its onSuccess function
 */
public static void readTag(Context ctx, Intent intent, OnNfcResponseListener listener) {
    String action = intent.getAction();
    ZapLog.debug(LOG_TAG, "onNewIntent: " + action);
    if (action != null) {
        if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED) || action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {

            Parcelable[] rawMessages =
                    intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawMessages != null) {
                NdefMessage[] messages = new NdefMessage[rawMessages.length];
                for (int i = 0; i < rawMessages.length; i++) {
                    messages[i] = (NdefMessage) rawMessages[i];
                }
                // Process the messages array.
                NdefMessage message = messages[0];

                ZapLog.debug(LOG_TAG, "Ndef message: " + message);
                NdefRecord[] records = message.getRecords();
                ZapLog.debug(LOG_TAG, "Ndef record: " + records[0]);
                if (records[0].getTnf() == NdefRecord.TNF_WELL_KNOWN) {
                    if (Arrays.equals(records[0].getType(), NdefRecord.RTD_URI)) {
                        byte[] rawPayload = records[0].getPayload();
                        StringBuilder sb = new StringBuilder();
                        for (int i = 1; i < rawPayload.length; i++) {
                            sb.append((char) rawPayload[i]);
                        }
                        String payload = sb.toString();
                        ZapLog.debug(LOG_TAG, "Ndef payload: " + payload);
                        listener.onSuccess(payload);
                    } else {
                        ZapLog.debug(LOG_TAG, "This NdefRecord is not supported");
                        showNotSupportedToast(ctx);
                    }
                } else {
                    ZapLog.debug(LOG_TAG, "This NdefRecord type name field (TNF) is not supported");
                    showNotSupportedToast(ctx);
                }

            } else {
                ZapLog.debug(LOG_TAG, "Tag message is empty");
                showNotSupportedToast(ctx);
            }
        }
    }
}