.NET MAUI中NFC Intent配置及双页面扫描失效问题解决
解决.NET MAUI中多页面NFC扫描失效问题及正确配置NFC Intent
一、修正MainActivity的NFC Intent配置
你当前的IntentFilter仅绑定了MainPage.MIME_TYPE,这会导致只有匹配该MIME类型的NFC标签才会被触发,且限制了页面的通用性。要让所有页面都能接收NFC事件,需调整IntentFilter覆盖所有常见NFC触发场景:
using Android.App; using Android.Content; using Android.Content.PM; using Android.Nfc; using Android.OS; using Plugin.NFC; namespace ParcoDelCurone; [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] // 覆盖三种NFC触发动作,不限制MIME类型(如需指定多个MIME,可添加多个对应IntentFilter) [IntentFilter(new[] { NfcAdapter.ActionNdefDiscovered }, Categories = new[] { Intent.CategoryDefault })] [IntentFilter(new[] { NfcAdapter.ActionTagDiscovered }, Categories = new[] { Intent.CategoryDefault })] [IntentFilter(new[] { NfcAdapter.ActionTechDiscovered }, Categories = new[] { Intent.CategoryDefault })] public class MainActivity : MauiAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { CrossNFC.Init(this); base.OnCreate(savedInstanceState); // 处理App启动时携带的NFC Intent if (Intent != null) CrossNFC.OnNewIntent(Intent); } protected override void OnResume() { base.OnResume(); CrossNFC.OnResume(); } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); CrossNFC.OnNewIntent(intent); } }
如果需要针对不同页面处理特定MIME类型的标签,可为每个MIME类型单独添加IntentFilter,例如:
[IntentFilter(new[] { NfcAdapter.ActionNdefDiscovered }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "text/plain")] [IntentFilter(new[] { NfcAdapter.ActionNdefDiscovered }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "application/json")]
二、页面层面的NFC事件绑定
仅配置Activity的Intent不够,每个需要扫描NFC的页面都需独立注册/取消注册NFC事件,避免事件冲突和内存泄漏:
以两个页面为例,在各自的代码-behind中添加以下逻辑:
using Plugin.NFC; public partial class Page1 : ContentPage { public Page1() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); // 注册NFC检测事件 CrossNFC.Current.NFCDetected += OnNFCDetected; // 启动监听 CrossNFC.Current.StartListening(); } protected override void OnDisappearing() { base.OnDisappearing(); // 取消事件注册 CrossNFC.Current.NFCDetected -= OnNFCDetected; // 停止监听 CrossNFC.Current.StopListening(); } private void OnNFCDetected(ITagInfo tagInfo) { // 处理当前页面的NFC标签逻辑 // 例如解析tagInfo中的数据,执行对应操作 Device.BeginInvokeOnMainThread(() => { // 更新UI操作需回到主线程 DisplayAlert("NFC扫描", $"标签ID: {tagInfo.Id}", "确定"); }); } }
将上述代码复制到第二个页面(如Page2),修改OnNFCDetected内的业务逻辑即可实现不同页面的独立处理。
三、必要权限配置
确保Android项目已添加NFC相关权限,可直接在Platforms/Android/AndroidManifest.xml中添加:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="false" />
内容的提问来源于stack exchange,提问作者Francesco
相关产品推荐
相关产品推荐

