如何在Flutter POS应用中实现NFC触发附近设备打开Android即时应用
实现Flutter POS NFC触发Android即时应用方案
核心逻辑
通过NFC传输NDEF格式的URL(App Link或自定义Scheme),目标设备的系统NFC服务会自动解析该URL,唤起关联的即时应用。
具体实现步骤
1. POS端(NFC数据发送)
使用nfc_manager包完成NDEF URL记录的写入,关键代码示例:
import 'package:nfc_manager/nfc_manager.dart'; Future<void> sendNfcTriggerUrl(String targetUrl) async { bool nfcAvailable = await NfcManager.instance.isAvailable(); if (!nfcAvailable) { // 处理NFC未开启/不可用的情况 return; } await NfcManager.instance.startSession( onDiscovered: (NfcTag tag) async { // 创建NDEF格式的URL记录 final ndefRecord = NdefRecord.createUri(Uri.parse(targetUrl)); final ndefMessage = NdefMessage([ndefRecord]); try { await Ndef.from(tag)?.write(ndefMessage); // 发送成功后停止会话 await NfcManager.instance.stopSession(); } catch (e) { // 处理写入失败 await NfcManager.instance.stopSession(errorMessage: e.toString()); } }, ); }
调用时传入你的即时应用关联的URL,比如https://yourdomain.com/launch-instant-app。
2. 接收端(即时应用配置)
需在AndroidManifest.xml中完成两项配置,确保系统能识别NFC传输的URL并唤起应用:
- 配置App Link关联(推荐,支持Google Play Instant):
<intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="yourdomain.com" android:pathPrefix="/launch-instant-app" /> </intent-filter>
- 配置NFC NDEF识别过滤器:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="false" /> <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="https" android:host="yourdomain.com" android:pathPrefix="/launch-instant-app" /> </intent-filter>
3. 替代方案:自定义URL Scheme
若不想用HTTPS的App Link,可使用自定义Scheme(如yourapp://launch),只需修改:
- POS端发送的URL改为自定义Scheme格式
- 接收端AndroidManifest.xml的intent-filter中
android:scheme值改为对应的自定义名称
关键注意事项
- 测试必须使用实体NFC设备,模拟器不支持NFC功能
- 接收设备需开启NFC功能
- 即时应用需提前在Google Play Console配置好Instant App属性
内容的提问来源于stack exchange,提问作者Redson Farias
相关产品推荐
相关产品推荐

