使用sumup-android-api时Callback触发导致应用多实例问题排查
问题:SumUp回调触发时启动应用第二个实例
我尝试使用SumUp Android API,回调触发前一切正常,但回调触发时,SumUp应用内似乎启动了我的应用的第二个实例。
第一个实例:
SumUp应用内的第二个实例(查看应用图标):
我通过以下代码启动SumUp支付流程:
Launcher.Default.OpenAsync(@"sumupmerchant://pay/1.0?affiliate-key=itsasecret&app-id=dummyapp&total=5.00¤cy=EUR&title=1000084564&skip-screen-success=true&callback=renditewebclient://sumup");
我的MainActivity.cs代码如下:
using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using System.Diagnostics; namespace RenditeBrowser { [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] [IntentFilter(new[] { Intent.ActionView }, Categories = new[] { Intent.ActionView, Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "renditewebclient", DataHost = "sumup")] public class MainActivity : MauiAppCompatActivity { protected override void OnCreate(Bundle? savedInstanceState) { if (this.Intent != null) { Intent intent = this.Intent; var action = intent.Action; var strLink = intent.DataString; if (Intent.ActionView == action && !string.IsNullOrWhiteSpace(strLink)) { if (strLink.Contains("sumup")) { System.Diagnostics.Trace.WriteLine("Intent-Data: " + strLink); } } } base.OnCreate(savedInstanceState); } } }
请问我哪里操作有误?
解决方案
问题出在Activity的启动模式配置上,默认模式会让系统在收到回调Intent时创建新的Activity实例,导致出现第二个应用实例。按以下步骤修改即可解决:
- 给MainActivity添加SingleTask启动模式
在[Activity]特性中加入LaunchMode = LaunchMode.SingleTask,确保系统复用已存在的Activity实例,而非创建新实例:
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTask, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
- 重写OnNewIntent方法处理回调Intent
使用SingleTask模式时,新的Intent会通过OnNewIntent传递给已存在的Activity实例,而不会触发OnCreate,所以需要在这个方法里处理SumUp的回调数据:
protected override void OnNewIntent(Intent? intent) { base.OnNewIntent(intent); if (intent != null) { var action = intent.Action; var strLink = intent.DataString; if (Intent.ActionView == action && !string.IsNullOrWhiteSpace(strLink) && strLink.Contains("sumup")) { System.Diagnostics.Trace.WriteLine("Intent-Data (回调): " + strLink); // 在这里添加你的回调处理逻辑,比如更新支付状态、通知用户等 } } }
- 保留OnCreate中的Intent处理(可选)
如果需要处理应用首次启动时的Intent(比如从其他应用跳转打开),可以保留原OnCreate中的代码,但回调逻辑主要放在OnNewIntent中。
这样修改后,SumUp回调触发时就会直接复用已有的应用实例,不会再创建第二个实例。
内容的提问来源于stack exchange,提问作者complete_stranger
相关产品推荐
相关产品推荐

