I've been trying to implement an app which saves user accounts (id, password and token) with the Android AccountManager. Been using this as my reference for implementing the functionality.
I am able to show my AuthenticationActivity and create accounts (which show up correctly in the Settings > Accounts
after I create them). After I add a new account I try to immediately login the user with the token received which I save with setAuthToken()
. However this never works and I see that the authToken
is always null. I then have to run the app for a second time and login again after which it works.
The code where I add a new account (from my signup activity) is,
private void addNewAccount(final AccountManager am, final String accountType, String authTokenType) {
Log.d(TAG, "addNewAccount(): " + accountType + ", " + authTokenType);
am.addAccount(accountType, authTokenType, null, null, this, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
final String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.d(TAG, "addNewAccount() -> bundle = " + bundle + ", authToken = " + authToken);
if (!TextUtils.isEmpty(authToken)) {
startLoggedInActivity(authToken);
} else {
Log.d(TAG, "token is null"); // <- always get here
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, null);
}
And the code where I finish the login (after I receive the token and add the new user) is,
private void finishLogin(Intent intent) {
Log.d(TAG, "finishLogin(): " + intent.getExtras());
if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT).show();
setResult(RESULT_CANCELED, intent);
} else {
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, accountPassword, null);
Log.d(TAG, "finishLogin() -> addAccountExplicitly: " + account + ", " + accountPassword);
mAccountManager.setAuthToken(account, mAuthTokenType, authtoken);
Log.d(TAG, "finishLogin() -> setAuthToken: " + authtoken);
} else {
mAccountManager.setPassword(account, accountPassword);
Log.d(TAG, "finishLogin() -> setPassword: " + account + ", " + accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
}
finish();
}
Does anyone know what the problem could be (been struggling with this for quite some time now :( )?