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

2022-08-31 01:23:57

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

public boolean isUserAGoat()

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

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

应该如何以及何时使用?


答案 1

安卓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");
}

上一个答案:

从其开始,用于返回的方法,直到在 API 21 中更改它。false

/**
 * 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");
}

这是更改


答案 2

我不知道这是否是“官方”用例,但以下情况会在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指出不会触发“无法访问的代码”,因为具体原因会破坏对调试标志的支持,即基本上这个用例(h / t @auselen)。(例如)。if (false)static final boolean DEBUG = false;

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


推荐