Основано на this Я пытаюсь auth с google. Но генерируется исключение GoogleAuthException, а сообщение - «BadUsername». Это меня смущает, так как я выбираю адрес электронной почты/имя пользователя для учетной записи. Кто-нибудь понял, что я делаю неправильно?Аутентификация с помощью google
public class MainActivity extends Activity implements MainFragment.OnFragmentInteractionListener {
private static final String TAG = MainActivity.class.getSimpleName();
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
private static final String SCOPE =
"oauth2:https://www.googleapis.com/auth/userinfo.profile";
@Override
protected void onCreate(Bundle savedInstanceState) {
...
pickUserAccount();
}
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
Toast.makeText(this, mEmail, Toast.LENGTH_SHORT).show();
ConfirmEmailTask confirmEmailTask = new ConfirmEmailTask(this, SCOPE, mEmail);
confirmEmailTask.execute();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
// Toast.makeText(this, R.string.pick_account, Toast.LENGTH_SHORT).show();
}
}
// Later, more code will go here to handle the result from some exceptions...
}
public class ConfirmEmailTask extends AsyncTask<Void, Void, String> {
Activity mActivity;
String mScope;
String mEmail;
ConfirmEmailTask(Activity activity, String name, String scope) {
this.mActivity = activity;
this.mScope = scope;
this.mEmail = name;
}
/**
* Executes the asynchronous job. This runs when you call execute()
* on the AsyncTask instance.
*/
@Override
protected String doInBackground(Void... params) {
try {
String token = fetchToken();
if (token != null) {
return token;
// Insert the good stuff here.
// Use the token to access the user's Google data.
// Toast.makeText(mActivity, token, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (UserRecoverableAuthException userRecoverableException) {
Log.d(TAG, "error");
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
// mActivity.handleException(userRecoverableException);
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
Log.d(TAG, fatalException.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(mActivity, result, Toast.LENGTH_SHORT).show();
}
}
}
Ниже приведено описание stacktrace.
W/System.err﹕ com.google.android.gms.auth.GoogleAuthException: BadUsername
W/System.err﹕ at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
W/System.err﹕ at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
W/System.err﹕ at dk.eterno.bloatwareremover.MainActivity$ConfirmEmailTask.fetchToken(MainActivity.java:138)
W/System.err﹕ at dk.eterno.bloatwareremover.MainActivity$ConfirmEmailTask.doInBackground(MainActivity.java:115)
W/System.err﹕ at dk.eterno.bloatwareremover.MainActivity$ConfirmEmailTask.doInBackground(MainActivity.java:97)
W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
Журнал регистрации, единственная странная вещь, которую я вижу, это getUsername() на самом деле не идет никуда. Итак, сборщик учетных записей работает, вы получаете данные, бросаете действительный адрес электронной почты в google и получаете эту ошибку? –
Я удалил getUsername(). На данный момент я просто хочу поджарить токен. Я добавил stacktrace к моему вопросу. Похоже, что у некоторых людей была такая же ошибка. В основном потому, что они забыли префикс области с помощью oauth2: – user672009