write Uri To NFC NdefFormatable Tag - Android Network

Android examples for Network:NFC Tag

Description

write Uri To NFC NdefFormatable Tag

Demo Code


import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Build;
import java.io.IOException;

public class Main{
    private static boolean writeUriToNdefFormatableTag(
            NdefFormatable ndefFormatableTag, Uri uri, String appPackage) {
        final NdefMessage msg = obtainNdefMessage(uri, appPackage);

        try {//from www . j  av a 2  s . co  m
            ndefFormatableTag.connect();
            ndefFormatableTag.format(msg);
            ndefFormatableTag.close();

            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        } finally {
            try {
                ndefFormatableTag.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }
    private static NdefMessage obtainNdefMessage(Uri uri, String appPackage) {
        final int recordCount = ((appPackage != null) ? 2 : 1);
        final NdefRecord[] records = new NdefRecord[recordCount];
        records[0] = NdefRecordCompatUtils.createUri(uri);

        if (appPackage != null) {
            records[1] = NdefRecordCompatUtils
                    .createApplicationRecord(appPackage);
        }

        return new NdefMessage(records);
    }
}

Related Tutorials