Home > Blockchain >  How to read data from an NFC device using C# android?
How to read data from an NFC device using C# android?

Time:11-03

I am trying to read data from an NFC credit card. The app is written using the .NET Maui framework. Right now I am trying to use the Plugin.NFC NuGet package because it seems to be the only one.

Here is the code I have so far:

        private TagInfo tmpData;
        private static void ReadTagEvent(ITagInfo data)
        {
            tmpData = (TagInfo)data;
        }
        public static NFC_READ_ERROR ReadNFC(ref TagInfo result, Page page)
        {
            if (!IsReady())
            {
                return NFC_READ_ERROR.NOT_ENABLED;
            }
            tmpData = null;
            
            CrossNFC.Current.StartListening();
            CrossNFC.Current.OnMessageReceived  = ReadTagEvent;
            page.DisplayAlert("Info", "Starting listening for NFC...", "Ok");
            while (tmpData == null)
            {
                Thread.Sleep(50);
            }
            page.DisplayAlert("Info", "tmpData != null", "Ok");
            CrossNFC.Current.StopListening();
            result = tmpData;
            if (tmpData.IsEmpty)
            {
                return NFC_READ_ERROR.NO_DATA;
            }
            return NFC_READ_ERROR.SUCCESS;
        }

This runs and displays the first alert. But the result of tagInfo saved to tmpData is still null. Because ReadTagEvent is never triggered. After the Start listening is called. And the device is in close proximity to the android phone it beeps so I know that it is listening. I have confirmed that the device has data and is working properly by testing it on another app. The second alert is never displayed. By the way, this code is run inside a Thread in the app's Display Page. Any help and code would be appreciated. Thanks.

CodePudding user response:

  1. Add NFC Permissions in your AndroidManifest.xml

    <uses-permission android:name="android.permission.NFC" />
    

    <uses-feature android:name="android.hardware.nfc" android:required="false" />

  2. Add the line CrossNFC.Init(this) in your OnCreate().

    
    protected override void OnCreate(Bundle savedInstanceState)
    {
    
        CrossNFC.Init(this);
    
        base.OnCreate(savedInstanceState);
    [...]
    }
    

3. Add the line CrossNFC.OnResume() in your OnResume() // Plugin NFC: Restart NFC listening on resume (needed for Android 10 ) 4. Add the line CrossNFC.OnNewIntent(intent) in your OnNewIntent() // Plugin NFC: Tag Discovery Interception

Plugin.NFC https://github.com/franckbour/Plugin.NFC

  • Related