【问题标题】:Error with check IMEI address and String检查 IMEI 地址和字符串时出错
【发布时间】:2017-04-27 06:33:05
【问题描述】:

我尝试比较 IMEI 码和一个字符串

public static String getDeviceIMEI(Context context) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
    }
    String identifier = null;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if (tm != null)
        identifier = tm.getDeviceId();
    if (identifier == null || identifier.length() == 0)
        identifier = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

    return identifier;
}

此方法计算设备的 IMEI 码,它返回一个带有该码的字符串。 而这个方法比较的是2个字符串:

private boolean checkIMEI() {        
    if (Device.getDeviceIMEI(SplashScreenActivity.this) == "xxx")
        return true;
    else
        return false;
}

(“xxx”是我设备的个人IMEI地址)

但是当我在设备上运行它时,方法 checkIMEI() 返回给我 false... 我没有任何想法来解决这个问题。 感谢您的帮助

【问题讨论】:

  • in checkIMEI() Device.getDeviceIMEI(SplashScreenActivity.this) 的值是多少? (你能记录下来吗)。另外,如果您不知道,if 块有点奇怪,它不包含任何代码。
  • @Matthias,我记录它并且 IMEI 的值(来自 Device.getDeviceIMEI(...))与我的输入(“xxx”)的值相同,xxx 值是结果Log.i("IMEI", Device.getDeviceIMEI(...));
  • 哦,对了,如果没记错的话,在 Java 中比较字符串必须使用 String.equals(otherString) 而不是 ==
  • @Matthias 好的,它有效!太好了,谢谢
  • 太好了,请随意接受我的答案作为正确答案:)

标签: android device imei


【解决方案1】:
public static String getIMEI(Context context) {
    TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    return TelephonyMgr.getDeviceId();
}

【讨论】:

  • 虽然这段代码可能会解决问题,但应该始终添加解释。
【解决方案2】:

您正在使用 == 比较 Java 中的字符串,它检查它是否是同一个对象,而不是同一个字符串,您可以使用 .equals() 来进行此操作,如下所示:

private boolean checkIMEI() {        
    if (Device.getDeviceIMEI(SplashScreenActivity.this).equals("xxx"))
        return true;
    else
        return false;
}

How do I compare strings in Java?

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2021-10-09
    • 2013-05-01
    • 2018-02-16
    • 2016-04-22
    相关资源
    最近更新 更多