MAUI Android:如何避免恢复应用时WebView重新加载页面?
解决MAUI Android平台WebView恢复时重置为初始页面的问题
Android平台下,MAUI的WebView在应用从后台恢复时会自动重新加载初始URL,丢失用户之前的导航状态。以下是具体解决步骤:
1. 修改XAML,给WebView命名
先给WebView添加x:Name,方便后台代码访问和操作:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="mauitestsingle.MainPage"> <WebView x:Name="MainWebView" Source="https://google.com"/> </ContentPage>
2. 后台代码保存并恢复当前URL
在MainPage的后台代码中,监听WebView的导航事件,每次页面加载完成后保存当前URL;应用恢复时,加载之前保存的URL:
using Microsoft.Maui.Controls; namespace mauitestsingle; public partial class MainPage : ContentPage { private const string LastWebUrlKey = "LastWebViewUrl"; public MainPage() { InitializeComponent(); // 监听导航完成事件,保存当前URL MainWebView.Navigated += OnWebViewNavigated; } protected override void OnAppearing() { base.OnAppearing(); // 恢复上次保存的URL if (Preferences.ContainsKey(LastWebUrlKey)) { var savedUrl = Preferences.Get(LastWebUrlKey, string.Empty); if (!string.IsNullOrEmpty(savedUrl) && MainWebView.Source.ToString() != savedUrl) { MainWebView.Source = new UrlWebViewSource { Url = savedUrl }; } } } private void OnWebViewNavigated(object sender, WebNavigatedEventArgs e) { // 导航成功时保存当前URL if (e.Result == WebNavigationResult.Success) { Preferences.Set(LastWebUrlKey, e.Url); } } }
3. Android平台原生状态保存(可选,保留页面细节)
如果需要保留页面的滚动位置、表单输入等细节,需要在Android项目的MainActivity中重写状态保存和恢复方法,利用原生WebView的状态保存机制:
using Android.App; using Android.Content.PM; using Android.OS; namespace mauitestsingle; [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] public class MainActivity : MauiAppCompatActivity { protected override void OnSaveInstanceState(Bundle outState) { base.OnSaveInstanceState(outState); // 获取原生WebView控件并保存状态 if (Microsoft.Maui.Controls.Application.Current.MainPage is MainPage mainPage) { var webViewHandler = (Microsoft.Maui.Handlers.WebViewHandler)mainPage.MainWebView.Handler; var androidWebView = webViewHandler.PlatformView; androidWebView.SaveState(outState); } } protected override void OnRestoreInstanceState(Bundle savedInstanceState) { base.OnRestoreInstanceState(savedInstanceState); // 恢复原生WebView状态 if (Microsoft.Maui.Controls.Application.Current.MainPage is MainPage mainPage) { var webViewHandler = (Microsoft.Maui.Handlers.WebViewHandler)mainPage.MainWebView.Handler; var androidWebView = webViewHandler.PlatformView; androidWebView.RestoreState(savedInstanceState); } } }
核心原理
Android系统在应用进入后台后,可能因资源回收销毁Activity,导致WebView重建并加载初始URL。通过以下两种方式避免状态丢失:
- 记录用户最后访问的URL,应用恢复时直接加载该URL
- 利用Android原生的状态保存机制,保存WebView的完整页面状态(包括滚动位置、表单数据等)
参考Xamarin相关解决方案的核心思路:
- 在WebView导航完成时保存当前URL到本地存储
- 页面显示时加载保存的URL
- 在Android Activity中重写状态保存方法,保留WebView原生状态
内容的提问来源于stack exchange,提问作者Isidoros Moulas
相关产品推荐
相关产品推荐

