问题
I've implemented my AccountManager authenticator and the service and the whole deal and it all seems to be working fine.
There is, however, one little problem: I only want a single account for my app to exist in account manager, but can't quite seem to find a way to limit this.
Is my only solution to do a search and delete the current accounts (by type) before adding the new account?
My current code:
private void removeAccounts()
{
Account [] accounts = mAcctMgr.getAccountsByType (mAccountType);
if (accounts.length == 0) return;
final Handler handler = new Handler ();
AccountManagerCallback<Boolean> callback = new AccountManagerCallback<Boolean>()
{
@Override
public void run(AccountManagerFuture<Boolean> arg0)
{
// nada
}
};
for (Account a : accounts) {
mAcctMgr.removeAccount (a, callback, handler);
}
}
I don't by any means call this an elegant solution, but at the moment seems to be the only thing that works.
回答1:
Per the javadocs for addAccount(), if an error condition occurs when creating the account, you should return a bundle that contains the KEY_ERROR_CODE
and KEY_ERROR_MESSAGE
parameters,
if (accountExists) {
final Bundle result = new Bundle();
result.putInt(AccountManager.KEY_ERROR_CODE, ERROR_CODE_ONE_ACCOUNT_ALLOWED);
result.putString(AccountManager.KEY_ERROR_MESSAGE, context.getString(R.string.one_account_allowed));
handler.post(new Runnable() {
@Override
public void run() {
RepeatSafeToast.show(context, R.string.one_account_allowed);
}
});
return result;
}
Returning null
does not mean failure, it means that the result will be communicated through the response parameter to the addAccount()
method.
回答2:
In the addAccount function of your Authenticator class (the one which extends AbstractAccountAuthenticator), first check if an account exists. If an account already exists, just return null (And maybe show a toast message). If there are no accounts, just return the bundle like you were doing before.
if(AccountHelper.accountExists(mContext)) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, "Only one account allowed", Toast.LENGTH_SHORT).show();
}
});
return null;
}
回答3:
That link says how rename an account, which may be equivalent to your request renameAccount on developer.Android. However it is only available from API-level 21. If somebody gets a way to make it for earlier devices, please share!
来源:https://stackoverflow.com/questions/8832046/disallow-multiple-accounts-in-accountmanager