Код: Выделить всё
class NfcObserver(context: Context) {
private val activity = WeakReference(context as? Activity)
private val nfcAdapter: NfcAdapter? by lazy { NfcAdapter.getDefaultAdapter(context) }
private fun isNfcSupported(): Boolean = nfcAdapter != null
private fun isNfcEnabled(): Boolean = nfcAdapter?.isEnabled == true
val nfcTagContentFlow: Flow = callbackFlow {
when {
!isNfcSupported() -> {
close(UnsupportedOperationException("NFC is not supported on this device"))
return@callbackFlow
}
!isNfcEnabled() -> {
close(IllegalStateException("NFC is not enabled"))
return@callbackFlow
}
}
val readerCallback = NfcAdapter.ReaderCallback { tag ->
launch {
handleNdefTag(tag)
}
}
val flags = NfcAdapter.FLAG_READER_NFC_A
nfcAdapter?.enableReaderMode(activity.get(), readerCallback, flags, null)
awaitClose {
nfcAdapter?.disableReaderMode(activity.get())
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... eader-mode