等到活动结束

时间:2016-01-08 00:20:26

标签: c# android xamarin xamarin.android

我使用Xamarin Auth在我的Android应用程序中使用OneDrive进行身份验证。我认为这可行,但我有一个问题,当打开登录提示的活动时,程序将继续,而不是等待auth完成。 我怎么能等到它关闭或以异步方式包装它?

代码:

        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;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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