Search code examples
android-activitymauinet6.0-androidnfcadapter

Get current Android activity in MAUI android (net6-android) library


I have a library for Xamarin.Forms (Android) allowing to use NFC, with this code :

public class MediaAccessReader : Java.Lang.Object, NfcAdapter.IReaderCallback
{
    public const string TypeName = "Nfc";
    private static NfcAdapter NfcAdapter { get; } = NfcAdapter.GetDefaultAdapter(Android.App.Application.Context);
    public string Name { get; set; }

    public void Initialize(MediaAddedEventHandler mediaAdded, MediaRemovedEventHandler mediaRemoved)
    {                        
        Name = "Nfc";
#if XAMARINANDROID
         var activity = Forms.Context as Activity;
         NfcAdapter?.EnableReaderMode(activity, this, NfcReaderFlags.NfcA | NfcReaderFlags.NfcB | NfcReaderFlags.NfcF | NfcReaderFlags.NfcV | NfcReaderFlags.SkipNdefCheck, Bundle.Empty);
#else
         var activity = ?????????????????;
         NfcAdapter?.EnableReaderMode(activity , this, NfcReaderFlags.NfcA | NfcReaderFlags.NfcB | NfcReaderFlags.NfcF | NfcReaderFlags.NfcV | NfcReaderFlags.SkipNdefCheck, Bundle.Empty);
#endif

        MediaAdded += mediaAdded;
        MediaRemoved += mediaRemoved;
    }
}

How could I replace the var activity = Forms.Context as Activity line to get the current activity and be able to call NfcAdapter?.EnableReaderMode without Xamarin Forms ?

Otherwise, is there another solution ?


Solution

  • It's include inside Xamarin.Essentials

    Xamarin.Essentials.Platform.CurrentActivity
    

    Essentials has been ported to .Net Maui

    Platform.CurrentActivity