How to enable NFC on your android app and read a TAG

First of all you need to enable the NFC beam on your AndroidManifest.xml:


<uses-permission android:name="android.permission.NFC"/>

<!-- Use the required="true" if your application will not function properly unless the device HAS an NFC hardware-->
 <uses-feature android:name="android.hardware.nfc" android:required="true"/>

 

Now on your activity read the tag:


Intent nfcIntent = new Intent(this, ReadNFC.class); //The ReadNFC class is where you will process the discovered tag.

PendingIntent pi = PendingIntent.getActivity(this, 0, nfcIntent, 0);

NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);

//If the device´s NFC is either disabled or unathorized the adapter will return null,

// I put a simple warning here, but you could do some fancy coding.

if(nfcAdapter!=null)
nfcAdapter.enableForegroundDispatch(this, pi, new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)}, null);
 else {
findViewById(R.id.statusNFC).setVisibility(TextView.VISIBLE);
 }

 

That´s it!

Thanks for reading.

Advertisements