Creates an Ndef message - Android Network

Android examples for Network:NFC Message

Description

Creates an Ndef message

Demo Code


//package com.java2s;

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

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;

public class Main {
    /**// ww w  . j a v  a2 s.  c  o  m
     * Creates an Ndef message
     * 
     * @param payload
     * @return
     */
    public static NdefMessage createMessage(String mimeType, byte[] payload) {
        // Min API Level of 14 requires an array as the argument
        return new NdefMessage(new NdefRecord[] { createRecord(mimeType,
                payload) });
    }

    /**
     * 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