Writes an NdefMessage to a NFC tag - Android Network

Android examples for Network:NFC Message

Description

Writes an NdefMessage to a NFC tag

Demo Code


//package com.java2s;

import android.nfc.NdefMessage;

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

import java.io.IOException;

public class Main {
    /**//w ww  .j  av  a 2s  . c  om
     * Writes an NdefMessage to a NFC tag
     *
     * @param message that should be written to the tag.
     * @param tag     discovered tag.
     * @return flag that tells if the message was successfully written to the tag.
     */
    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()) {
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    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) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }
    }
}

Related Tutorials