【问题标题】:Android AccountManager [closed]Android AccountManager [关闭]
【发布时间】:2011-05-10 03:13:58
【问题描述】:

有人可以帮助我逐步使用 android 中的 AccountManager 以及一个简单的示例以便更好地理解吗?

【问题讨论】:

  • 你到底想做什么?
  • 你检查过 Android SDK 中的示例吗?

标签: android


【解决方案1】:

我实际上是在回答这个问题,以便我自己可以清楚地了解,所以这里是(我对 Android 还不是很精通):

应用程序通常会首先检查帐户是否存在,您可以使用:

AccountManager mgr = AccountManager.get(getApplicationContext());
Account[] accounts = mgr.getAccountsByType("com.mydomain");
// assert that accounts is not empty

您需要使用AccountManagerFuture<Bundle> 来保存身份验证令牌的结果。这必须是异步的,因为 Android 设备可能会同时要求用户登录:

private AccountManagerFuture<Bundle> myFuture = null;
private AccountManagerCallback<Bundle> myCallback = new AccountManagerCallback<Bundle>() {
    @Override public void run(final AccountManagerFuture<Bundle> arg0) {
        try {
           myFuture.getResult().get(AccountManager.KEY_AUTHTOKEN); // this is your auth token
       } catch (Exception e) {
           // handle error
       }
   }

}

现在您可以异步请求身份验证令牌:

myFuture = mgr.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, true, myCallback, null);

AUTH_TOKEN_TYPE 取决于您的身份验证机制。对于谷歌帐户,它只是“啊”。

现在,每当您执行经过身份验证的请求时,只需传递令牌(在标头中,作为参数等),以便服务器端知道您是谁。

【讨论】:

猜你喜欢
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多