如何检查 Android 设备上是否可用 Google Authenticator?

3

我的Android应用程序使用AccountManager API访问Google财务。是否有任何在AndroidManifest.xml中的特性/属性或其他技术,我可以使用来确保该应用程序仅适用于安装了Google身份验证器(附加组件)的设备?

3个回答

3
  1. AccountManager自API Level 5起可用,这意味着所有Android 2.0或更高版本的设备都将拥有它。

  2. 您可以使用getAccountsByType检查Google帐户,并将com.google作为帐户类型。

  3. 即使设备运行Android 2.0或更高版本,也不能保证用户会设置Google帐户。他们将无法访问市场或其他Google应用程序(如Gmail、Maps等),但其他任何内容都将正常工作。

像Google一样操作:当用户启动应用程序时,请检查是否存在正确的帐户,如果不存在,则通知用户并停止应用程序。


假设设备已安装了Google API(在Android 2.0之上),那么我们应该能够将用户重定向到设置页面以设置新帐户。我需要找出一种方法来确定是否已安装了Google身份验证器的附加组件,而不是找出他们是否设置了任何Google帐户。 - mhdwrk
在 Android 模拟器上,只有当目标设置为平台 2.2 或更高版本的 Google API(级别 8)时,"添加 Google 帐户" 选项才会显示在设置中! - mhdwrk

0

这不仅仅与Google账户验证器有关,这种行为是普遍的:

AccountManager.get(context).addAccount(
                    <google account type>,
                    <needed token type>,
                    null,
                    <options or null if not needed>,
                    activityToStartAccountAddActivity,
                    new AccountManagerCallback<Bundle>() {
                        @Override
                        public void run(AccountManagerFuture<Bundle> future {
                            try {
                                future.getResult();
                            } catch (OperationCanceledException e) {
                                throw new RuntimeException(e);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            } catch (AuthenticatorException e) {
                                throw new RuntimeException(e); // you'll go here with "bind failure" if google account authenticator is not installed
                            }
                        }
                    },
                    null);

如果您的设备上没有安装支持所请求的帐户类型和令牌类型的身份验证器,则会出现AuthenticatorException。基本上,任何Android设备都有Google Authenticator。当然,如果它没有被root并且相关包已删除,则不适用 :)


这个行为不仅与Google账户验证器有关,当传递的参数需要令牌类型但没有注册相关的认证器时,我们也会遇到这种情况。 - Deepscorn

0
使用getAccountsByType解决方案的问题在于,您无法区分认证器未安装的情况和认证器存在但未通过它进行身份验证的帐户的存在。在第二种情况下,您可能需要提示用户添加新帐户。
尝试添加帐户然后检查异常也不是理想的方法,当方法AccountManager.getAuthenticatorTypes()存在时。像这样使用它:
String type = "com.example"; // Account type of target authenticator
AccountManager am = AccountManager.get(this);
AuthenticatorDescription[] authenticators = am.getAuthenticatorTypes();
for (int i = 0; i < authenticators.length(); ++i) {
    if (authenticators[i].type.equals(type)) {
        return true; // Authenticator for accounts of type "com.example" exists.
    }
return false; // no authenticator was found.

我的Java有点生疏(我是Xamarin开发者),但这应该能让你了解如何在不触发添加帐户活动的情况下检查系统上是否存在认证器。

Sources:
getAuthenticatorTypes
AuthenticatorDescription.type


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接