Android系统为外部服务提供了账号登录的机制,用于同步数据等作用。
进入设置->账户->添加账户,即可看到目前手机上有哪些App提供了同步服务。
接下来将会演示如何在App中定义登录服务并添加一个登录选项到这里。
账户的授权和同步
账户功能主要有2个:授权和同步。
授权:即账户登录怎么把关,可以通过验证账户密码的形式,也允许直接通过AccountManager的addAcount接口直接添加账户。
需要继承AbstractAccountAuthenticator来实现我们自己的授权机制。
同步:以邮箱账户为例,在添加一个Exchange邮箱账户后,我们可以看到它提供了联系人,日历,邮件等同步功能,这些同步服务每一项都需要App来继承实现AbstractThreadedSyncAdapter,用于该项的同步。
简单的演示
如何添加登录入口
第一步:实现AbstractAccountAuthenticator
在res/xml下添加一个xml,用于定义account-authenticator的以下属性:
sample_authenticator.xml
<account-authenticator
xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="com.android.test"
android:icon="@drawable/ic_account_icon"
android:smallIcon="@drawable/ic_account_icon"
android:label="@string/account_title"/>
accountType -> 自定义的一个串,一般为包名
icon -> 图标
smallIcon -> 小图标,可能用于显示在状态栏等空间较小的地方
label -> 显示的账户名
接下来实现一个实现一个AbstractAccountAuthenticator,重点是实现addAccount方法的行为,现在先忽略具体实现。
public class TestAuthenticator extends AbstractAccountAuthenticator {
Context mContext;
AccountManager mManager;
public TestAuthenticator(Context context) {
super(context);
mContext = context;
mManager = AccountManager.get(context);
}
@Override
public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String s) {
throw new UnsupportedOperationException();
}
@Override
public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse, String s, String s1, String[] strings, Bundle bundle) throws NetworkErrorException {
//这里可以返回包含Login界面Intent的Bunble,在点击添加这个账户后就能进入我们自定义的登录界面
return null;
}
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle bundle) throws NetworkErrorException {
return null;
}
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException {
return null;
}
@Override
public String getAuthTokenLabel(String s) {
return null;
}
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException {
return null;
}
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] strings) throws NetworkErrorException {
return null;
}
}
第二步:实现Service和声明权限
实现一个Service,AccountManagerService需要通过Service来获取Authenticator中的的Binder,通过Binder回调来获取到我们自定义的登录行为。
在onBind中,我们需要返回TestAuthenticator中的IBinder:
public class TestAuthenticateService extends Service {
TestAuthenticator mAuthenticator;
@Override
public void onCreate() {
super.onCreate();
mAuthenticator = new TestAuthenticator(this.getApplicationContext());
}
@Override
public IBinder onBind(Intent intent) {
//限制了只有在AccountManagerService绑定service