format NFC Tech Tag - Android Network

Android examples for Network:NFC Tag

Description

format NFC Tech Tag

Demo Code


//package com.java2s;
import java.io.IOException;

import java.nio.charset.Charset;

import android.content.Intent;

import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;

import android.nfc.tech.NdefFormatable;

import android.util.Log;

public class Main {
    private static final String TAG = "NfcFilter";

    public static boolean formatTechTag(Intent intent) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        NdefFormatable format = NdefFormatable.get(tag);

        if (format != null) {
            try {
                format.connect();//w w  w .  j a v a2  s.c  om
                NdefMessage msg = new NdefMessage(createTextRecord(""));
                format.format(msg);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (FormatException e) {
                Log.w(TAG, "", e);
            }
        }
        return false;
    }

    public static NdefRecord createTextRecord(String payload) {

        Charset utfEncoding = Charset.forName("UTF-8");
        byte[] textBytes = payload.getBytes(utfEncoding);
        NdefRecord ndefRecord = null;

        ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_TEXT, new byte[0], textBytes);
        return ndefRecord;
    }
}

Related Tutorials