81 lines
2.4 KiB
C#
81 lines
2.4 KiB
C#
using Android.App;
|
|
using Android.Content;
|
|
using Android.Content.PM;
|
|
using Android.Nfc;
|
|
using Android.Nfc.Tech;
|
|
using Android.OS;
|
|
using Com.Lvcheng.Lock.Shared.Nfc.Example.Java;
|
|
using NFCLockDemoV2;
|
|
using NFCLockDemoV2.Platforms.Android;
|
|
using NFCLockDemoV2.ViewModels;
|
|
using Microsoft.Maui;
|
|
using Microsoft.Maui.Controls;
|
|
|
|
namespace NFCLockAppV2;
|
|
|
|
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density, Exported = true)]
|
|
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryLauncher })]
|
|
[IntentFilter(new[] { NfcAdapter.ActionNdefDiscovered }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "text/plain")]
|
|
public class MainActivity : MauiAppCompatActivity
|
|
{
|
|
private NFCHelper? nfcHelper;
|
|
private MainViewModel mainViewModel;
|
|
|
|
protected override void OnCreate(Bundle savedInstanceState)
|
|
{
|
|
base.OnCreate(savedInstanceState);
|
|
InitializeNFC();
|
|
}
|
|
|
|
private void InitializeNFC()
|
|
{
|
|
if (!TryInitializeNFC())
|
|
{
|
|
Microsoft.Maui.Controls.Application.Current.Dispatcher.Dispatch(() =>
|
|
{
|
|
TryInitializeNFC();
|
|
});
|
|
}
|
|
}
|
|
|
|
private bool TryInitializeNFC()
|
|
{
|
|
if (nfcHelper != null && mainViewModel != null)
|
|
return true;
|
|
|
|
MainViewModel viewModel = null;
|
|
if (Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext?.Services != null)
|
|
{
|
|
viewModel = Microsoft.Maui.Controls.Application.Current.Handler.MauiContext.Services.GetService<MainViewModel>();
|
|
}
|
|
|
|
if (viewModel != null)
|
|
{
|
|
NFCCallbacks nFCCallbacks = new NFCCallbacks(viewModel);
|
|
nfcHelper = new NFCHelper(this, nFCCallbacks);
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
protected override void OnResume()
|
|
{
|
|
base.OnResume();
|
|
// 确保NFC功能在每次恢复时都已初始化
|
|
InitializeNFC();
|
|
nfcHelper.OnResume();
|
|
}
|
|
|
|
protected override void OnPause()
|
|
{
|
|
base.OnPause();
|
|
nfcHelper.OnPause();
|
|
}
|
|
|
|
protected override void OnNewIntent(Intent intent)
|
|
{
|
|
base.OnNewIntent(intent);
|
|
nfcHelper.OnNewIntent(intent);
|
|
}
|
|
} |