Skip to content

Commit 4b177f0

Browse files
committed
add docs for tag event stream support
1 parent 1824bad commit 4b177f0

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,64 @@ To use this plugin on Android, you also need to:
3838

3939
* Add [android.permission.NFC](https://developer.android.com/reference/android/Manifest.permission.html#NFC) to your `AndroidManifest.xml`.
4040

41+
To receive NFC tag events even when your app is in the foreground, you can set up tag event stream support:
42+
43+
1. Create a custom Activity that extends `FlutterActivity` in your Android project:
44+
45+
```kotlin
46+
package your.package.name
47+
48+
import android.app.PendingIntent
49+
import android.content.Intent
50+
import android.nfc.NfcAdapter
51+
import android.nfc.Tag
52+
import io.flutter.embedding.android.FlutterActivity
53+
import im.nfc.flutter_nfc_kit.FlutterNfcKitPlugin
54+
55+
class MainActivity : FlutterActivity() {
56+
override fun onResume() {
57+
super.onResume()
58+
val adapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(this)
59+
val pendingIntent: PendingIntent = PendingIntent.getActivity(
60+
this, 0, Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE
61+
)
62+
// See https://developer.android.com/reference/android/nfc/NfcAdapter#enableForegroundDispatch(android.app.Activity,%20android.app.PendingIntent,%20android.content.IntentFilter[],%20java.lang.String[][]) for details
63+
adapter?.enableForegroundDispatch(this, pendingIntent, null, null)
64+
}
65+
66+
override fun onPause() {
67+
super.onPause()
68+
val adapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(this)
69+
adapter?.disableForegroundDispatch(this)
70+
}
71+
72+
override fun onNewIntent(intent: Intent) {
73+
val tag: Tag? = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
74+
if (tag != null) {
75+
FlutterNfcKitPlugin.handleTag(tag)
76+
}
77+
}
78+
}
79+
```
80+
81+
2. Update your `AndroidManifest.xml` to use this activity instead of the default Flutter activity.
82+
83+
3. In your Flutter code, listen to the tag event stream:
84+
85+
```dart
86+
@override
87+
void initState() {
88+
super.initState();
89+
// Listen to NFC tag events
90+
FlutterNfcKit.tagStream.listen((tag) {
91+
print('Tag detected: ${tag.id}');
92+
// Process the tag
93+
});
94+
}
95+
```
96+
97+
This will allow your app to receive NFC tag events through a stream, which is useful for scenarios where you need continuous tag reading or want to handle tags even when your app is in the foreground but not actively polling.
98+
4199
### iOS
42100

43101
This plugin now supports Swift package manager, and requires iOS 13+.

0 commit comments

Comments
 (0)