2014-09-16 2 views
1

В моем приложении Android я запрашиваю токен google plus, который я отправляю на сервер. Я хочу иметь возможность получать информацию о пользователе, включая его адрес электронной почты на сервере.Android, запрашивающий Google + адрес электронной почты пользователя

Вот вызов, который работает, но не дает мне по электронной почте:

GoogleAuthUtil.getToken(activity, Plus.AccountApi.getAccountName(googleApiClient), "oauth2:" + Scopes.PLUS_ME + " " + Scopes.PLUS_LOGIN + " " + Scopes.PROFILE); 

С ним я только получить эту информацию:

{ 

    "id": "11213535252359196332836", 
    "name": "Name Surname", 
    "given_name": "Name", 
    "family_name": "Surname", 
    "link": "https://plus.google.com/+laskdjfksdjf", 
    "picture": "https://asdfsdafasdfasdfasdfasdfasdfsdaf7c/photo.jpg", 
    "gender": "male", 
    "locale": "en" 

} 

я обнаружил, что мне нужно попросить userinfo.email разрешение, поэтому я изменил мой вызов:

GoogleAuthUtil.getToken(activity, Plus.AccountApi.getAccountName(googleApiClient), "oauth2:" + Scopes.PLUS_ME + " " + Scopes.PLUS_LOGIN + " " + Scopes.PROFILE + " https://www.googleapis.com/auth/userinfo.email"); 

проблема заключается в том, что теперь getToken() возвращает мне эту ошибку:

09-16 18:53:57.311: W/System.err(26467): com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission 
09-16 18:53:57.316: W/System.err(26467): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source) 
09-16 18:53:57.316: W/System.err(26467): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source) 
09-16 18:53:57.316: W/System.err(26467): at lt.sm.discountcity.GPlus.getServerOnlineToken(GPlus.java:237) 
09-16 18:53:57.316: W/System.err(26467): at lt.sm.discountcity.fragments.LoginFragment$5$1.runOnSeparateThread(LoginFragment.java:173) 
09-16 18:53:57.316: W/System.err(26467): at lt.smtools.tasks.TaskManager$2.run(TaskManager.java:139) 
09-16 18:53:57.316: W/System.err(26467): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
09-16 18:53:57.316: W/System.err(26467): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
09-16 18:53:57.316: W/System.err(26467): at java.lang.Thread.run(Thread.java:841) 

Любые идеи, что я делаю неправильно и как это решить?

+1

возможно дубликат [UserRecoverableAuthException: NeedPermission] (http://stackoverflow.com/questions/14383965/userrecoverableauthexception-needpermission) – njzk2

+0

возможно дубликат [Google+ не возвращает адрес электронной почты друга пользователя в] (http://stackoverflow.com/questions/24262227/google-does-not-return-users-friends-email-address) – DaImTo

+0

Я видел первый пост, и я не понимаю, как второй пост дублируется, потому что он рассказывает о том, как получить друзей по электронной почте, а не от пользователя, который вошел в систему. Решение для первого сообщения помещает меня в бесконечный цикл. – SMart

ответ

0

http://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html

void getAndUseAuthTokenBlocking() { 
    try { 
     // Retrieve a token for the given account and scope. It will always return either 
     // a non-empty String or throw an exception. 
     final String token = GoogleAuthUtil.getToken(Context, String, String)(context, email,  scope); 
     // Do work with token. 
     ... 
     if (server indicates token is invalid) { 
      // invalidate the token that we found is bad so that GoogleAuthUtil won't 
      // return it next time (it may have cached it) 
      GoogleAuthUtil.invalidateToken(Context, String)(context, token); 
      // consider retrying getAndUseTokenBlocking() once more 
      return; 
     } 
     return; 
    } catch (GooglePlayServicesAvailabilityException playEx) { 
    Dialog alert = GooglePlayServicesUtil.getErrorDialog(
     playEx.getConnectionStatusCode(), 
     this, 
     MY_ACTIVITYS_AUTH_REQUEST_CODE); 
    ... 
    } catch (UserRecoverableAuthException userAuthEx) { 
     // Start the user recoverable action using the intent returned by 
     // getIntent() 
     myActivity.startActivityForResult(
       userAuthEx.getIntent(), 
       MY_ACTIVITYS_AUTH_REQUEST_CODE); 
     return; 
    } catch (IOException transientEx) { 
     // network or server error, the call is expected to succeed if you try again later. 
     // Don't attempt to call again immediately - the request is likely to 
     // fail, you'll hit quotas or back-off. 
     ... 
     return; 
    } catch (GoogleAuthException authEx) { 
     // Failure. The call is not expected to ever succeed so it should not be 
     // retried. 
     ... 
     return; 
    } 
    } 
+0

Если я добавлю эту строку: activity.startActivityForResult (e.getIntent(), RC_AUTHORIZATION); в блоке catch UserRecoverableAuthException мое приложение запускает бесконечный цикл с помощью google plus, входящего в систему, выпадающего окна разрешения доступа, а затем регистрируется снова и снова и снова и снова ... и СНОВА! – SMart

Смежные вопросы