首页 > 解决方案 > AbstractAccountAuthenticator 只允许 1 个帐户

问题描述

我已将 AbstractAccountAuthenticator 实现为使用 SyncAdapter 的要求,但我的应用程序一次仅支持 1 个帐户。

当用户尝试通过设置添加另一个帐户时 - 设置崩溃并出现停止工作的错误。

我见过一些应用程序,例如LinkedIn、Facebook,它们以不同的方式处理它向用户显示吐司消息,并声明只支持一个帐户。我怎样才能实现这个功能?

这是我的验证器

class ApplicationAuthenticator(private val context: Context) : AbstractAccountAuthenticator(context) {

    // Editing properties is not supported
    @Throws(UnsupportedOperationException::class)
    override fun editProperties(response: AccountAuthenticatorResponse,
                                accountType: String): Bundle? {

        throw UnsupportedOperationException()
    }

    // Don't add additional accounts
    override fun addAccount(response: AccountAuthenticatorResponse, accountType: String,
                            authTokenType: String, features: Array<String>,
                            options: Bundle): Bundle? {

        return bundleOf(AccountManager.KEY_INTENT to null)
    }

    // Ignore attempts to confirm credentials
    @Throws(NetworkErrorException::class)
    override fun confirmCredentials(response: AccountAuthenticatorResponse, account: Account,
                                    options: Bundle): Bundle? {

        return null
    }

    // Getting an authentication token is not supported
    @Throws(NetworkErrorException::class, UnsupportedOperationException::class)
    override fun getAuthToken(response: AccountAuthenticatorResponse, account: Account,
                              authTokenType: String, loginOptions: Bundle): Bundle? {

        throw UnsupportedOperationException()
    }

    // Getting a label for the auth token is not supported
    override fun getAuthTokenLabel(authTokenType: String): String {
        return context.resources.getString(R.string.application_name)
    }

    // Updating user credentials is not supported
    override fun updateCredentials(response: AccountAuthenticatorResponse, account: Account,
                                   authTokenType: String, loginOptions: Bundle): Bundle? {

        return null
    }

    // Checking features for the account is not supported
    @Throws(NetworkErrorException::class)
    override fun hasFeatures(response: AccountAuthenticatorResponse, account: Account,
                             features: Array<String>): Bundle {

        return bundleOf(KEY_BOOLEAN_RESULT to false)
    }

}

标签: androidandroid-syncadapterandroid-authenticator

解决方案


当用户单击“添加帐户”按钮时,Android 只会调用addAccount您的ApplicationAuthenticator. 作为回报,它期望创建帐户、启动帐户设置的 Intent 或错误。

如果您不允许多个帐户,您可以在此处有多个选项:

  • 返回带有代码ERROR_CODE_UNSUPPORTED_OPERATION的错误。虽然我还没有尝试过。
  • 返回您现有的帐户作为结果。此时您还可以显示一个Toast.

    要返回现有帐户,只需addAccount返回Bundle带有以下键及其各自值的 a:

    已添加帐户的 AccountManager.KEY_ACCOUNT_NAME 和 AccountManager.KEY_ACCOUNT_TYPE,或

  • 返回一个Intent不创建帐户但向用户解释这是不受支持/不必要的操作的 Activity。Activity 不需要实际添加帐户。

    这为 IMO 提供了最佳的用户体验。


推荐阅读