如何让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
相关产品推荐
相关产品推荐

