xamarin Android 利用 AccountManager 实现多个APP间共享数据

在上上个星期,客户又有了很炫酷的需求。需求如下:
有 A 和 B 两个 APP,A 登录成功后,把验证身份用的 token 保存在 AccountManager 中,此时 B 要登录账号,先检查 Account 中是否有对应的token,有则自动 login,没有就按部就班手动输入账号密码登录。
客户指名要用 AccountManager 去做。

实现这个需求的关键点:

  1. APP 可以把验证用的 token 存到 AccountManager 中。
  2. 其它的 APP 可以从 AccountManager 中读取到 token。

一开始以为网上找找资料,去 Stack Overflow 上逛逛就可以找到资料,其实不然。我翻了两天的资料,第三天才自己琢磨明白。
在公司是用的 xamarin.forms 做的(需要 iOS 和 Android 跨平台开发),自己在家整理资料,就用 xamarin Android 做了个 demo,用来说明用法。


接下来,上代码:

  1. 需要添加权限

  1. 中添加:

    
        
    
    

  1. 新建 authenticator_config 文件:

新建这个文件主要是要用其中的 accountType 类型。

  1. 在 MainActivity 添加
AccountManager _am = AccountManager.Get(Android.App.Application.Context);
Account _account = new Account("AccountTestName", "AccountTestType");

此时的 Account 的 type 类型一定要与 authenticator_config 文件中的一致。

public void SaveShareData(string value)
{
    if (_am.GetAccountsByType("AccountTestType").Length == 0)
        _am.AddAccountExplicitly(_account, null, null);
    _am.SetAuthToken(_account, "AuthtokenTestType", value);
}

public string GetShareData()
{
    if (_am.GetAccountsByType("AccountTestType").Length == 0)
        return null;
    return _am.PeekAuthToken(_account, "AuthtokenTestType");
}

public void DeleteShareData()
{
    _am.RemoveAccountExplicitly(_account);
    _am.InvalidateAuthToken("AccountTestType", _am.PeekAuthToken(_account, "AuthtokenTestType"));
}

在 OnCreate 中添加:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);

   SetContentView(Resource.Layout.activity_main);

   TextView textView = FindViewById(Resource.Id.text);
    EditText editText = FindViewById(Resource.Id.edit);
    Button button1 = FindViewById

效果如下:

Screenshot_1563206103.png

untitled.gif


做完收工:

注:

  1. 必须是相同的 Account 账号(name 和 type 相同),authTokentype 也要相同。
  2. debug 模式无所谓,如果是打包发布,必须使用相同的签名证书的APP才能互相读取信息。

以上。

你可能感兴趣的:(xamarin Android 利用 AccountManager 实现多个APP间共享数据)