小编典典

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

javascript

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

public boolean isUserAGoat()

用于确定进行此呼叫的用户是否会受到传送。

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

应该如何以及何时使用它?


阅读 337

收藏
2022-01-12

共2个答案

小编典典

Android R 更新:
在 Android R 中,此方法始终返回 false。谷歌表示这样做是为了to protect goat privacy

/**
 * 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");
}
2022-01-12
小编典典

我不知道这是否是“官方”用例,但以下会在 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;例如)。

我替换了whilefor if,产生了一个更晦涩的用例。我相信你可以用这种行为来绊倒你的 IDE,比如 Eclipse,但是这个编辑是 4 年后的未来,我没有 Eclipse 环境可以玩。

2022-01-12