Xamarin Forms Android:重新唤起Chrome自定义标签页登录问题求助
解决方案:通过中转Activity唤起Chrome自定义标签继续登录流程
核心思路
创建一个无UI的透明中转Activity,专门处理MitID返回的应用链接,将请求转发回之前打开的Chrome自定义标签会话,避免直接唤起MainActivity打断登录流程。
步骤1:添加透明中转Activity
在Android项目中新建一个CustomTabRedirectActivity,配置对应的IntentFilter接收MitID返回的https://my-url链接:
[Activity(Theme = "@style/Theme.Transparent", LaunchMode = LaunchMode.SingleInstance, Exported = true)] [IntentFilter(new[] { Android.Content.Intent.ActionView }, Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable }, DataScheme = "https", DataHost = "my-url")] public class CustomTabRedirectActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); if (Intent?.Data != null) { // 获取MitID返回的跳转URL(即需要回到的自定义标签页面地址) var redirectUrl = Intent.Data.ToString(); // 构建自定义标签Intent,将已有的会话拉回前台 var customTabsIntent = new CustomTabsIntent.Builder().Build(); customTabsIntent.Intent.AddFlags(ActivityFlags.ReorderToFront); customTabsIntent.LaunchUrl(this, Android.Net.Uri.Parse(redirectUrl)); } // 立即关闭中转Activity,无需显示UI Finish(); } }
步骤2:配置透明主题
在Resources/values/styles.xml中添加透明主题定义(供中转Activity使用):
<style name="Theme.Transparent" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowIsTranslucent">true</item> <item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item> </style>
步骤3:调整MainActivity的IntentFilter
移除MainActivity中原本匹配https://my-url的IntentFilter,避免与中转Activity的配置冲突:
// 仅保留MainActivity原本的基础配置,移除DataScheme/DataHost相关的IntentFilter [Activity(Label = "app-A", LaunchMode = LaunchMode.SingleTask, Icon = "@mipmap/ic_launcher", RoundIcon = "@mipmap/ic_launcher_round", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, Exported = true)] public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity { // ... 原有代码 }
原理说明
- MitID认证完成后,会唤起匹配
https://my-url的CustomTabRedirectActivity(而非MainActivity) - 中转Activity获取跳转URL后,通过
ActivityFlags.ReorderToFront将之前打开的Chrome自定义标签会话拉回前台,继续完成登录流程 - 登录流程完成后,WebAuthenticator会通过预设的
callBackUri正常跳转回MainActivity
内容的提问来源于stack exchange,提问作者Vering
相关产品推荐
相关产品推荐

