Android SharedPreferences Tutorial and Example

Reading RFID Tags With Android

Radio-frequency identification lets an Android device identify nearby objects, products or access tokens without a camera or printed barcode. For mobile developers, the first distinction matters: most Android phones read NFC tags, which are a short-range form of RFID, while long-range UHF RFID usually requires a dedicated reader connected through Bluetooth, USB or a manufacturer SDK.

A practical application might scan equipment in a Sydney workshop, verify stock in a Melbourne shop or record event badges in Brisbane. This tutorial explains the Android APIs, tag technologies, permissions and storage decisions behind a reliable reader, with examples suitable for a small SQLite-backed project or a larger inventory system.

NFC And UHF RFID Are Different

NFC operates at 13.56 MHz and normally requires the phone to be within a few centimetres of the tag. Common NFC tags use technologies such as NfcA, NfcB, NfcF, NfcV and IsoDep. They can store NDEF records containing text, URLs, contact data or application-specific payloads. Android phones generally include an NFC controller, although hardware availability varies by model.

UHF RFID is designed for longer read distances and can identify many tags rapidly. Australian warehouses and retail operations may use UHF readers around the 920–926 MHz allocation, subject to Australian Communications and Media Authority requirements. A standard smartphone cannot replace this reader; an Android application must communicate with the reader’s Bluetooth or USB interface and handle its proprietary SDK.

Preparing The Android Project

Declare NFC support in AndroidManifest.xml. If the application cannot function without NFC, use android:required="true"; otherwise, leave it false so users on tablets or budget phones can still install the app.

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

The NFC permission is a normal manifest declaration rather than a runtime permission. In an activity, obtain the adapter and check both the device and its current setting. A phone carried through a busy Sydney commute may have NFC disabled to save battery or avoid accidental interactions, so the interface should explain how to enable it rather than failing silently.

private lateinit var nfcAdapter: NfcAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    nfcAdapter = NfcAdapter.getDefaultAdapter(this)

    if (nfcAdapter == null) {
        showMessage("This device does not support NFC")
    } else if (!nfcAdapter.isEnabled) {
        showMessage("Enable NFC in Settings")
    }
}

Choosing A Tag Reading Mode

For a simple application, foreground dispatch is easy to understand. The activity creates an IntentFilter for NFC discovery and receives a new intent when the user taps a tag. This is suitable for a screen that says “Tap an asset tag”, especially when the user scans one item at a time.

Reader mode is usually cleaner for dedicated scanning screens. It reduces competing system behaviour and delivers a Tag object to a callback while the activity is active. It is available from Android 4.4, making it appropriate for current Australian phones while still supporting many older devices.

private val readerCallback = NfcAdapter.ReaderCallback { tag ->
    val id = tag.id.joinToString("") { byte ->
        "%02X".format(byte)
    }

    runOnUiThread {
        idTextView.text = id
    }
}

override fun onResume() {
    super.onResume()
    nfcAdapter.enableReaderMode(
        this,
        readerCallback,
        NfcAdapter.FLAG_READER_NFC_A or
            NfcAdapter.FLAG_READER_NFC_B or
            NfcAdapter.FLAG_READER_NFC_V,
        null
    )
}

override fun onPause() {
    super.onPause()
    nfcAdapter.disableReaderMode(this)
}

Always disable reader mode when the activity pauses. Otherwise, a background screen may continue receiving scans or interfere with another application. If an application must read a secure transport card, do not assume that access to the card’s UID grants access to its protected travel data; systems such as Sydney’s Opal and Melbourne’s myki use controlled protocols and are not ordinary writable NFC tags.

Parsing NDEF Records Safely

An NFC tag may expose an Ndef technology, but it may also contain only a hardware identifier or use a different protocol. Check the technology before connecting, set a sensible timeout, and close the connection in a finally block.

fun readNdef(tag: Tag): String? {
    val ndef = Ndef.get(tag) ?: return null

    return try {
        ndef.connect()
        val message = ndef.ndefMessage ?: return null
        message.records.joinToString("\n") { record ->
            String(record.payload, Charsets.UTF_8)
        }
    } catch (error: IOException) {
        null
    } finally {
        try {
            if (ndef.isConnected) ndef.close()
        } catch (_: IOException) {
        }
    }
}

Payload parsing needs care. A URI record can include a prefix byte, a text record may contain a language-code length, and arbitrary manufacturer data may not be UTF-8 at all. Treat the payload as untrusted input: limit its size, validate URLs, reject unexpected commands and display malformed bytes safely. A background coroutine or executor should perform I/O so the user interface remains responsive.

Saving Scans And Protecting Personal Data

A scan record commonly contains the tag identifier, timestamp, operator, location, tag type and optional payload. SQLite is a useful local store when users need search, duplicate detection and offline operation. Store timestamps in UTC, then format them for the device’s local timezone. This avoids confusion when stock moves between Perth, Adelaide and the east coast.

A tag ID is not automatically anonymous. If it identifies a worker, customer, student or household, it may become personal information when combined with an account or location. The Australian Privacy Act 1988 and the Australian Privacy Principles can affect collection, notice, retention and disclosure. Tell users what the scan records, restrict access, encrypt sensitive local data and delete records when the business purpose ends.

For field teams that work without reliable connectivity, queue records locally and upload them after authentication. If an audit archive must be transferred between devices, a ZIP storage guide can help when packaging exported JSON or CSV files, though compression is not encryption. Protect archives with an appropriate encryption method and avoid placing secrets in filenames or plain metadata.

Testing In Australian Conditions

Test with several tag types rather than one cheap sample tag. Check blank NDEF tags, read-only tags, tags with corrupted records and tags that use a technology your app does not support. Test the phone in a protective case, because thick wallets and metal-backed cases can reduce the reading range.

Real workflows matter more than a desk demonstration. Try repeated scans in a noisy warehouse near Melbourne, poor connectivity at a regional site and bright outdoor use at a Queensland event. Australian retailers and logistics providers may already have UHF inventory infrastructure, so confirm whether your application is reading individual NFC labels or integrating with a Bluetooth RFID sled.

Avoid treating a tag ID as proof that an item is genuine. IDs can sometimes be copied, and an unlocked NDEF record can be rewritten. For valuable equipment, combine the scan with server-side ownership checks, signed data or a second verification step. Also record failed scans and connection errors, since those logs reveal whether the problem is the tag, reader distance, permissions or network.

NFC And Dedicated RFID In Practice

The following comparison helps select an implementation before writing the user interface or database layer.

Capability Android NFC Dedicated UHF RFID reader
Typical range A few centimetres Several metres, depending on hardware and environment
Common use Tap-to-read labels, pairing, small records Warehouse inventory and multiple-item scans
Android connection Built into the phone Bluetooth, USB or vendor SDK
Typical tag standards NDEF, ISO 14443, ISO 15693 EPC Gen2 / UHF protocols
Scan pattern Usually one deliberate tap Many tags in a reading field
Main design concern Technology and payload parsing Reader configuration, battery and duplicate filtering

For a classroom project or a small asset register, NFC and NfcAdapter provide the shortest path from a tap to a saved database row. For pallet counting or shop-floor stocktaking, select a compatible UHF reader first, then build an Android integration around its documented API. Keeping those use cases separate prevents an application from promising long-range RFID behaviour that the phone’s NFC hardware cannot deliver.