Write an NDEF message to a Tag for NFC - Android Network

Android examples for Network:NFC Message

Description

Write an NDEF message to a Tag for NFC

Demo Code


//package com.java2s;
import java.io.IOException;

import android.nfc.NdefMessage;

import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;

import android.util.Log;

public class Main {
    private static final String LOG_TAG = "NfcUtils";

    /**//www  . j  a va 2s. c o m
     * Write an NDEF message to a Tag
     * 
     * @param message
     * @param tag
     * @return true if successful, false if not written to
     */
    public static boolean writeTag(NdefMessage message, Tag tag) {
        int size = message.toByteArray().length;
        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();
                if (!ndef.isWritable()) {
                    Log.e(LOG_TAG,
                            "Not writing to tag- tag is not writable");
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    Log.e(LOG_TAG,
                            "Not writing to tag- message exceeds the max tag size of "
                                    + ndef.getMaxSize());
                    return false;
                }
                ndef.writeNdefMessage(message);
                return true;
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);
                        return true;
                    } catch (IOException e) {
                        Log.e(LOG_TAG, "Not writing to tag", e);
                        return false;
                    }
                } else {
                    Log.e(LOG_TAG, "Not writing to tag- undefined format");
                    return false;
                }
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Not writing to tag", e);
            return false;
        }
    }
}

Related Tutorials