write Uri To NFC Ndef Tag - Android Network

Android examples for Network:NFC Tag

Description

write Uri To NFC Ndef 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 writeUriToNdefTag(Ndef ndefTag, Uri uri,
            String appPackage) {/*from  ww  w  . jav a  2 s . c  o m*/
        final NdefMessage msg = obtainNdefMessage(uri, appPackage);

        try {
            ndefTag.connect();
            ndefTag.writeNdefMessage(msg);
            ndefTag.close();

            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        } finally {
            try {
                ndefTag.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