Kotlin Functions

 

The Future of Contactless Interaction: Dive Deep into Kotlin & NFC

Near Field Communication (NFC) has opened the doors to countless innovative applications. From contactless payments to smart posters, NFC has reshaped the way devices communicate in close proximity. However, integrating NFC into your Android apps using Kotlin can seem daunting, especially if you’re new to both. Fear not! In this article, we’ll demystify the process of implementing NFC using Kotlin.

The Future of Contactless Interaction: Dive Deep into Kotlin & NFC

1. Introduction to NFC

Near Field Communication (NFC) is a short-range wireless technology that enables communication between devices when they’re just a few centimeters apart. The common uses include:

– Mobile payments (like Google Pay)

– Information sharing (e.g., vCards)

– Electronic ticketing

– Smart posters

2. Checking NFC Capabilities

Before diving into NFC operations, your app should check if the device supports NFC and if it’s enabled:

```kotlin
val nfcAdapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(this)

if (nfcAdapter == null) {
    // Device doesn't support NFC
} else {
    if (!nfcAdapter.isEnabled) {
        // NFC is disabled
    } else {
        // NFC is available and enabled
    }
}
```

3. Reading NFC Tags

Most basic NFC operations involve reading a tag. Here’s a simple way to do it:

1. Define the NFC Intent Filter

To detect NFC intents, you’ll need to define intent filters in your AndroidManifest.xml:

```xml
<activity
    android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>
```

This filter allows your activity to be notified when a plain text NFC tag is discovered.

2. Handle the Intent in your Kotlin Activity

When an NFC tag is detected, the `onNewIntent` method is called:

```kotlin
override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)

    if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent?.action) {
        val rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
        val messages: List<NdefMessage> = rawMessages.map { it as NdefMessage }
        val payload = messages[0].records[0].payload
        val text = String(payload)
        // Handle the text data here
    }
}
```

4. Writing to NFC Tags

While reading is relatively simple, writing requires a bit more care:

1. Create an NDEF Message

To write data to a tag, first create an NDEF (NFC Data Exchange Format) message:

```kotlin
val text = "Hello, NFC!"
val record = NdefRecord.createMime("text/plain", text.toByteArray(Charset.forName("US-ASCII")))
val message = NdefMessage(arrayOf(record))
```

2. Write to the Tag

To write the message to a discovered tag:

```kotlin
val nfcAdapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(this)

val tag: Tag? = intent?.getParcelableExtra(NfcAdapter.EXTRA_TAG)
val ndef = Ndef.get(tag)

ndef?.let {
    it.connect()
    it.writeNdefMessage(message)
    it.close()
}
```

Remember to handle exceptions appropriately, as writing to a tag can fail for various reasons (tag removed during write, insufficient storage, etc.).

5. Advanced Usage: Peer-to-Peer Mode

NFC is not limited to tag reading and writing. Devices can communicate directly using Android Beam, which was deprecated in Android 10, or its successor, Nearby.

```kotlin
val nfcAdapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(this)

nfcAdapter?.setNdefPushMessageCallback({ _, _ ->
    val text = "Hello from device!"
    val record = NdefRecord.createMime("text/plain", text.toByteArray(Charset.forName("US-ASCII")))
    NdefMessage(arrayOf(record))
}, this)
```

Conclusion

NFC offers a wide array of possibilities for mobile apps, from the mundane to the futuristic. Kotlin, with its concise and expressive syntax, makes working with NFC on Android more straightforward. Whether you’re building the next mobile payment solution or simply dabbling in wireless communications, Kotlin and NFC are tools you’ll want in your arsenal. Happy coding!

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.