You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI深度链接报错:Window was already created 求助

解决.NET MAUI安卓深度链接后台运行时"Window was already created"错误

问题原因

应用处于后台时,安卓系统会通过OnNewIntent而非OnCreate触发深度链接,现有代码仅处理了OnCreate场景,导致后台唤醒时Intent处理逻辑异常;同时异步导航操作未确保在UI线程执行,引发窗口创建冲突。

解决方案步骤

1. 补充安卓OnNewIntent事件处理

修改MauiProgram.cs中的生命周期配置,统一处理OnCreate和OnNewIntent的Intent:

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .UseViewServices()
            .UseMicrocharts()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            })
            .ConfigureLifecycleEvents(lifecycle =>
            {
#if ANDROID
                lifecycle.AddAndroid(android => {
                    android.OnCreate((activity, bundle) =>
                    {
                        HandleAndroidIntent(activity.Intent);
                    });
                    // 新增后台唤醒时的Intent处理
                    android.OnNewIntent((activity, intent) =>
                    {
                        HandleAndroidIntent(intent);
                        // 更新Activity的Intent,避免后续重复处理
                        activity.Intent = intent;
                    });
                });
#endif
            });

//...

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }

    // 统一处理安卓Intent
    static void HandleAndroidIntent(Android.Content.Intent intent)
    {
        var action = intent?.Action;
        var data = intent?.Data?.ToString();

        if (action == Android.Content.Intent.ActionView && data is not null)
        {
            if (Uri.TryCreate(data, UriKind.RelativeOrAbsolute, out var uri))
            {
                // 确保在UI线程发送AppLink请求事件
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    App.Current?.SendOnAppLinkRequestReceived(uri);
                });
            }
        }
    }
}

2. 确保AppLink处理在UI线程执行

修改OnAppLinkRequestReceived方法,将异步导航操作包裹在UI线程调用中:

protected override async void OnAppLinkRequestReceived(Uri uri)
{
    base.OnAppLinkRequestReceived(uri);

    if (uri.Host == "engelberth-developing" && uri.Segments != null)
    {
        // 异步操作切换到UI线程执行
        await MainThread.InvokeOnMainThreadAsync(async () =>
        {
            if (uri.Segments.Length == 5 && uri.Segments[2] == "share/")
            {
                Global.Transfer = uri.Segments[3].Replace("/", "|") + uri.Segments[4].Replace("/", "").Replace('*', '/');
                await AssignService.SetNextPage<ISharedItemPage>();
            }
            else if (uri.Segments.Length == 4 && uri.Segments[2] == "sync/")
            {
                Global.Transfer = uri.Segments[3].Replace("/", "").Replace('*', '/');
                await AssignService.SetNextPage<IDeviceSyncPage>();
            }
        });
    }
}

3. 完善页面导航的线程安全检查

修改SetNextPage方法,确保导航操作在UI线程执行并校验Shell.Current有效性:

public static async Task SetNextPage<TService>(string paramValue = null)
{
    await MainThread.InvokeOnMainThreadAsync(async () =>
    {
        var implementationType = services
                                 .Where(service => service.ServiceType == typeof(TService))
                                 .Select(service => service.ImplementationType)
                                 .FirstOrDefault();

        // 校验Shell实例是否有效
        if (implementationType != null && Shell.Current != null)
        {
            var route = paramValue != null ? $"/{implementationType.Name}?{paramValue}" : $"/{implementationType.Name}";
            await Shell.Current.GoToAsync(route);
        }
    });
}

说明

  • 安卓后台唤醒时,系统会复用现有Activity并触发OnNewIntent,补充该事件处理可确保深度链接逻辑在后台场景正常执行。
  • 所有UI相关操作必须在主线程执行,避免跨线程操作导致窗口状态冲突。
  • 校验Shell.Current可防止应用初始化未完成时的导航错误。

内容的提问来源于stack exchange,提问作者tengelberth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:48:14