在我使用 Blazor 的 .NET Maui 混合应用程序中,我有一个要求:当用户尝试向后导航或按移动应用程序中的后退按钮时,我需要显示一个确认弹出窗口,询问他们是否要在继续之前关闭应用程序关闭应用程序。我在 App.xaml.cs 中尝试了以下代码,但再次打开应用程序时会弹出它。我想知道在关闭应用程序之前要调用哪个方法。
public partial class App : Application
{
private IAudioPlayer _audioPlayer;
private IAudioManager _audioManager;
private NavigationManager NavigationManager;
public bool isPlaying = true;
public App(IAudioManager audioManager)
{
InitializeComponent();
MainPage = new MainPage();
_audioManager = audioManager;
}
protected override Window CreateWindow(IActivationState? activationState)
{
Window window = base.CreateWindow(activationState);
window.Created += (s, e) =>
{
// Custom logic
};
window.Destroying += (s, e) =>
{
_audioPlayer.Stop();
};
window.Deactivated += (s, e) =>
{
if (_audioPlayer != null)
{
_audioPlayer.Stop();
}
};
window.Deactivated += Window_Deactivated;
return window;
}
}
private async void Window_Deactivated(对象发送者,EventArgs e) { bool canDeactivate = 等待 ShowConfirmationDialog(); if (!canDeactivate) {
}
}
private async Task<bool> ShowConfirmationDialog()
{
bool canDeactivate = false;
string message = "Do you want to leave the app?";
var result = await MainPage.DisplayAlert("Confirmation", message, "Yes", "No");
if (result)
{
canDeactivate = true;
}
return canDeactivate;
}
我尝试在 App.xaml.cs 中执行类似的操作,但在关闭应用程序后,它会调用,以便再次打开我的弹出窗口。
在Android平台上,如果MainPage是你的根页面,你可以尝试通过重写MainPage.xaml.cs中的
OnBackButtonPressed
方法来设置点击后退按钮时的Popup:
protected override bool OnBackButtonPressed()
{
Dispatcher.Dispatch(async () =>
{
var leave = await DisplayAlert("asd", "dsadsa", "Yes", "No");
if (leave)
{
Exit();
}
});
return false;
}
//This method is used to move the application to the background
public void Exit()
{
bool exit = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.MoveTaskToBack(true);
if (!exit)
{
var intent = new Android.Content.Intent(Android.Content.Intent.ActionMain);
intent.AddCategory(Android.Content.Intent.CategoryHome);
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.StartActivity(intent);
}
}