整体理解
Android帐号同步是一个系统的机制,是由系统调度的,可以配置运行策略的同步机制,实际上通常是配合同步适配器工作的https://developer.android.google.cn/training/sync-adapters/index.html
从文档的描述及实际的使用方式来看,帐号同步机制应该是同步适配器的延伸,就是需要同步的数据是需要验证身份和用户凭据的
帐号
这里的帐号和不是我们通常理解的App的帐号,App的帐号相关信息是由App的服务器存储的,这里帐号是由Android系统提供的服务存储的,可以理解为帐号的服务端是系统,系统负责存储这些帐号的相关信息,并且,文档提到,不应该在这里存储敏感的用户信息,因为root后这里的数据将可以被读取
帐号同步的实现
下边实现一个完整的帐号同步的例子,以pixel 2手机为例,其他手机的界面可能不太一样,但功能应该是一致的
如果实现了帐号同步并添加了帐号,在系统的设置-帐号界面是能看到我们添加的帐号的,在添加帐号界面,则会显示我们App的帐号类型
添加身份验证器
public class AccountAuthenticator extends AbstractAccountAuthenticator {
private Context mContext;
public AccountAuthenticator(Context context) {
super(context);
mContext = context;
}
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
Intent intent = new Intent(mContext, AddAccountActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
return null;
}
//...其他方法空实现即可
}
添加身份验证器服务
这个服务是系统与应用交互的入口,注册了这个服务,系统就能找到应用中帐号身份验证器并与应用交互,这里只需要简单实例化AccountAuthenticator
并返回一个IBinder
对象即可,系统已经把主要的逻辑已经在AccountAuthenticator
的父类AbstractAccountAuthenticator
里封装好了
class AuthenticatorService : Service() {
private var accountAuthenticator: AccountAuthenticator? = null
override fun onCreate() {
super.onCreate()
accountAuthenticator = AccountAuthenticator(this)
}
override f