NFC Tag Connectivity + Wearable Watch Communication

NFC Tag Connectivity and Wearable Watch Communication


1. NFC Tag Connectivity
2. Wearable Watch / Wear OS Communication

By the end of Day 2, you should be able to explain:

- What is NFC?
- How Android reads NFC tags
- What is NDEF?
- NFC use cases
- NFC implementation flow
- What is Wear OS phone-watch communication?
- Why Wear OS uses Data Layer instead of raw Bluetooth socket
- MessageClient, DataClient, Asset, CapabilityClient
- Pros, cons, comparisons, diagrams, and interview answers

---

Part 1: NFC Tag Connectivity

1. What is NFC?

NFC means Near Field Communication.

It is a short-range wireless technology. It works when the phone is very close to another NFC device or NFC tag.

Simple meaning:

NFC = tap phone near tag and read/write small data

Example:

Phone touches NFC tag
        |
Phone reads tag data
        |
App opens product/user/details screen

Android’s NFC documentation explains NFC tasks such as sending and receiving data using NDEF messages, which is the common format for NFC tag data in Android.

---

2. Real-Life NFC Examples

Tap metro card
Tap office ID card
Tap payment card
Tap product tag
Tap hotel room card
Tap warehouse asset tag
Tap NFC sticker to open app screen

---

3. NFC Use Cases for Android Developer

Use CaseExample
Product informationTap product tag and open product details
AttendanceEmployee taps ID card
WarehouseTap asset tag to identify item
Deep linkTap NFC tag and open app screen
Device setupTap tag to configure Wi-Fi/IoT device
Access controlTap card to validate access
Smart posterTap poster and open URL/app
Inventory appTap NFC label attached to box/item

---

4. NFC Basic Flow

User taps NFC tag
        |
Android system detects tag
        |
Android reads tag data
        |
Android checks which app can handle it
        |
App receives intent
        |
App reads NDEF message
        |
App extracts data
        |
App performs action

---

5. NFC Diagram

NFC Tag
   |
   | tap
   v
Android Phone
   |
NFC Adapter
   |
Android NFC Dispatch System
   |
Your Activity
   |
Read NDEF Data
   |
Show result / Navigate screen

---

6. What is NFC Tag?

An NFC tag is a small chip that can store small data.

Examples of stored data:

Text
URL
Product ID
Employee ID
Deep link
Wi-Fi configuration
Custom JSON

Example tag data:

{
  "productId": "P1001",
  "name": "Bluetooth Scanner",
  "location": "Warehouse A"
}

---

7. What is NDEF?

NDEF means NFC Data Exchange Format.

It is a standard format used to store data on NFC tags.

Simple meaning:

NDEF = standard format to store NFC tag data

NDEF structure:

NDEF Message
   |
   +-- NDEF Record 1
   +-- NDEF Record 2
   +-- NDEF Record 3

---

8. NDEF Message and NDEF Record

NDEF Message

An NDEF message is a container.

NDEF Record

An NDEF record is the actual data item.

Example:

NDEF Message
   |
   +-- Record 1: Text = "Product ID 101"
   +-- Record 2: URL = "https://example.com/product/101"

Simple memory:

NDEF Message = Box
NDEF Record  = Item inside box

---

9. NFC Dispatch System

When an NFC tag is scanned, Android decides which app should open.

Android checks NFC intents in this order:

1. ACTION_NDEF_DISCOVERED
2. ACTION_TECH_DISCOVERED
3. ACTION_TAG_DISCOVERED

Simple meaning:

First Android tries to find app based on NDEF data.
If not found, it checks tag technology.
If still not found, it sends a generic tag intent.

Android’s tag API notes that NDEF is the preferred way to handle tag data because it can be stored on many tag types and is not tied to one specific tag technology.

---

10. NFC Intent Types

IntentMeaning
ACTION_NDEF_DISCOVEREDTag contains NDEF data
ACTION_TECH_DISCOVEREDTag technology is matched
ACTION_TAG_DISCOVEREDGeneric fallback tag intent

---

11. NFC Manifest Permission

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

Declare NFC hardware feature:

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

Use required="false" when the app can work without NFC.

Use required="true" when NFC is mandatory.

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

Interview line:

If NFC is optional, I use required=false and check NFC availability at runtime.
If NFC is mandatory, I use required=true.

---

12. NFC Activity Intent Filter

Example: App wants to handle plain text NFC tag.
<activity
    android:name=".NfcActivity"
    android:exported="true">

    <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>

---

13. NFC Implementation Flow in Android

1. Add NFC permission
2. Add NFC feature
3. Create Activity to handle NFC
4. Add intent filter
5. User taps NFC tag
6. Android launches Activity
7. Read intent action
8. Extract NDEF messages
9. Read NDEF records
10. Parse payload
11. Use data in app

---

14. NFC Read Pseudocode

class NfcActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        handleNfcIntent(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)

        handleNfcIntent(intent)
    }

    private fun handleNfcIntent(intent: Intent) {
        if (intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) {

            val rawMessages =
                intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)

            rawMessages?.forEach { rawMessage ->
                val ndefMessage = rawMessage as NdefMessage

                ndefMessage.records.forEach { record ->
                    val payload = record.payload
                    val data = payload.decodeToString()

                    Log.d("NFC", "NFC Data: $data")
                }
            }
        }
    }
}

---

15. NFC Foreground Dispatch

What is Foreground Dispatch?

Foreground Dispatch allows the currently opened app screen to get NFC tag data first.

Simple meaning:

If my app screen is open, give NFC tag data to my app first.

Use case:

Warehouse app screen is open
        |
User taps product NFC tag
        |
Same screen receives tag
        |
App shows product details

Android’s advanced NFC documentation explains foreground dispatch as a way for a foreground application to handle NFC intents even when other apps also filter for the same tag types.

---

16. NFC Reader Mode

What is Reader Mode?

Reader Mode is used when your app screen is actively reading NFC tags.

Simple meaning:

Reader Mode = app actively waits for NFC tag scan

Use case:

Open "Scan NFC Tag" screen
        |
App enables reader mode
        |
User taps tag
        |
App directly reads tag

---

17. Foreground Dispatch vs Reader Mode

TopicForeground DispatchReader Mode
MeaningForeground app gets NFC intent firstApp actively reads NFC tags
StyleIntent-basedCallback-based
Use caseExisting activity should receive tagDedicated NFC scan screen
App stateApp must be foregroundApp must be foreground
ComplexityMediumCleaner for active scanning

---

18. NFC Pros and Cons

Pros

ProsExplanation
Simple user actionUser only taps tag
FastSmall data can be read quickly
Good for identificationProduct ID, employee ID, asset ID
Passive tags possibleSome tags do not need battery
Useful for deep linksCan open specific app screen

Cons

ConsExplanation
Very short rangePhone must be very close
Small data onlyNot for large data transfer
Hardware requiredNot all devices may support NFC
Tag compatibilityDifferent tag types exist
Security riskTags can be cloned or modified if not protected

---

19. NFC Best Practices

1. Check NFC availability at runtime.
2. Check if NFC is enabled.
3. Prefer NDEF when possible.
4. Validate tag data before using it.
5. Do not trust NFC data blindly.
6. Do not store sensitive data in plain text on tag.
7. Use deep links carefully.
8. Handle duplicate scans.
9. Handle empty or corrupted tags.
10. Give clear UI feedback after scan.

---

20. NFC Interview Answer

Question: What is NFC and how do you implement it in Android?

Answer:

> NFC is Near Field Communication. It is used for tap-based short-range communication. In Android, I declare NFC permission and feature in the manifest. If the tag contains NDEF data, Android sends an ACTION_NDEF_DISCOVERED intent to my activity. I read EXTRA_NDEF_MESSAGES, parse the NdefMessage, extract records, validate the data, and perform the required action.

---

Part 2: Wearable Watch / Wear OS Communication

21. What is Wearable Watch Communication?

Wearable watch communication means your Android phone app exchanges data with a smartwatch app.

Example:

Phone app sends command to watch
Watch app sends sensor/status data to phone

Simple meaning:

Phone app <-> Watch app communication

---

22. Important Interview Correction

For Wear OS, do not say:
I use raw Bluetooth socket for phone-watch app communication.

Correct answer:

For Wear OS, I use Wearable Data Layer APIs.

Google’s Wear OS Data Layer overview says apps access the Data Layer API through the Wearable class and client classes such as DataClient and MessageClient.

---

23. Why Not Raw Bluetooth for Wear OS?

Because the phone-watch pairing and transport are handled by the system.

Your app should use the high-level Wear OS APIs.

Phone App
   |
Wearable Data Layer API
   |
System transport
   |
Watch App

Simple meaning:

Bluetooth may be used internally,
but app code should use Data Layer.

---

24. Wear OS Communication Diagram

Phone App
   |
   | MessageClient
   v
Watch App

Phone App
   |
   | DataClient
   v
Watch App

Phone App
   |
   | Asset / Channel
   v
Watch App

---

25. Wear OS Data Layer API

The Data Layer is a communication layer between phone and watch apps.

It provides different clients for different needs.

Wearable Data Layer
   |
   +-- MessageClient
   +-- DataClient
   +-- Asset
   +-- ChannelClient
   +-- CapabilityClient
   +-- NodeClient

---

26. Wear OS Clients

ClientUse
MessageClientSend small commands/events
DataClientSync data/state
AssetSend binary data like image
ChannelClientStream larger data
CapabilityClientCheck if device supports feature
NodeClientFind connected phone/watch nodes

Android’s Wear OS client type guide introduces the different Data Layer clients and compares their capabilities, helping developers choose the correct client for each communication need.

---

27. MessageClient

What is MessageClient?

MessageClient is used to send small commands or events.

Simple meaning:

MessageClient = send command now

Example:

Phone says: Start tracking
Watch receives: /start_tracking
Watch starts tracking

---

MessageClient Use Cases

Use CaseExample
Start actionStart workout
Stop actionStop tracking
Trigger syncRefresh watch data
Open screenOpen watch screen
Send commandStart sensor reading

---

MessageClient Diagram

Phone App
   |
   | sendMessage("/start_tracking")
   v
Watch App
   |
Receives message
   |
Starts tracking

---

Phone Side Pseudocode

class WatchCommandSender(
    private val context: Context
) {
    private val nodeClient =
        Wearable.getNodeClient(context)

    private val messageClient =
        Wearable.getMessageClient(context)

    suspend fun sendStartTrackingCommand() {
        val nodes = nodeClient.connectedNodes.await()

        nodes.forEach { node ->
            messageClient.sendMessage(
                node.id,
                "/start_tracking",
                "start".toByteArray()
            ).await()
        }
    }
}

---

Watch Side Pseudocode

class WatchMessageListenerService : WearableListenerService() {

    override fun onMessageReceived(messageEvent: MessageEvent) {
        when (messageEvent.path) {
            "/start_tracking" -> {
                startTracking()
            }

            "/stop_tracking" -> {
                stopTracking()
            }
        }
    }

    private fun startTracking() {
        Log.d("WATCH", "Tracking started")
    }

    private fun stopTracking() {
        Log.d("WATCH", "Tracking stopped")
    }
}

---

28. DataClient

What is DataClient?

DataClient is used to sync data or state between phone and watch.

Simple meaning:

DataClient = keep data/state synced

Example:

Phone selected workout mode = Running
        |
DataClient syncs mode
        |
Watch shows Running mode

Wear OS sync documentation says Data Layer is used to synchronize data between Wear OS devices and phones, while developers should also consider when direct network communication is more appropriate.

---

DataClient Use Cases

Use CaseExample
Sync user settingUnit: km/miles
Sync workout modeRunning/Cycling
Sync profile dataName, age, goal
Sync statusConnected/tracking
Sync small app stateCurrent selected item

---

DataClient Diagram

Phone App
   |
PutDataMapRequest
   |
DataClient.putDataItem()
   |
Wear OS Data Layer
   |
Watch App receives data change

---

DataClient Pseudocode

suspend fun syncWorkoutMode(
    context: Context,
    mode: String
) {
    val dataClient = Wearable.getDataClient(context)

    val request = PutDataMapRequest.create("/workout_mode").apply {
        dataMap.putString("mode", mode)
        dataMap.putLong("updatedAt", System.currentTimeMillis())
    }.asPutDataRequest()

    dataClient.putDataItem(request).await()
}

---

29. Asset

What is Asset?

Asset is used to send larger binary data.

Simple meaning:

Asset = send image/file-like data

Example:

Phone sends profile image to watch
Watch displays profile image

---

30. CapabilityClient

What is CapabilityClient?

CapabilityClient is used to check whether the phone/watch supports a feature.

Simple meaning:

CapabilityClient = check feature availability

Example:

Does connected watch support heart-rate tracking?
Does watch app support workout feature?

---

31. NodeClient

What is NodeClient?

NodeClient is used to find connected devices/nodes.

Simple meaning:

NodeClient = find connected watch/phone

Example:

Phone checks connected watch nodes
Then sends command to each connected node

---

32. Wear OS Pairing for Development

For development, Android Studio supports testing with Wear OS emulators and pairing a watch emulator with a phone. Google’s Wear OS setup docs describe pairing devices through the Wear OS app and Android Studio tools.

Development setup:

1. Create phone emulator or use real phone
2. Create Wear OS emulator
3. Pair phone and watch
4. Create phone app module
5. Create wear app module
6. Use Wearable Data Layer APIs
7. Test message/data sync

---

33. Wear OS Implementation Flow

1. Create phone app
2. Create watch app
3. Pair phone and watch
4. Add Wear OS dependencies
5. Use NodeClient to find connected node
6. Use MessageClient for command
7. Use DataClient for sync
8. Handle message/data events on watch
9. Update UI
10. Handle disconnect/unavailable state

---

34. Wear OS Phone-Watch Example

Requirement

Phone has Start Tracking button.
When user taps button:
- Phone sends command to watch
- Watch receives command
- Watch shows "Tracking Started"

Flow

Phone Button Click
        |
ViewModel
        |
SendWatchCommandUseCase
        |
WatchRepository
        |
MessageClient
        |
WatchMessageListenerService
        |
Watch UI updates

---

35. Android Architecture for Wear OS

Phone App
   |
Presentation Layer
   |
ViewModel
   |
Use Case
   |
Repository
   |
Wear Data Source
   |
Wearable Data Layer API
   |
Watch App

---

Package Structure

feature_watch/
   presentation/
      WatchConnectScreen.kt
      WatchConnectViewModel.kt
      WatchUiState.kt

   domain/
      repository/
         WatchRepository.kt

      usecase/
         SendWatchCommandUseCase.kt
         SyncWatchDataUseCase.kt
         ObserveWatchConnectionUseCase.kt

   data/
      WatchRepositoryImpl.kt
      WearMessageDataSource.kt
      WearDataSyncDataSource.kt

---

UI State

sealed interface WatchUiState {
    data object Idle : WatchUiState
    data object SearchingWatch : WatchUiState
    data object Connected : WatchUiState
    data object SendingCommand : WatchUiState
    data object CommandSent : WatchUiState
    data object WatchNotFound : WatchUiState
    data class Error(val message: String) : WatchUiState
}

---

36. NFC vs Wear OS Comparison

TopicNFCWear OS Communication
Main ideaTap phone to tagPhone app talks to watch app
RangeVery shortPhone-watch connection
ConnectionUsually no long connectionSystem paired connection
Data typeSmall tag dataCommands, sync data, assets
Main APINfcAdapter, NdefMessageWearable, MessageClient, DataClient
User actionTap tagWatch paired/connected
Common use caseProduct/asset IDStart workout, sync status
Best keywordNDEFData Layer

---

37. NFC vs BLE vs Wear OS

TopicNFCBLEWear OS
CommunicationTap-basedScan/connectData Layer
RangeVery shortNearbyPaired/network
DataVery smallSmall/mediumSmall/medium
PowerLowLowManaged by system
Use caseTag scanSensor/wearablePhone-watch app sync
APINFC APIsBluetoothGattWearable APIs
ExampleProduct tagHeart-rate sensorWatch command

---

38. Wear OS Pros and Cons

Pros

ProsExplanation
High-level APINo need to manage raw Bluetooth
Good app-to-app syncPhone and watch apps communicate cleanly
Multiple clientsMessage, data, asset, capability
System-managed transportBluetooth/cloud can be handled internally
Secure app matchingPhone/watch app identity is managed by platform

Cons

ConsExplanation
Needs watch appUsually requires companion Wear OS app
Setup complexityPhone-watch pairing and modules
Not for all watchesMainly Wear OS ecosystem
Sync delay possibleData sync may not be instant
Need proper testingEmulator/real watch setup needed

---

39. Important Interview Points

NFC:
- NFC is tap-based.
- NDEF is standard NFC data format.
- Android dispatches NFC intents.
- Foreground dispatch gives priority to foreground Activity.
- Validate NFC tag data before using it.

Wear OS:
- Use Data Layer, not raw Bluetooth socket.
- MessageClient is for commands.
- DataClient is for syncing state/data.
- Asset is for binary data.
- CapabilityClient checks feature availability.
- NodeClient finds connected devices.

---

40. Common Mistakes

MistakeWhy It Is Wrong
Treating NFC like BluetoothNFC is tap-based, not continuous
Storing sensitive data openly on NFC tagTags can be read by others
Not validating NFC dataMalicious tag can trigger wrong behavior
Saying Wear OS uses raw Bluetooth socketCorrect API is Data Layer
Using MessageClient for large dataUse Asset/Channel for larger data
Not handling disconnected watchWatch may not be reachable
Keeping SDK/API code inside ActivityBad architecture
Not testing with emulator/real watchCommunication bugs are common

---

41. Interview Questions and Answers

Q1. What is NFC?

Answer:

> NFC means Near Field Communication. It is a short-range tap-based communication technology. In Android, it is commonly used to read NFC tags containing text, URL, product ID, employee ID, or deep link data.

---

Q2. What is NDEF?

Answer:

> NDEF means NFC Data Exchange Format. It is a standard format used to store data on NFC tags. An NDEF message contains one or more NDEF records.

---

Q3. How do you read NFC tag data in Android?

Answer:

> I add NFC permission and feature in the manifest. Then I add an NFC intent filter, usually for ACTION_NDEF_DISCOVERED. When the user taps a tag, Android sends an intent to my activity. I read EXTRA_NDEF_MESSAGES, parse NdefMessage, extract records, validate data, and then perform the required action.

---

Q4. What is NFC foreground dispatch?

Answer:

> Foreground dispatch allows the currently visible activity to receive NFC tag intents before other apps. It is useful when the app has a dedicated NFC scan screen open.

---

Q5. What is Wear OS Data Layer?

Answer:

> Wear OS Data Layer is the recommended communication layer between phone and Wear OS watch apps. It provides clients like MessageClient, DataClient, Asset, CapabilityClient, and NodeClient.

---

Q6. What is MessageClient?

Answer:

> MessageClient is used to send small commands or events from phone to watch or watch to phone, such as /start_tracking or /stop_tracking.

---

Q7. What is DataClient?

Answer:

> DataClient is used to synchronize state or small data between phone and watch, such as workout mode, user setting, or current status.

---

Q8. Can we use raw Bluetooth socket for Wear OS communication?

Answer:

> For normal Wear OS app-to-app communication, I would not use raw Bluetooth socket. I would use Wearable Data Layer APIs. The system manages the underlying transport, and the app uses high-level clients like MessageClient and DataClient.

---

Q9. How do you design Wear OS communication in Clean Architecture?

Answer:

> I keep Wear OS APIs in the data layer. The domain layer has repository interfaces and use cases like SendWatchCommandUseCase. The ViewModel exposes state using StateFlow. This keeps UI independent from Wear OS APIs and makes the code testable.

---

Q10. When will you use NFC vs Wear OS Data Layer?

Answer:

> I use NFC when the user taps a tag to read small data like product ID or deep link. I use Wear OS Data Layer when a phone app and watch app need to communicate, send commands, sync state, or exchange assets.

---

42. Day 2 Practice Tasks

Task 1: NFC Reader App

Create a simple NFC reader flow.

Screen:
- Waiting for NFC tag
- User taps tag
- App reads NDEF data
- App shows tag value

Expected flow:

NFC tag tapped
        |
Activity receives intent
        |
Read NDEF message
        |
Parse record
        |
Show value on screen

---

Task 2: Wear OS Command App

Create a phone-watch command flow.

Phone screen:
- Button: Start Tracking
- Button: Stop Tracking

Watch screen:
- Shows tracking status

Expected flow:

Phone button clicked
        |
MessageClient sends command
        |
Watch receives command
        |
Watch updates UI

---

43. Day 2 Revision Mind Map

Day 2
   |
   +-- NFC
   |      |
   |      +-- Tap-based
   |      +-- NDEF
   |      +-- NDEF Message
   |      +-- NDEF Record
   |      +-- Intent Dispatch
   |      +-- Foreground Dispatch
   |      +-- Reader Mode
   |
   +-- Wear OS
          |
          +-- Data Layer
          +-- MessageClient
          +-- DataClient
          +-- Asset
          +-- CapabilityClient
          +-- NodeClient
          +-- Phone App <-> Watch App

---

44. Final Memory Lines

NFC       = Tap + NDEF + Intent Dispatch
NDEF      = NFC data format
MessageClient = Send command
DataClient    = Sync state/data
Asset         = Send binary data
CapabilityClient = Check feature support
NodeClient    = Find connected watch/phone
Wear OS communication = Data Layer, not raw Bluetooth socket

---

45. Final Day 2 Interview Pitch

> NFC is used for tap-based short-range communication. In Android, I use NFC permission, intent filters, and NDEF parsing to read tag data. For active scanning, I can use foreground dispatch or reader mode. For Wear OS communication, I use the Wearable Data Layer API instead of raw Bluetooth sockets. MessageClient is used for commands, DataClient for state synchronization, Asset for binary data, CapabilityClient for feature discovery, and NodeClient for finding connected devices. I keep these APIs inside the data layer and expose clean states to the UI through ViewModel and StateFlow.