How to trigger reading NFC tags from screens

  Kiến thức lập trình

I’m trying to write code so my android app could read/write NFC tags from a screen. I use Kotlin and Jetpack Compose. I have one MainActivity.kt and two screens: HomeScreen.kt and NFCReader.kt. A button on HomeScreen.kt will open NFCReader.kt and a button on NFCReader.kt will start the read/write process.

I have tried using DisposableEffect but for some reason, it keeps triggering the phone’s default NFC scanner.

Below is my code for DisposableEffect. I checked the logcat after every run and I couldn’t find the log so I believe the I might not implement the effect correctly? Please help, TIA.

@Composable
fun NFCReader(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
) {
    val nfcAdapter = NfcAdapter.getDefaultAdapter(activity)
    val activity = LocalContext.current.getActivity() as ComponentActivity
    val context = LocalContext.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME) {
                Log.d("TAG_", "turn on NFC reader here")
                val pendingIntent = PendingIntent.getActivity(
                    activity, 0, Intent(activity, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                    PendingIntent.FLAG_MUTABLE
                )
                val intentFilters = arrayOf<IntentFilter>(
                    IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED),
                    IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED),
                    IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
                )
                nfcAdapter.enableForegroundDispatch(activity, pendingIntent, intentFilters, null)
            }
            if (event == Lifecycle.Event.ON_PAUSE) {
                Log.d("TAG_", "turn off NFC reader")
                nfcAdapter.disableForegroundDispatch(activity)
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)

        val listener = Consumer<Intent> {
            // Do something
            Log.d("TAG_", "inside listener")
        }
        activity.addOnNewIntentListener(listener)
        onDispose {
            activity1.removeOnNewIntentListener(listener)
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
}

New contributor

just_asking is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT