android.nfc.NdefMessage Java Examples

The following examples show how to use android.nfc.NdefMessage. 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: 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 #2
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 #3
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 #4
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 #5
Source File: NfcHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Writes an NdefMessage to a NFC tag
 */
public static void writeTag(NdefMessage message, Tag tag) throws Exception {
    int size = message.toByteArray().length;
    Ndef ndef = Ndef.get(tag);
    if (ndef != null) {
        ndef.connect();
        if (!ndef.isWritable()) {
            throw new NfcTagNotWritableException();
        }
        if (ndef.getMaxSize() < size) {
            throw new NfcTagInsufficientMemoryException(ndef.getMaxSize(), size);
        }
        ndef.writeNdefMessage(message);
    } else {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
            format.connect();
            format.format(message);
        } else {
            throw new IllegalArgumentException("Ndef format is NULL");
        }
    }
}
 
Example #6
Source File: GenericControlRecord.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
@Override
public NdefRecord getNdefRecord() {
	if(!hasTarget()) {
		throw new IllegalArgumentException("Expected target");
	}
	
	List<NdefRecord> records = new ArrayList<NdefRecord>();
	records.add(target.getNdefRecord());
	
	if (hasAction()) {
		records.add(action.getNdefRecord());
	}
	
	if (hasData()) {
		records.add(data.getNdefRecord());
	}
	
	byte[] array = new NdefMessage(records.toArray(new NdefRecord[records.size()])).toByteArray();
	
	byte[] payload = new byte[array.length + 1];
	payload[0] = configurationByte;
	System.arraycopy(array, 0, payload, 1, array.length);
	
	return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, type, id != null ? id : EMPTY, payload);
}
 
Example #7
Source File: NfcReadUtilityImpl.java    From android-nfc-lib with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public SparseArray<String> readFromTagWithSparseArray(Intent nfcDataIntent) {
    Parcelable[] messages = nfcDataIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    SparseArray<String> resultMap = messages != null ? new SparseArray<String>(messages.length) : new SparseArray<String>();

    if (messages == null) {
        return resultMap;
    }

    for (Parcelable message : messages) {
        for (NdefRecord record : ((NdefMessage) message).getRecords()) {
            byte type = retrieveTypeByte(record.getPayload());

            String i = resultMap.get(type);
            if (i == null) {
                resultMap.put(type, parseAccordingToType(record));
            }
        }
    }

    return resultMap;
}
 
Example #8
Source File: NfcWriteUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeGeolocationToTagFromIntent(Double latitude, Double longitude, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException {
    final NdefMessage ndefMessage = mNfcMessageUtility.createGeolocation(latitude, longitude);
    final Tag tag = retrieveTagFromIntent(intent);
    return writeToTag(ndefMessage, tag);
}
 
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: NdefWriteImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException {
    setReadOnly(true);
    boolean result = writeToNdef(message, ndef);
    setReadOnly(false);
    return result;
}
 
Example #11
Source File: NfcHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts a Long into a NdefMessage in application/vnd.facebook.places MIMEtype.
 * <p/>
 * for writing Places
 */
public static NdefMessage getAsNdef(String content) {
    byte[] textBytes = content.getBytes();
    NdefRecord textRecord = new NdefRecord(
            NdefRecord.TNF_MIME_MEDIA,
            "application/eu.power_switch".getBytes(),
            new byte[]{},
            textBytes);
    return new NdefMessage(new NdefRecord[]{
            textRecord,
            NdefRecord.createApplicationRecord("eu.power_switch")});
}
 
Example #12
Source File: NfcWriteUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeEmailToTagFromIntent(@NotNull String recipient, String subject, String message, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException {
    final NdefMessage ndefMessage = mNfcMessageUtility.createEmail(recipient, subject, message);
    final Tag tag = retrieveTagFromIntent(intent);
    return writeToTag(ndefMessage, tag);
}
 
Example #13
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 #14
Source File: NFCReadFragment.java    From android-nfc-tag-read-write with MIT License 5 votes vote down vote up
private void readFromNFC(Ndef ndef) {

        try {
            ndef.connect();
            NdefMessage ndefMessage = ndef.getNdefMessage();
            String message = new String(ndefMessage.getRecords()[0].getPayload());
            Log.d(TAG, "readFromNFC: "+message);
            mTvMessage.setText(message);
            ndef.close();

        } catch (IOException | FormatException e) {
            e.printStackTrace();

        }
    }
 
Example #15
Source File: InvoiceActivity.java    From android-sdk with MIT License 5 votes vote down vote up
@Override
public NdefMessage createNdefMessage(NfcEvent event) {

    if (mInvoice != null && mInvoice.getPaymentUrls() != null && mInvoice.getPaymentUrls().getBIP72b() != null) {
        return new NdefMessage(new NdefRecord[]{
                NdefRecord.createUri(mInvoice.getPaymentUrls().getBIP72())
        });
    }
    return null;
}
 
Example #16
Source File: NfcUtils.java    From WiFiKeyShare with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate an NDEF message containing the given Wi-Fi configuration
 *
 * @param wifiNetwork the Wi-Fi configuration to convert
 * @return an NDEF message containing the given Wi-Fi configuration
 */
public static NdefMessage generateNdefMessage(WifiNetwork wifiNetwork) {
    byte[] payload = generateNdefPayload(wifiNetwork);

    NdefRecord mimeRecord = new NdefRecord(
            NdefRecord.TNF_MIME_MEDIA,
            NfcUtils.NFC_TOKEN_MIME_TYPE.getBytes(Charset.forName("US-ASCII")),
            new byte[0],
            payload);
    NdefRecord aarRecord = NdefRecord.createApplicationRecord(PACKAGE_NAME);

    return new NdefMessage(new NdefRecord[] {mimeRecord, aarRecord});
}
 
Example #17
Source File: HiddenReceiverActivity.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
private String readNfcTagPayload(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    if (rawMsgs != null) {
        NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
        for (int i = 0; i < rawMsgs.length; i++) {
            msgs[i] = (NdefMessage) rawMsgs[i];
        }

        return new String(msgs[0].getRecords()[0].getPayload());
    }

    return null;
}
 
Example #18
Source File: ZannenNfcWriter.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
private NdefMessage getNoteAsNdef() {
	String dummy = "dummy";
    byte[] textBytes = dummy.toString().getBytes();
    NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),
            new byte[] {}, textBytes);
    return new NdefMessage(new NdefRecord[] {
        textRecord
    });
}
 
Example #19
Source File: HandoverSelectRecord.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
@Override
public NdefRecord getNdefRecord() {

	// implementation note: write alternative carriers and error record together
	List<NdefRecord> records = new ArrayList<NdefRecord>();
	
	if (hasAlternativeCarriers()) {

		// n alternative carrier records
		for(Record record : alternativeCarriers) {
			records.add(record.getNdefRecord());
		}
	}
	
	if (hasError()) {
		// an error message
		records.add(error.getNdefRecord());
	}
	
	byte[] subPayload = new NdefMessage(records.toArray(new NdefRecord[records.size()])).toByteArray();
	byte[] payload = new byte[subPayload.length + 1];

	// major version, minor version
	payload[0] = (byte)((majorVersion << 4) | minorVersion);
	System.arraycopy(subPayload, 0, payload, 1, subPayload.length);
	
	return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_HANDOVER_SELECT, id != null ? id : EMPTY, payload);
}
 
Example #20
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 #21
Source File: NFCTagReadWriteManager.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
private void readTagFromIntent(Intent intent) {
    if (intent != null){
        String action = intent.getAction();

        /*if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            uidRead = true;

            String uid = ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
            onTagReadListener.onUidRead(uid);
        }*/
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            tagRead = true;

            // get NDEF tag details
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                Ndef ndefTag = Ndef.get(tag);
                //int tagSize = ndefTag.getMaxSize();         // tag size
                tagIsWritable = ndefTag.isWritable();   // is tag writable?
                //String tagType = ndefTag.getType();            // tag type

                Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                if (rawMessages != null) {
                    NdefRecord[] records = ((NdefMessage) rawMessages[0]).getRecords();
                    String text = ndefRecordToString(records[0]);
                    onTagReadListener.onTagRead(text);
                }
            }
        }
    }
}
 
Example #22
Source File: BaseActivity.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    if (shareUrl != null) {
        return new NdefMessage(new NdefRecord[]{
                NdefRecord.createUri(shareUrl)
        });
    }
    return null;
}
 
Example #23
Source File: NfcSensor.java    From Cardboard with Apache License 2.0 5 votes vote down vote up
public CardboardDeviceParams getCardboardDeviceParams() {
	NdefMessage tagContents = null;
	synchronized (this.mTagLock) {
		try {
			tagContents = this.mCurrentTag.getCachedNdefMessage();
		} catch (Exception e) {
			return null;
		}
	}
	if (tagContents == null) {
		return null;
	}
	return CardboardDeviceParams.createFromNfcContents(tagContents);
}
 
Example #24
Source File: BeamShareData.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
@Override
public BeamShareData createFromParcel(Parcel source) {
    Uri[] uris = null;
    NdefMessage msg = source.readParcelable(NdefMessage.class.getClassLoader());
    int numUris = source.readInt();
    if (numUris > 0) {
        uris = new Uri[numUris];
        source.readTypedArray(uris, Uri.CREATOR);
    }
    UserHandle userHandle = source.readParcelable(UserHandle.class.getClassLoader());
    int flags = source.readInt();

    return new BeamShareData(msg, uris, userHandle, flags);
}
 
Example #25
Source File: ActivitySendIdentityByNfc.java    From ploggy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    try {
        String payload = Json.toJson(Data.getInstance().getSelf().mPublicIdentity);
        return new NdefMessage(
                new NdefRecord[] {
                        NdefRecord.createMime(NFC_MIME_TYPE, payload.getBytes()),
                        NdefRecord.createApplicationRecord(NFC_AAR_PACKAGE_NAME) });
    } catch (Utils.ApplicationError e) {
        Log.addEntry(LOG_TAG, "failed to create outbound NFC message");
    }
    return null;
}
 
Example #26
Source File: NdefImpl.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
/**
 * Read the current {@link android.nfc.NdefMessage} on this tag.
 *
 * <p>This always reads the current NDEF Message stored on the tag.
 *
 * <p>Note that this method may return null if the tag was in the
 * INITIALIZED state as defined by NFC Forum, as in that state the
 * tag is formatted to support NDEF but does not contain a message yet.
 *
 * <p>This is an I/O operation and will block until complete. It must
 * not be called from the main application thread. A blocked call will be canceled with
 * {@link IOException} if {@link #close} is called from another thread.
 *
 * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
 *
 * @return the NDEF Message, can be null
 * @throws TagLostException if the tag leaves the field
 * @throws IOException if there is an I/O failure, or the operation is canceled
 * @throws FormatException if the NDEF Message on the tag is malformed
 */
@Override
public NdefMessage getNdefMessage() throws IOException, FormatException {
    delegate.checkConnected();

    try {
        INfcTag tagService = delegate.getTag().getTagService();
        if (tagService == null) {
            throw new IOException("Mock tags don't support this operation.");
        }
        int serviceHandle = delegate.getTag().getServiceHandle();
        if (tagService.isNdef(serviceHandle)) {
            NdefMessage msg = tagService.ndefRead(serviceHandle);
            if (msg == null && !tagService.isPresent(serviceHandle)) {
                throw new TagLostException();
            }
            return msg;
        } else if (!tagService.isPresent(serviceHandle)) {
            throw new TagLostException();
        } else {
            return null;
        }
    } catch (RemoteException e) {
        Log.e(TAG, "NFC service dead", e);
        return null;
    }
}
 
Example #27
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Precondition : macAddress should not be null
 */
@Override
public NdefMessage createBluetoothAddress(@NotNull String macAddress) throws FormatException {
    byte[] payload = convertBluetoothToNdefFormat(macAddress);
    NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, NfcType.BLUETOOTH_AAR, null, payload);

    return new NdefMessage(record);
}
 
Example #28
Source File: NfcWriteUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean writeUriWithPayloadToTagFromIntent(@NotNull String urlAddress, byte payloadHeader, @NotNull Intent intent) throws FormatException, ReadOnlyTagException, InsufficientCapacityException, TagNotPresentException {
    NdefMessage ndefMessage = mNfcMessageUtility.createUri(urlAddress, payloadHeader);
    final Tag tag = retrieveTagFromIntent(intent);
    return writeToTag(ndefMessage, tag);
}
 
Example #29
Source File: NfcMessageUtilityImpl.java    From android-nfc-lib with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Precondition : At least recipient should not be null
 */
@Override
public NdefMessage createEmail(@NotNull String recipient, String subject, String message) throws FormatException {
    subject = (subject != null) ? subject : "";
    message = (message != null) ? message : "";
    String address = recipient + "?subject=" + subject + "&body=" + message;

    return createUriMessage(address, NfcPayloadHeader.MAILTO);
}
 
Example #30
Source File: Message.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
/**
 * Convert record to its byte-based {@link NdefMessage} representation. At least one record needs to be present.
 * 
 * @return record in {@link NdefMessage} form.
 * @throws IllegalArgumentException if zero records.
 */

public NdefMessage getNdefMessage() {
	NdefRecord[] ndefRecords = new NdefRecord[size()];
	for(int i = 0; i < ndefRecords.length; i++) {
		ndefRecords[i] = get(i).getNdefRecord();
	}
	return new NdefMessage(ndefRecords);
}