Disallow multiple accounts in AccountManager

跟風遠走 提交于 2019-11-30 07:01:48

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.

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;
    }

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!