Login, NFCWaiter

This commit is contained in:
2025-03-24 14:02:25 +01:00
parent d55dee91e9
commit ebe33abf69
11 changed files with 308 additions and 62 deletions
@@ -0,0 +1,117 @@
using Plugin.NFC;
using System.Collections.ObjectModel;
namespace WorkFlowCheck.MAUI.Pages.NFC;
public partial class NFCWaiter : ContentPage
{
private bool _eventsAlreadySubscribed = false;
private bool _onReceiveing = false;
private TaskCompletionSource<string> _taskCompletionSource;
public NFCWaiter(TaskCompletionSource<string> taskCompletionSource)
{
InitializeComponent();
_taskCompletionSource = taskCompletionSource;
}
protected override async void OnAppearing()
{
base.OnAppearing();
CrossNFC.Legacy = false;
if (CrossNFC.IsSupported)
{
if (!CrossNFC.Current.IsAvailable)
await ShowAlert("NFC is not available");
if (!CrossNFC.Current.IsEnabled)
await ShowAlert("NFC is disabled");
await AutoStartAsync().ConfigureAwait(false);
}
else
{
await ShowAlert("NFC is not available");
}
}
async Task AutoStartAsync()
{
// Some delay to prevent Java.Lang.IllegalStateException "Foreground dispatch can only be enabled when your activity is resumed" on Android
await Task.Delay(500);
await StartListeningIfNotiOS();
}
async Task StartListeningIfNotiOS()
{
await BeginListening();
}
async Task BeginListening()
{
try
{
MainThread.BeginInvokeOnMainThread(() =>
{
SubscribeEvents();
CrossNFC.Current.StartListening();
});
}
catch (Exception ex)
{
await ShowAlert(ex.Message);
}
}
async Task EndListening()
{
try
{
MainThread.BeginInvokeOnMainThread(() =>
{
UnsubscribeEvents();
CrossNFC.Current.StopPublishing();
CrossNFC.Current.StopListening();
});
}
catch (Exception ex)
{
await ShowAlert(ex.Message);
}
}
void SubscribeEvents()
{
if (_eventsAlreadySubscribed)
UnsubscribeEvents();
_eventsAlreadySubscribed = true;
CrossNFC.Current.OnMessageReceived += Current_OnMessageReceived_NFCData;
}
void UnsubscribeEvents()
{
CrossNFC.Current.OnMessageReceived -= Current_OnMessageReceived_NFCData;
_eventsAlreadySubscribed = false;
}
async void Current_OnMessageReceived_NFCData(ITagInfo tagInfo)
{
_onReceiveing = true;
if (tagInfo == null)
{
await ShowAlert("No tag found");
_onReceiveing = false;
return;
}
// Customized serial number
var identifier = tagInfo.Identifier;
var serialNumber = NFCUtils.ByteArrayToHexString(identifier, ":");
_taskCompletionSource.TrySetResult(serialNumber);
await EndListening();
await Navigation.PopAsync();
_onReceiveing = false;
}
Task ShowAlert(string message, string title = null) => DisplayAlert(string.IsNullOrWhiteSpace(title) ? "NFC olvasás" : title, message, "OK");
}