我的Android应用程序使用AccountManager API访问Google财务。是否有任何在AndroidManifest.xml中的特性/属性或其他技术,我可以使用来确保该应用程序仅适用于安装了Google身份验证器(附加组件)的设备?
我的Android应用程序使用AccountManager API访问Google财务。是否有任何在AndroidManifest.xml中的特性/属性或其他技术,我可以使用来确保该应用程序仅适用于安装了Google身份验证器(附加组件)的设备?
AccountManager自API Level 5起可用,这意味着所有Android 2.0或更高版本的设备都将拥有它。
您可以使用getAccountsByType
检查Google帐户,并将com.google
作为帐户类型。
即使设备运行Android 2.0或更高版本,也不能保证用户会设置Google帐户。他们将无法访问市场或其他Google应用程序(如Gmail、Maps等),但其他任何内容都将正常工作。
像Google一样操作:当用户启动应用程序时,请检查是否存在正确的帐户,如果不存在,则通知用户并停止应用程序。
这不仅仅与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并且相关包已删除,则不适用 :)
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