Android NFC Reader Mode: A Step-by-Step Guide

Learn how to implement NFC reader mode in your Android app! This guide covers permissions, adapter setup, intent handling, and data exchange for NFC tag reading.

Android NFC Reader Mode: A Step-by-Step Guide
Android NFC Reader Mode: A Step-by-Step Guide

Implementing Android NFC Reader Mode: A Developer’s Guide

Near Field Communication (NFC) is a powerful technology for mobile applications, enabling contactless interactions. This guide focuses on implementing NFC reader mode in Android.

Overall Process

StepDescription
1Create an Android project and add NFC permissions and features.
2Initialize the NFC adapter.
3Register for NFC tag discovery.
4Define the NFC tag reading logic.
5Handle data exchange with NFC tags.
6Test the application.

Detailed Steps:

1. Create Project & Add NFC Permissions

In Android Studio, create a new project. Add the following to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.NFC"/>
<uses-feature android:name="android.hardware.nfc" android:required="true"/>

  • uses-permission: Declares that your app needs NFC access.
  • uses-feature: Specifies that the app requires NFC and should only be available on NFC-enabled devices.

2. Initialize the NFC Adapter

In your main Activity’s onCreate() method, get an instance of the NFC adapter:

import android.nfc.NfcAdapter;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private NfcAdapter nfcAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (nfcAdapter == null) {
            // Device doesn't support NFC
            Toast.makeText(this, "NFC is not supported on this device.", Toast.LENGTH_SHORT).show();
            finish(); // Close app
        }
    }
}

  • NfcAdapter.getDefaultAdapter(this): Retrieves the NFC adapter.
  • Error handling is crucial to gracefully handle cases where NFC isn’t available.

3. Register for NFC Tag Discovery

Register a PendingIntent to handle NFC tag discovery in onResume() and disable it in onPause():

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;

@Override
protected void onResume() {
    super.onResume();

    if (nfcAdapter != null) {
        Intent intent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,  PendingIntent.FLAG_MUTABLE);
        IntentFilter[] filters = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)};
        String[][] techList = null; //  {new String[] { NfcF.class.getName() }};
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, techList);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (nfcAdapter != null) {
        nfcAdapter.disableForegroundDispatch(this);
    }
}

  • enableForegroundDispatch(): Registers your activity to be the preferred receiver for NFC intents when it’s in the foreground.
  • disableForegroundDispatch(): Unregisters the activity when it’s no longer in the foreground.
  • PendingIntent.FLAG_MUTABLE: add this flag for targetSdkVersion >= 31

4. Define NFC Tag Reading Logic

Override onNewIntent() to handle the discovered NFC tag:

import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag != null) {
            readNfcTag(tag);
        }
    }
}

  • getParcelableExtra(NfcAdapter.EXTRA_TAG): Extracts the NFC tag object from the intent.

5. Handle Data Exchange

Implement the readNfcTag() method to read data from the tag:

import android.nfc.Tag;
import android.widget.Toast;

private void readNfcTag(Tag tag) {
    // Implement your tag reading logic here.
    // For example, get the tag ID:
    byte[] tagId = tag.getId();
    String tagIdString = bytesToHexString(tagId); // Convert byte array to hex string

    Toast.makeText(this, "NFC Tag ID: " + tagIdString, Toast.LENGTH_LONG).show();

    //Further tag processing will go here.
}

private String bytesToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}

  • This example shows how to get the Tag ID and convert it to Hex String. More advanced implementations would involve reading NDEF messages.
Android NFC Reader Mode: A Step-by-Step Guide
Android NFC Reader Mode: A Step-by-Step Guide

6. Test the Application

Build and run the app. Ensure NFC is enabled on your device. Bring an NFC tag near the device to trigger the onNewIntent method and your tag reading logic.

Teile deine Liebe
posterminal
posterminal