等待活动关闭

本文关键字:活动 等待 | 更新日期: 2023-09-27 18:29:23

我使用Xamarin Auth在我的android应用程序中使用OneDrive进行身份验证。我认为这会起作用,但我的问题是,当登录提示的活动打开时,程序将继续,而不是等待验证完成。我如何才能等到它关闭,或者用其他异步方式包装它?

代码:

        private IDictionary<string, string> authenticationResponseValues;
    protected override async Task<AccountSession> GetAuthenticationResultAsync()
    {
        await Task.Run(() => ShowWebView());
        return new AccountSession(authenticationResponseValues, this.ServiceInfo.AppId, AccountType.MicrosoftAccount)
        {
            CanSignOut = true
        };
    }
    private void ShowWebView()
    {
        var auth = new OAuth2Authenticator(
                clientId: MSA_CLIENT_ID,
                scope: string.Join(",", scopes),
                authorizeUrl: new Uri(GetAuthorizeUrl()),
                redirectUrl: new Uri(RETURN_URL));

        auth.Completed += SetAccountInfos;
        var intent = auth.GetUI(Application.Context);
        intent.SetFlags(ActivityFlags.NewTask);
        Application.Context.StartActivity(intent);
    }
    private void SetAccountInfos(object sender, AuthenticatorCompletedEventArgs eventArgs)
    {
        if (eventArgs.IsAuthenticated)
        {
            Debug.WriteLine(eventArgs);
            Debug.WriteLine(eventArgs.Account == null ? "IS NULL" : "IS NOT NULL");
            if (eventArgs.Account != null)
            {
                OAuthErrorHandler.ThrowIfError(eventArgs.Account.Properties);
                authenticationResponseValues = eventArgs.Account.Properties;
            }
        }
    }

等待活动关闭

我认为使用异步策略是不合理的,因为应用程序在登录结果返回之前运行。

尝试使用同步方式。制作一个登录页面。如果成功,请切换到您的真实应用程序。

我找到了一个解决方案。这是我的代码:

await ShowWebView();
return new AccountSession(authenticationResponseValues, ServiceInfo.AppId,
            AccountType.MicrosoftAccount)
{
    CanSignOut = true
};
private Task<bool> ShowWebView()
    {
        var tcs = new TaskCompletionSource<bool>();
        var auth = new OAuth2Authenticator(OneDriveAuthenticationConstants.MSA_CLIENT_ID, string.Join(",", OneDriveAuthenticationConstants.Scopes), new Uri(GetAuthorizeUrl()),
            new Uri(OneDriveAuthenticationConstants.RETURN_URL));
        auth.Completed += (sender, eventArgs) =>
        {
            if (eventArgs.IsAuthenticated)
            {
                OAuthErrorHandler.ThrowIfError(eventArgs.Account.Properties);
                authenticationResponseValues = eventArgs.Account.Properties;
                tcs.SetResult(true);
            }
        };
        var intent = auth.GetUI(Application.Context);
        intent.SetFlags(ActivityFlags.NewTask);
        Application.Context.StartActivity(intent);
        return tcs.Task;
    }

以及指向回购中类别的链接:https://github.com/Apply-Solutions/MoneyManager/blob/master/Src/MoneyManager.Droid/Src/AndroidAuthenticationProvider.cs