如何检查Google身份验证器是否可在Android设备上使用?
我的Android应用使用AccountManager API访问Google财经。 AndroidManifest.xml中是否有任何功能/属性,或者我可以使用其他技术来确保该应用仅适用于安装了Google身份验证器(附件)的设备?如何检查Google身份验证器是否可在Android设备上使用?
AccountManager从API Level 5开始可用,这意味着所有使用Android 2.0或更高版本的设备都会拥有它。
您可以使用
getAccountsByType
与com.google
作为帐户类型来检查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。基本上,任何Android设备都有谷歌验证器。如果它不是根源,并删除相关软件包,当然:)
它不仅与Google帐户身份验证程序相关,当没有身份验证程序注册所需的标记类型时会收到此行为,并将其作为参数传递 – Deepscorn 2015-06-18 10:01:51
使用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开发者),但是这应该给你如何检查系统上的认证存在的想法不触发加帐户活动,如果它确实存在。
假定设备已安装(在Android 2.0的顶部)谷歌API那么我们应该能够重定向用户的设置来设置一个新的帐户。我需要一种方法来确定是否已安装Google身份验证程序的附加组件,而不是查明是否已设置任何Google帐户。 – mhdwrk 2011-05-07 20:34:13
在Android模拟器上,只有在平台2.2或更高版本上将目标设置为Google API(级别8)时,“添加Google帐户”选项才会显示在设置中! – mhdwrk 2011-05-07 20:48:09