首页 > 解决方案 > NFC 融入跨平台应用,Xamarin.Android 集成

问题描述

我想在跨平台应用程序中使用 NFC(读取 NFC 标签)我在 Xamarin 论坛上找到了 Xamarin.Android 的 NFC 示例。示例有效,我尝试为跨平台执行此操作,但遇到了障碍

( nfcAdapter = NfcAdapter.GetDefaultAdapter(this);) NfcAdapter 在这种情况下 = NULL,但手机有 NFC(示例有效) 我认为问题是因为当我从 ContentPage 移动到 Android 类时,我无法将 ContentPage 的内容导入 Android for NfcAdapter ,要在 Android 上访问 NFC 类,我将内容作为类 NFCWorker_Droid 获取,它无法访问屏幕

我假设我需要通过接口迁移有关 ContentPage 的信息,但我无法将 Xamarin.ContentPage 转换为 Android.Content

在界面的帮助下,我转到android项目中的类 IntoContentPage我调用接口的方法DependencyService.Get<INFCWorker>().EnableWriteMode();并移动到类到android项目中

下面的代码显示了在 Android 中调用的类代码

[assembly: Xamarin.Forms.Dependency(typeof(NFCWorker_Droid))]
namespace TestNavigationPage2.Droid
{
    public class NFCWorker_Droid : Activity,INFCWorker
    {
        public const string ViewApeMimeType = "application/vnd.xamarin.nfcxample";
        public static readonly string NfcAppRecord = "xamarin.nfxample";
        public static readonly string Tag = "NfcXample";
        private bool _inWriteMode;
        private NfcAdapter _nfcAdapter;

public void EnableWriteMode()
        {
            _inWriteMode = true;
            // Get a reference to the default NFC adapter for this device. This adapter 
            // is how an Android application will interact with the actual hardware.
            _nfcAdapter = NfcAdapter.GetDefaultAdapter(this); 
            // Create an intent filter for when an NFC tag is discovered.  When
            // the NFC tag is discovered, Android will u
            var tagDetected = new IntentFilter(NfcAdapter.ActionTagDiscovered);
            var filters = new[] { tagDetected };

            // When an NFC tag is detected, Android will use the PendingIntent to come back to this activity.
            // The OnNewIntent method will invoked by Android.
            //var intent = new Intent(this, GetType());
            //var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);

            if (_nfcAdapter == null)
            {
                Page4.Instance.GlobalText = "NFC is not supported on this device.";
            }
            else
            {
                DisplayMessage("NFC is here!");
                //_nfcAdapter.EnableForegroundDispatch(this, pendingIntent, filters, null);
            }
        }
}

标签: c#androidxamarincross-platformnfc

解决方案


推荐阅读