Creates a custom MIME type encapsulated in an NDEF record for a given payload - Android Network

Android examples for Network:NFC Record

Description

Creates a custom MIME type encapsulated in an NDEF record for a given payload

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import android.nfc.NdefRecord;

public class Main {
    /**/*from   w  w  w .ja  va2  s  .c o m*/
     * Creates a custom MIME type encapsulated in an NDEF record for a given
     * payload
     * 
     * @param mimeType
     */
    public static NdefRecord createRecord(String mimeType, byte[] payload) {
        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
        NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                mimeBytes, new byte[0], payload);
        return mimeRecord;
    }

    private static NdefRecord createRecord(String text)
            throws UnsupportedEncodingException {

        //create the message in according with the standard
        String lang = "en";
        byte[] textBytes = text.getBytes();
        byte[] langBytes = lang.getBytes("US-ASCII");
        int langLength = langBytes.length;
        int textLength = textBytes.length;

        byte[] payload = new byte[1 + langLength + textLength];
        payload[0] = (byte) langLength;

        // copy langbytes and textbytes into payload
        System.arraycopy(langBytes, 0, payload, 1, langLength);
        System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);

        NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_TEXT, new byte[0], payload);
        return recordNFC;
    }
}

Related Tutorials