Method that parses Intent to get NFC ID - Android Network

Android examples for Network:NFC

Description

Method that parses Intent to get NFC ID

Demo Code


//package com.java2s;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;

public class Main {
    /**//from  ww w. j a v a  2 s. c o  m
     * <p>
     * Method that parses
     * </p>
     * 
     * @note Mayby can be simplified/shortened with NfcAdapter.EXTRA_ID (Maybe)
     * @example
     * @reference
     * 
     * @author Lauri Vene
     * @since 0.5
     * 
     * @history
     * 
     * @param nfcIntent   is the intent that was caught in ACTION_TAG_DISCOVERY
     * @return   hexadecimal formatted ID for TAG 
     * 
     * @modifies no?
     * @precondition
     * @postcondition
     */
    public static String getUidFromIntent(Intent nfcIntent) {
        Bundle extra = nfcIntent.getExtras();
        String text = "";
        try {
            Tag t = (Tag) extra.get(NfcAdapter.EXTRA_TAG);
            byte[] uid = t.getId();
            text = getHexString(uid);
        } catch (Exception e) {
            Log.e("NFC", "could not get uid from tag");
        }
        return text;
    }

    /**
     * <p>
     * Parses Tag id from byte[] and formats it to hexadecimal format.
     * Leading zeros will be included in this value
     * </p>
     * 
     * @note
     * @example
     * @reference
     * 
     * @author Lauri Vene
     * @since 0.5
     * 
     * @history
     * 
     * @param
     * @return
     * 
     * @modifies no
     * @precondition
     * @postcondition
     */
    private static String getHexString(byte[] data) {
        String result = "";
        for (int i = 0; i < data.length; i++) {
            result += Integer.toString((data[i] & 0xFF) + 0x100, 16)
                    .substring(1);
        }
        return result;
    }
}

Related Tutorials