Xamarin Form Android:SEND Intent场景下WebAuthenticator未关闭Chrome
问题
我开发了一个Xamarin Form Android应用,用于分享图片。需求是首次使用应用分享内容时需登录,采用WebAuthenticator实现OAuth2认证。该认证能正常重定向回应用,但Google Chrome浏览器仍在后台运行未关闭。正常应用登录场景下浏览器会自动关闭,但通过SEND Intent触发登录时则不会。
相关代码如下:
WebAuthenticator认证代码
var authResult = await WebAuthenticator.AuthenticateAsync(new WebAuthenticatorOptions { Url = new Uri($"{_baseUrl}"), CallbackUrl = new Uri("callback://") });
WebAuthenticationCallbackActivity代码
[Activity(NoHistory = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTop, Exported = true)] [IntentFilter(new[] { Android.Content.Intent.ActionView }, Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable }, DataScheme = "callback")] public class WebAuthenticationCallbackActivity : Xamarin.Essentials.WebAuthenticatorCallbackActivity { }
Android清单文件配置
<intent> <action android:name="android.support.customtabs.action.CustomTabsService" /> </intent>
请问缺少哪些配置导致浏览器未关闭?
解决方案
问题根源是SEND Intent启动应用时,任务栈结构和直接启动不同,导致Custom Tab无法正确关联并自动关闭,需要补充以下配置和修改:
优化回调Activity的任务栈配置
在WebAuthenticationCallbackActivity的特性中添加TaskAffinity=""和ExcludeFromRecents="true",让回调Activity处于独立任务栈,认证完成后可彻底清理浏览器相关会话:[Activity(NoHistory = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTop, Exported = true, TaskAffinity = "", ExcludeFromRecents = true)] [IntentFilter(new[] { Android.Content.Intent.ActionView }, Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable }, DataScheme = "callback")] public class WebAuthenticationCallbackActivity : Xamarin.Essentials.WebAuthenticatorCallbackActivity { }强制使用临时浏览器会话
在WebAuthenticator调用时开启临时会话选项,确保认证后浏览器自动关闭:var authResult = await WebAuthenticator.AuthenticateAsync(new WebAuthenticatorOptions { Url = new Uri($"{_baseUrl}"), CallbackUrl = new Uri("callback://"), PrefersEphemeralWebBrowserSession = true });完善Custom Tab服务的清单配置
你当前的清单配置不完整,需要将Custom Tab服务声明放在<application>标签内的<service>节点中:<application ...> <service android:name="androidx.browser.customtabs.CustomTabsService" android:exported="true"> <intent-filter> <action android:name="android.support.customtabs.action.CustomTabsService" /> </intent-filter> </service> </application>调整分享接收Activity的启动模式
处理SEND Intent的Activity设置SingleTask启动模式,避免创建新任务栈,让WebAuthenticator能正确关联当前应用任务:[Activity(LaunchMode = Android.Content.PM.LaunchMode.SingleTask, ...)] public class ShareReceiverActivity : Activity { // 分享Intent处理逻辑 }
以上修改通过统一任务栈关联、强制临时会话等方式,确保认证完成后Chrome浏览器能自动关闭,不会留在后台。
内容的提问来源于stack exchange,提问作者abani samal

