创建桩身份验证器

同步适配器框架假定您的同步适配器在与帐号相关联的设备存储空间和需要登录访问权限的服务器存储空间之间传输数据。因此,框架要求您在同步适配器中提供一个名为“身份验证器”的组件。此组件可插入到 Android 帐号和身份验证框架中,并提供用于处理登录信息等用户凭据的标准界面。

即使您的应用不使用帐号,您也需要提供身份验证器组件。如果您不使用帐号或服务器登录信息,则身份验证器处理的信息会被忽略,因此您可以提供包含桩方法实现的身份验证器组件。您还需要提供绑定 Service,以允许同步适配器框架调用身份验证器的方法。

本课介绍了如何定义桩身份验证器的所有部分,以满足同步适配器框架的要求。如果您需要提供真正的身份验证器来处理用户帐号,请参阅 AbstractAccountAuthenticator 的参考文档。

添加桩身份验证器组件

如需向应用添加桩身份验证器组件,请创建一个扩展 AbstractAccountAuthenticator 的类,然后通过返回 null 或抛出异常来为所需的方法打桩。

以下代码段展示了桩身份验证器类的一个示例:

Kotlin

/*
 * Implement AbstractAccountAuthenticator and stub out all
 * of its methods
 */
class Authenticator(context: Context) // Simple constructor
    : AbstractAccountAuthenticator(context) {

    // Editing properties is not supported
    override fun editProperties(r: AccountAuthenticatorResponse, s: String): Bundle {
        throw UnsupportedOperationException()
    }

    // Don't add additional accounts
    @Throws(NetworkErrorException::class)
    override fun addAccount(
            r: AccountAuthenticatorResponse,
            s: String,
            s2: String,
            strings: Array<String>,
            bundle: Bundle
    ): Bundle?  = null

    // Ignore attempts to confirm credentials
    @Throws(NetworkErrorException::class)
    override fun confirmCredentials(
            r: AccountAuthenticatorResponse,
            account: Account,
            bundle: Bundle
    ): Bundle?  = null

    // Getting an authentication token is not supported
    @Throws(NetworkErrorException::class)
    override fun getAuthToken(
            r: AccountAuthenticatorResponse,
            account: Account,
            s: String,
            bundle: Bundle
    ): Bundle {
        throw UnsupportedOperationException()
    }

    // Getting a label for the auth token is not supported
    override fun getAuthTokenLabel(s: String): String {
        throw UnsupportedOperationException()
    }

    // Updating user credentials is not supported
    @Throws(NetworkErrorException::class)
    override fun updateCredentials(
            r: AccountAuthenticatorResponse,
            account: Account,
            s: String,
            bundle: Bundle
    ): Bundle {
        throw UnsupportedOperationException()
    }

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

Java

/*
 * Implement AbstractAccountAuthenticator and stub out all
 * of its methods
 */
public class Authenticator extends AbstractAccountAuthenticator {
    // Simple constructor
    public Authenticator(Context context) {
        super(context);
    }
    // Editing properties is not supported
    @Override
    public Bundle editProperties(
            AccountAuthenticatorResponse r, String s) {
        throw new UnsupportedOperationException();
    }
    // Don't add additional accounts
    @Override
    public Bundle addAccount(
            AccountAuthenticatorResponse r,
            String s,
            String s2,
            String[] strings,
            Bundle bundle) throws NetworkErrorException {
        return null;
    }
    // Ignore attempts to confirm credentials
    @Override
    public Bundle confirmCredentials(
            AccountAuthenticatorResponse r,
            Account account,
            Bundle bundle) throws NetworkErrorException {
        return null;
    }
    // Getting an authentication token is not supported
    @Override
    public Bundle getAuthToken(
            AccountAuthenticatorResponse r,
            Account account,
            String s,
            Bundle bundle) throws NetworkErrorException {
        throw new UnsupportedOperationException();
    }
    // Getting a label for the auth token is not supported
    @Override
    public String getAuthTokenLabel(String s) {
        throw new UnsupportedOperationException();
    }
    // Updating user credentials is not supported
    @Override
    public Bundle updateCredentials(
            AccountAuthenticatorResponse r,
            Account account,
            String s, Bundle bundle) throws NetworkErrorException {
        throw new UnsupportedOperationException();
    }
    // Checking features for the account is not supported
    @Override
    public Bundle hasFeatures(
        AccountAuthenticatorResponse r,
        Account account, String[] strings) throws NetworkErrorException {
        throw new UnsupportedOperationException();
    }
}

将身份验证器绑定到框架

为了让同步适配器框架能够访问您的身份验证器,您必须为其创建绑定 Service。此服务提供了一个 Android binder 对象,以允许框架调用身份验证器并在身份验证器和框架之间传递数据。

以下代码段展示了如何定义绑定 Service

Kotlin

/**
* A bound Service that instantiates the authenticator
* when started.
*/
class AuthenticatorService : Service() {

    // Instance field that stores the authenticator object
    private lateinit var mAuthenticator: Authenticator

    override fun onCreate() {
        // Create a new authenticator object
        mAuthenticator = Authenticator(getApplicationContext())
    }

    /*
     * When the system binds to this Service to make the RPC call
     * return the authenticator's IBinder.
     */
    override fun onBind(intent: Intent?): IBinder = mAuthenticator.iBinder
}

Java

/**
 * A bound Service that instantiates the authenticator
 * when started.
 */
public class AuthenticatorService extends Service {
    ...
    // Instance field that stores the authenticator object
    private Authenticator mAuthenticator;
    @Override
    public void onCreate() {
        // Create a new authenticator object
        mAuthenticator = new Authenticator(getApplicationContext());
    }
    /*
     * When the system binds to this Service to make the RPC call
     * return the authenticator's IBinder.
     */
    @Override
    public IBinder onBind(Intent intent) {
        return mAuthenticator.getIBinder();
    }
}

添加身份验证器元数据文件

如需将身份验证器组件插入到同步适配器框架和帐号框架中,您需要为这些框架提供描述该组件的元数据。此元数据声明您为同步适配器创建的帐号类型,并声明您希望让用户看到您的帐号类型时系统显示的界面元素。请在一个 XML 文件中声明此元数据,该文件存储在应用项目的 /res/xml/ 目录中。您可以为该文件指定任何名称,但通常将它命名为 authenticator.xml

此 XML 文件包含一个元素 <account-authenticator>,该元素具有以下属性:

android:accountType
同步适配器框架要求每个同步适配器都具有域名形式的帐号类型。该框架会将帐号类型用作同步适配器内部标识的一部分。对于需要登录的服务器,帐号类型和用户帐号会作为登录凭据的一部分发送到服务器。

即使服务器不要求提供登录信息,您仍然需要提供账号类型。对于该值,请使用由您控制的域名。虽然框架使用该值来管理您的同步适配器,但该值不会发送到您的服务器。

android:icon
指向包含图标的可绘制对象资源的指针。如果您通过在 res/xml/syncadapter.xml 中指定 android:userVisible="true" 属性将同步适配器设为可见,则必须提供此图标资源。该图标会显示在系统“设置”应用的帐号部分。
android:smallIcon
指向包含小版图标的可绘制资源的指针。根据屏幕尺寸的需要,系统“设置”应用的帐号部分可能会使用此资源来代替 android:icon
android:label
用于向用户标识帐号类型的可本地化字符串。如果您通过在 res/xml/syncadapter.xml 中指定 android:userVisible="true" 属性来将同步适配器设为可见,则应提供此字符串。该字符串会显示在系统“设置”应用的帐号部分内,位于您为身份验证器定义的图标旁边。

以下代码段显示了您之前创建的身份验证器的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<account-authenticator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:accountType="example.com"
        android:icon="@drawable/ic_launcher"
        android:smallIcon="@drawable/ic_launcher"
        android:label="@string/app_name"/>

在清单中声明身份验证器

在上一步中,您创建了绑定 Service,用于将身份验证器关联到同步适配器框架。如需向系统标识此服务,请通过将以下 <service> 元素添加为 <application> 的子元素,在应用清单中声明此服务:

    <service
            android:name="com.example.android.syncadapter.AuthenticatorService">
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator"/>
        </intent-filter>
        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/authenticator" />
    </service>

<intent-filter> 元素设置由 intent 操作 android.accounts.AccountAuthenticator 触发的过滤器,系统发送该操作以运行身份验证器。当过滤器被触发时,系统会启动 AuthenticatorService,即您提供的用于封装身份验证器的绑定 Service

<meta-data> 元素声明身份验证器的元数据。android:name 属性将元数据关联到身份验证框架。android:resource 元素指定您之前创建的身份验证器元数据文件的名称。

除身份验证器之外,同步适配器还需要内容提供器。如果您的应用尚未使用 content provider,请转到下一课,了解如何创建桩内容提供器;否则,请转到创建同步适配器一课。