write NFC Tag to NdefMessage - Android Network

Android examples for Network:NFC Message

Description

write NFC Tag to NdefMessage

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 {
    public static boolean writeTag(NdefMessage message, Tag tag) {
        int size = message.toByteArray().length;

        try {//from w ww .  j a  v a 2 s  .c  o m
            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 formatable = NdefFormatable.get(tag);
                if (formatable != null) {
                    try {
                        formatable.connect();
                        formatable.format(message);
                        return true;
                    } catch (IOException e) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }
    }
}

Related Tutorials