2016-01-08 105 views
0

我使用Xamarin身份验证在我的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; 
      } 
     } 
    } 
+0

你如何展示你的登录?通过'startActivityForResult',一连串的活动... – SushiHangover

+0

我添加了意图的代码。对不起,我首先忘记了它。我用startActivityForResult用不同的int值(例如-1,0,1)尝试了它,但那也不起作用。 – NPadrutt

回答

0

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

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

+0

有一个登录页面。但问题出在Application.Context.StartActivity(intent)之后;它只是离开该方法,并返回新的AccountSession为null,因为没有调用SetAccountInfos的authenticationResponseValues。我需要一种方法来等待,直到这个方法被调用来继续。 – NPadrutt

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