提问人:mhdwrk 提问时间:5/8/2011 更新时间:8/13/2017 访问量:1126
如何检查 Google 身份验证器是否在 Android 设备上可用?
how to check if Google authenticator is available on a Android device?
问:
我的 Android 应用使用 AccountManager API 访问 Google 财经。AndroidManifest .xml 中是否有任何功能/属性或任何其他技术可用于确保该应用仅适用于安装了 Google 身份验证器(插件)的设备?
答:
AccountManager 从 API 级别 5 开始可用,这意味着所有具有 android 2.0 或更高版本的设备都将拥有它。
您可以检查带有 with 作为帐户类型的 google 帐户。
getAccountsByType
com.google
即使设备具有 Android 2.0 或更高版本,也不能保证用户会设置 Google 帐户。他们将无法访问市场或其他谷歌应用程序(gmail、地图等),但其他任何事情都可以使用。
就像谷歌所做的那样:当用户启动应用程序时,检查是否有正确的帐户,如果没有,请通知用户并停止应用程序。
评论
它不仅与谷歌帐户身份验证器有关,这种行为是一般的:
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。基本上,任何安卓设备都有谷歌身份验证器。如果它没有被root并删除了相关包,当然:)
评论
使用解决方案的问题在于,您无法区分未安装身份验证器的情况,或者存在身份验证器但缺少通过它进行身份验证的帐户。在第二种情况下,您可能需要提示用户添加新帐户。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 开发人员),但这应该让您了解如何检查系统上是否存在身份验证器,而不会触发添加帐户活动,以防它确实存在。
评论