Create new NFC Uri Record - Android Network

Android examples for Network:NFC Record

Description

Create new NFC Uri Record

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import android.net.Uri;

import android.nfc.NdefRecord;
import android.util.Pair;

public class Main {
    public static NdefRecord newUriRecord(Uri uri) throws IOException {

        List<Pair<String, Integer>> prefixList = new ArrayList<Pair<String, Integer>>();
        prefixList.add(Pair.create("http://www.", 0x01));
        prefixList.add(Pair.create("https://www.", 0x02));
        prefixList.add(Pair.create("http://", 0x03));
        prefixList.add(Pair.create("https://", 0x04));
        prefixList.add(Pair.create("tel:", 0x05));
        prefixList.add(Pair.create("mailto:", 0x06));

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        for (Pair<String, Integer> pair : prefixList) {
            if (newUriRecordSub(os, uri, pair.first, pair.second)) {
                break;
            }/*from w w  w .j a  va 2 s .c o m*/
        }
        if (os.size() == 0) {
            newUriRecordSub(os, uri, "", 0x00);
        }

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_URI, new byte[] {}, os.toByteArray());
    }

    static boolean newUriRecordSub(ByteArrayOutputStream os, Uri uri,
            String prefix, int code) throws IOException {
        if (uri.toString().startsWith(prefix)) {
            os.write(code);
            os.write(uri.toString().substring(prefix.length())
                    .getBytes(Charset.forName("UTF-8")));
            return true;
        } else {
            return false;
        }
    }
}

Related Tutorials