Android UserManager.isUserAGoat() 的正确用例?

新手上路,请多包涵

我正在查看 Android 4.2 中引入的新 API。在查看 UserManager 类时,我遇到了以下方法:

 public boolean isUserAGoat()

用于确定进行此调用的用户是否受到远距传送。

返回进行此调用的用户是否是山羊。

应该如何以及何时使用?

原文由 Ovidiu Latcu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 344
2 个回答

安卓 R 更新:

从 Android R 开始,此方法始终返回 false。谷歌表示这样做是为了“保护山羊的隐私”:

 /**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#R}, this method always returns
 * {@code false} in order to protect goat privacy.</p>
 *
 * @return Returns whether the user making this call is a goat.
 */
public boolean isUserAGoat() {
    if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
        return false;
    }
    return mContext.getPackageManager()
            .isPackageAvailable("com.coffeestainstudios.goatsimulator");
}


上一个答案:

从他们的 来源 来看,该方法用于返回 false 直到它在 API 21 中被更改。

 /**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 * @return whether the user making this call is a goat
 */
public boolean isUserAGoat() {
    return false;
}

看起来该方法对我们开发人员没有实际用处。此前有人表示,这可能是一个 彩蛋

在 API 21 中,实现已更改为检查是否已安装应用程序包 com.coffeestainstudios.goatsimulator

 /**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 *
 * @return Returns true if the user making this call is a goat.
 */
public boolean isUserAGoat() {
    return mContext.getPackageManager()
            .isPackageAvailable("com.coffeestainstudios.goatsimulator");
}

这是 来源变化

原文由 meh 发布,翻译遵循 CC BY-SA 4.0 许可协议

我不知道这是否是“官方”用例,但以下会在 Java 中产生警告(如果与 return 语句混合,会进一步产生编译错误,导致代码无法访问):

 while (1 == 2) { // Note that "if" is treated differently
    System.out.println("Unreachable code");
}

然而这是合法的:

 while (isUserAGoat()) {
    System.out.println("Unreachable but determined at runtime, not at compile time");
}

所以我经常发现自己写了一个愚蠢的实用方法来以最快的方式虚拟出一个代码块,然后在完成调试时找到对它的所有调用,所以只要实现没有改变,这个就可以用于那个。

JLS 指出 if (false) 不会触发“无法访问的代码”,具体原因是这会破坏对调试标志的支持,即基本上这个用例 (h/t @auselen)。 (例如 static final boolean DEBUG = false; )。

我将 while 替换为 if ,产生了一个更晦涩的用例。我 相信 您可以通过这种行为使您的 IDE(如 Eclipse)出错,但这次编辑是 4 年后的事,而且我没有 Eclipse 环境可以玩。

原文由 djechlin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题