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

如何让Maui Android的SingleTop、SingleTask按文档正常工作

MAUI Android 接收WhatsApp/Telegram共享文件的多实例与异常问题

我正在开发一款能接收WhatsApp或Telegram共享文件的MAUI Android应用,遇到以下系列问题:

  • 最初仅定义一个Activity并设为SingleTask启动模式,但通过任务切换器恢复时会调用OnCreate而非OnNewIntent;从WhatsApp共享文件时会创建应用新实例,导致双实例运行崩溃,切换为SingleTop或SingleInstance模式问题依旧。
  • 进一步排查发现:应用会以WhatsApp进程的子进程形式创建,任务切换器中会显示一个MyApp任务和一个WhatsApp任务,但后者的UI是覆盖在正常WhatsApp UI上的MyApp实例,且两个“实例”共享同一Activity实例值和窗口。
  • 切换应用时触发错误:System.InvalidOperationException: 'This window is already associated with an active Activity (MyApp.MainActivity). Please override CreateWindow on MyApp.App to add support for multiple activities or set the LaunchMode to SingleTop on MyApp.MainActivity.',修改Manifest和MainActivity为SingleTop无效果。
  • 设置NoHistory = false可避免Activity在任务切换时被销毁,但从WhatsApp或Telegram共享文件时,应用仍会作为其子进程重建,该问题未解决。
  • 新增LaunchActivity后,共享文件操作中调用OnCreate和base.OnCreate时会创建新的AppShell及其侧边菜单,但新AppShell出现异常:
    • 不响应FlyoutIsPresented = false语句
    • 侧边菜单的ListView虽ItemSource有数百条记录却无内容
    • 仅在应用后台运行时,通过共享操作重启应用才会出现此问题

相关代码

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, 
        LaunchMode = LaunchMode.SingleTask, 
        NoHistory = true,
        Exported = true,
        TaskAffinity = "com.mycompany.myapp",
        ConfigurationChanges =  ConfigChanges.ScreenSize | ConfigChanges.Orientation | 
                                ConfigChanges.UiMode | ConfigChanges.ScreenLayout | 
                                ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]

    //whatsapp & telegram send binaries as octet-stream
    [IntentFilter(new[] { Android.Content.Intent.ActionSend },
                Categories = new[] { Android.Content.Intent.CategoryDefault },
                DataMimeType = @"application/octet-stream", 
                Icon = "@mipmap/appicon")]


public partial class LaunchActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        try
        {
            base.OnCreate(bundle);
            Platform.Init(this, bundle);


            if (Intent.Action == Intent.ActionSend || Intent.Action == Intent.ActionView)
                ProcessSendOrViewIntent();

            LaunchMainActivity();

            Finish();
        }
        catch (Exception e)
        {
            LogException(e, false);
            throw;
        }
    }

    void LaunchMainActivity()
    {
        Intent intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
        StartActivity(intent);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:22:16