UserRecoverableAuthException: NeedPermission
Я попытался выполнить руководство: https://developers.google.com/android/guides/http-auth.
код:
token = GoogleAuthUtil.getToken(getApplicationContext(),
mEmail, mScope);
манифеста:
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.NETWORK"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>
<uses-permission android:name="android.permission.INTERNET"/>
Ошибки:
01-17 18:37:38.230: W/System.err(3689): com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission
01-17 18:37:38.230: W/System.err(3689): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
01-17 18:37:38.230: W/System.err(3689): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
01-17 18:37:38.230: W/System.err(3689): at com.example.mgoogleauth.MainActivity$GetIOStreamTask.doInBackground(MainActivity.java:39)
01-17 18:37:38.230: W/System.err(3689): at com.example.mgoogleauth.MainActivity$GetIOStreamTask.doInBackground(MainActivity.java:1)
01-17 18:37:38.230: W/System.err(3689): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-17 18:37:38.230: W/System.err(3689): at java.lang.Thread.run(Thread.java:856)
Ответы
Ответ 1
Попробуйте выполнить быстрый запуск программы для Android, это пошаговое руководство, показывающее, как разрешить и загрузить файл на диск: https://developers.google.com/drive/quickstart-android p >
Чтобы быть более конкретным, похоже, что вы не улавливаете исключение UserRecoverableException и запускаете намерение разрешить пользователю авторизацию приложения.
Это описано в документах Google Play Services, которые вы связали и обработали в примере быстрого запуска следующим образом:
...
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
...
Ответ 2
метод getAndUseAuthTokenBlocking() официального официального руководства GoogleAuthUtil объясняет, как справиться с этим исключением:
// Example of how to use the GoogleAuthUtil in a blocking, non-main thread context
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;
}
}
Ответ 3
У меня была такая же ошибка, в моем случае я использовал неправильную область, я просто изменяю
https://www.googleapis.com/auth/plus.login
для
https://www.googleapis.com/auth/userinfo.profile
Ответ 4
На этой странице документации
https://developers.google.com/+/mobile/android/sign-in в этом примере есть хорошее объяснение этого исключения.
В частности, похоже, что эта строка должна быть отмечена:
Запрос кода авторизации всегда будет вызывать UserRecoverableAuthException при первом вызове GoogleAuthUtil.getToken
catch (UserRecoverableAuthException e) {
// Requesting an authorization code will always throw
// UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
// because the user must consent to offline access to their data. After
// consent is granted control is returned to your activity in onActivityResult
// and the second call to GoogleAuthUtil.getToken will succeed.
startActivityForResult(e.getIntent(), AUTH_CODE_REQUEST_CODE);
return;
}
Ответ 5
Документы были недавно обновлены и теперь работают для поддержки SDK M (с запросом разрешения), а также отображаются диалоговое окно OAuth.
Примечание
Документы Google часто не обновляются, но, похоже, они обращают внимание, когда вы сообщаете о проблеме. Пример был обновлен через неделю, когда я отправил отзыв. Поэтому, если вы видите нерабочий пример, отправьте отзыв!
https://developers.google.com/drive/v3/web/quickstart/android