Android开发(40) 使用Android系统的账户中心

概述

在android的系统设置页,有个“账户”分组,里面有很多的账户,很多app都使用了这个账户系统,比如“谷歌”,“淘宝”,“微信”,“华为”等。这些都是大公司呢,有没有可能我们也使用这个,让我们的软件的名称也出现在这里呢,答应是肯定的。看看效果图:

2044033-ac5c0cb045c7dccf.jpg

2044033-0fc158e432f95df7.jpg

2044033-7b01cbdf7dbd4517.jpg

加上这个,我们的app立马就高大上了,如何做到呢?

实现步骤

  1. 继承 AbstractAccountAuthenticator 实现 一个 自己的 账户认证器
  2. 继承自 service,实现一个服务,该服务使用上一步的 账户认证器
  3. 继承 AccountAuthenticatorActivity ,实现 自定义的 登录页面。

知识准备

你需要了解 上面积个类的知识,和accountManager,我翻译了这几个类的概述,参考我前几篇文章。

http://www.jianshu.com/p/82311e1ce09e
http://www.jianshu.com/p/044c31c3f48d

实现

如果被系统发现?

自定义的服务代码如下:

<service
        android:name=".MyAuthenticatorService"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/authenticator" />
    </service>

我们看到,这个service 指定了过滤器为 android.accounts.AccountAuthenticator,这是个系统调用的 action。

自定义 认证器 做了什么?

我们需要在定义认证器里实现 它的 addAccount 和 getAuthToken 方法。

addAccount方法: 在api里解释说,在 添加账户时,需要从用户收集认证信息(账户名和密码),需要返回一个intent,以打开一个activity,这个activity就是我们登陆页了。我们需要在登录页里处理登录的逻辑实现,并使用AccountManager记录下 登录成功的用户信息,并保存在账户中心。

getAuthToken方法: 获得auth Token ,这是一个授权标记,有些地方翻译为“令牌”,就是从服务端返回的字符串,指示了登录成功。很多系统不在本地(手机)保存真实的密码,配合auth token 来显示一次登录认证,后续的操作请求都携带auth token作为身份令牌。

@Override
public Bundle addAccount(AccountAuthenticatorResponse response,
        String accountType, String authTokenType,
        String[] requiredFeatures, Bundle options)
        throws NetworkErrorException {
    // 需要实现
    Log.v(TAG, "addAccount()");
    final Intent intent = new Intent(mContext, LoginActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final 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;
}

演示下载: http://yunpan.cn/cAIvcxDHZjrIS 访问密码 d8f7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值