【问题标题】:Getting the Wrong Mobile Prefix in Android在 Android 中获取错误的移动前缀
【发布时间】:2017-02-22 09:41:36
【问题描述】:

我正在制作一个应用程序,我将从 sim 中获取用户的完整电话号码 - 包括国家和手机前缀。我的电话号码是 061555555,所以当我将它保存到服务器时,它应该是这样的:+38761555555。

这是我的问题 - 当我使用下面的代码时,我得到以下信息:+387218900032555555,即。 不是 061 变成 61,而是变成 218900032。此行号给出了错误的数字:

MyPhoneNumber = tMgr.getLine1Number(); 

我也试过this和this。

这是我的代码:

// Get users phone number
private String getMyPhoneNumber() {
    TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    // Get the SIM country ISO code
    String simCountry = tMgr.getSimCountryIso().toUpperCase();
    // Get the operator code of the active SIM (MCC + MNC)
    String simOperatorCode = tMgr.getSimOperator();
    // Get the name of the SIM operator
    String simOperatorName = tMgr.getSimOperatorName();
    // Get the SIM’s serial number
    String simSerial = tMgr.getSimSerialNumber();

    String MyPhoneNumber = "0000000000";

    try {
        MyPhoneNumber = tMgr.getLine1Number();
    } catch (NullPointerException ex) {
    }

    if (MyPhoneNumber.equals("")) {
        MyPhoneNumber = tMgr.getSubscriberId();
    }

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber countryNumberProto = null;
    try {
        countryNumberProto = phoneUtil.parse(MyPhoneNumber, simCountry);
    } catch (NumberParseException e) {
        System.err.println("NumberParseException was thrown: " + e.toString());
    }

    String myPhone = phoneUtil.format(countryNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
    // I tried INTERNATIONAL and NATIONAL as well

    return myPhone;
}

【问题讨论】:

    标签: android telephonymanager libphonenumber phonenumberutils


    【解决方案1】:

    我认为您正在解析“national_number”而不是“country_code”。检查您的 JSON 解析代码字段逻辑

    {
      "country_code": 41,
      "national_number": 446681800
    }
    

    https://github.com/googlei18n/libphonenumber

    【讨论】:

    • 当我调试时,我得到以下内容:Country Code: 387 National Number 21890032555555.
    • 它表示 38 不是“simCountry”的国家代码 & 上面一个和你的 Q 一样。
    • 我的国家代码是 387,但我的国家号码(手机前缀)应该以 61 开头,而不是 21890032。抱歉,如果我没有正确理解您的答案,我再次更新了我的代码。请指出我的代码错误。
    • 这是您号码的 JSON 对象 { "code": "+387", "name": "Bosnia and Herzegovina" }
    • 我建议您为所有国家/地区打印 JSON。它会让你知道@你的“simCountry”有什么问题吗?
    【解决方案2】:

    我检查了我的设置->状态,发现我的电话号码是未知的,并且显示的是IMEI而不是我的电话号码,所以我想我会让用户通过手动输入来确认他的电话号码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 2012-06-11
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多