Android NFC Reader: Read Data from NFC Tags

Learn how to read NFC data in your Android app! This guide covers NFC basics, code examples, and steps to build an NFC reader for your Android projects.

Android NFC Reader: Read Data from NFC Tags

NFC (Near Field Communication) technology has revolutionized mobile payments, smart cards, and the Internet of Things (IoT). Android devices, with built-in NFC capabilities, can seamlessly interact with other NFC-enabled devices. This blog post will guide you through implementing NFC data reading in your Android application, providing code examples, sequence diagrams, and state diagrams.

Android NFC Reader: Read Data from NFC Tags
Android NFC Reader: Read Data from NFC Tags

NFC and Android

NFC reader is a short-range wireless communication technology, typically operating within a 4cm range. It’s commonly used for payments, access control, and authentication. Android devices utilize the NFC adapter to read data from NFC tags. Here are some core components related to NFC in Android:

  • NfcAdapter: The primary class for managing NFC functionality.
  • NfcAdapter.enableForegroundDispatch(): Activates foreground dispatch, enabling your app to receive NFC messages when it’s in the foreground.
  • PendingIntent: Used to set the intent triggered upon NFC tag scanning.
  • NdefMessage: Represents the NFC data format (e.g., text, URI) message.

Implementation Steps for Reading NFC Data

1. Check for NFC Support

First, verify that the device supports NFC. Use the following code:

NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
    // Device doesn't support NFC
    Toast.makeText(this, "This device doesn't support NFC", Toast.LENGTH_SHORT).show();
    finish();
}

content_copydownloadUse code with caution.Java

2. Create a PendingIntent

Create a PendingIntent that launches your app and calls the relevant callback when an NFC tag is scanned:

PendingIntent pendingIntent = PendingIntent.getActivity(
        this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

content_copydownloadUse code with caution.Java

3. Enable Foreground Dispatch

Enable foreground dispatch using enableForegroundDispatch() to receive NFC data when the app is in the foreground. This triggers the corresponding operations when the user brings an NFC tag close to the device.

@Override
protected void onResume() {
    super.onResume();
    nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}

@Override
protected void onPause() {
    super.onPause();
    nfcAdapter.disableForegroundDispatch(this);
}

content_copydownloadUse code with caution.Java

4. Handle NFC Data

In the onNewIntent method, process the read NFC data. Here’s an example:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMessages != null) {
            // Process NFC message
            NdefMessage[] messages = new NdefMessage[rawMessages.length];
            for (int i = 0; i < rawMessages.length; i++) {
                messages[i] = (NdefMessage) rawMessages[i];
                readNdefMessage(messages[i]);
            }
        }
    }
}

private void readNdefMessage(NdefMessage message) {
    for (NdefRecord record : message.getRecords()) {
        // Process specific NFC record here
        String payload = new String(record.getPayload());
        Log.d("NFC", "Data read: " + payload);
    }
}

content_copydownloadUse code with caution.Java

Android NFC Reader: Read Data from NFC Tags
Android NFC Reader: Read Data from NFC Tags

5. Running the Application

When a user brings an NFC tag near the device, the application will read the data from the tag and display it in the logs. In a real-world application, you can display this data in the user interface or use it for subsequent logic processing.

Sequence Diagram

sequenceDiagram
    participant Android App
    participant Android NFC Device
    participant User
    User->Android NFC Device: Approaches NFC Tag
    Android NFC Device->Android App: ACTION_NDEF_DISCOVERED
    Android App->Android App: onNewIntent()
    Android App->Android App: Process NFC Data
    Android App->Android App: Display Read Results

content_copydownloadUse code with caution.Mermaid

State Diagram

stateDiagram
    [*] --> Idle
    Idle --> NFC_Detected: NFC Tag Detected
    NFC_Detected --> Processing: Processing NFC Data
    Processing --> Result: Data Processing Complete
    Result --> Idle:

content_copydownloadUse code with caution.Mermaid

Conclusion

By following these steps, you can implement NFC data reading in your Android applications. NFC technology offers numerous conveniences, from payments to authentication, and its applications are constantly expanding. Understanding and mastering NFC usage can enrich your application’s functionality and provide a better user experience.

In practical development, you can explore advanced features such as NFC writing operations, data encryption, and integration with backend services. This article aims to help you understand Android NFC technology and apply it to real-world projects, creating greater value.

Share your love
posterminal
posterminal