Google的Android文档(http://developer.android.com/reference/android/accounts/AccountManager.html#addAccountExplicitly(android.accounts.Account, java.lang. net)。字符串,android.os.Bundle))说:
如果帐户已成功添加,则为True,如果帐户未添加,则为false已存在、帐户为空或发生其他错误
我是假的。具体来说,还有哪些错误会导致这种情况?
false if the account already exists
如果没有提供任何信息,这可能是您得到false的原因
AccountManagerService
是管理帐户的实际系统服务,而AccountManager
只是隐藏所有绑定服务相关内容的代理。
以下addAccountInternal
方法的源代码从AccountManagerService
是相当不言自明的,除了如果你传递null
为account
,那么IllegalArgumentException
将被抛出,而不是执行这个方法:
private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Bundle extras, boolean restricted, int callingUid) {
if (account == null) {
return false;
}
synchronized (accounts.cacheLock) {
final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
db.beginTransaction();
try {
long numMatches = DatabaseUtils.longForQuery(db,
"select count(*) from " + TABLE_ACCOUNTS
+ " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
new String[]{account.name, account.type});
if (numMatches > 0) {
Log.w(TAG, "insertAccountIntoDatabase: " + account
+ ", skipping since the account already exists");
return false;
}
ContentValues values = new ContentValues();
values.put(ACCOUNTS_NAME, account.name);
values.put(ACCOUNTS_TYPE, account.type);
values.put(ACCOUNTS_PASSWORD, password);
values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
if (accountId < 0) {
Log.w(TAG, "insertAccountIntoDatabase: " + account
+ ", skipping the DB insert failed");
return false;
}
if (extras != null) {
for (String key : extras.keySet()) {
final String value = extras.getString(key);
if (insertExtraLocked(db, accountId, key, value) < 0) {
Log.w(TAG, "insertAccountIntoDatabase: " + account
+ ", skipping since insertExtra failed for key " + key);
return false;
}
}
}
db.setTransactionSuccessful();
logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
accounts, callingUid);
insertAccountIntoCacheLocked(accounts, account);
} finally {
db.endTransaction();
}
sendAccountsChangedBroadcast(accounts.userId);
}
if (accounts.userId == UserHandle.USER_OWNER) {
addAccountToLimitedUsers(account);
}
return true;
}
底线:addAccountExplicitly
将返回false
,如果所需的帐户已经存在,或者一些SQLite数据库错误阻止了在数据库中存储帐户相关信息。
确保你是连接到互联网!在我的情况下,这就是问题所在!
if (accountManager.addAccountExplicitly(_account, null, null)) {
System.out.println("_add account if");
}else {
// This block is also executed in case device has no internet connection
}