Google公共电话号码解析库: libphonenumber

libphonenumber是用于解析、格式化、存储和校验电话号码的Java、C++或JavaScript类库。2010年,libphonenumber的Java实现首次以开源形式发布。在2014年,libphonenumber成为Debian发行版的一部分。 其中Java版本优化用于运行在智能手机上,并且用在了 Android framework 4.0 (Ice Cream Sandwich)以上的版本中。

GitHub 地址:https://github.com/googlei18n/libphonenumber

功能亮点:

  • Parsing/formatting/validating phone numbers for all countries/regions of the world.
  • getNumberType - gets the type of the number based on the number itself; able to distinguish Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP and Personal Numbers (whenever feasible).
  • isNumberMatch - gets a confidence level on whether two numbers could be the same.
  • getExampleNumber/getExampleNumberByType - provides valid example numbers for all countries/regions, with the option of specifying which type of example phone number is needed.
  • isPossibleNumber - quickly guessing whether a number is a possible phonenumber by using only the length information, much faster than a full validation.
  • isValidNumber - full validation of a phone number for a region using length and prefix information.
  • AsYouTypeFormatter - formats phone numbers on-the-fly when users enter each digit.
  • findNumbers - finds numbers in text input.
  • PhoneNumberOfflineGeocoder - provides geographical information related to a phone number.
  • PhoneNumberToCarrierMapper - provides carrier information related to a phone number.
  • PhoneNumberToTimeZonesMapper - provides timezone information related to a phone number.


快速开始

Let's say you have a string representing a phone number from Switzerland. This is how you parse/normalize it into a PhoneNumber object:

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}

At this point, swissNumberProto contains:

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

PhoneNumber is a class that is auto-generated from the phonenumber.proto with necessary modifications for efficiency. For details on the meaning of each field, refer to https://github.com/googlei18n/libphonenumber/blob/master/resources/phonenumber.proto

Now let us validate whether the number is valid:

boolean isValid = phoneUtil.isValidNumber(swissNumberProto); // returns true

There are a few formats supported by the formatting method, as illustrated below:

// Produces "+41 44 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
// Produces "+41446681800"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));

You could also choose to format the number in the way it is dialed from another country:

// Produces "011 41 44 668 1800", the number when it is dialed in the United States.
System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));

Formatting Phone Numbers 'as you type'

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
System.out.println(formatter.inputDigit('6'));  // Outputs "6"
...  // Input more digits
System.out.println(formatter.inputDigit('3'));  // Now outputs "650 253"


项目中使用实例:

/**
    代码示例
    StringUtil 为String工具类,并未提供,可执行更换。
    可以使用String 原生函数替换
*/
public class PhoneUtil {

    private static PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

    private static PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper.getInstance();

    private static PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();

    /**
     * 根据国家代码和手机号  判断手机号是否有效
     * @param phoneNumber
     * @param countryCode
     * @return
     */
    public static boolean checkPhoneNumber(String phoneNumber, String countryCode){

        int ccode = StringUtil.toInteger(countryCode);
        long phone = StringUtil.toLong(phoneNumber, 0L);

        PhoneNumber pn = new PhoneNumber();
        pn.setCountryCode(ccode);
        pn.setNationalNumber(phone);

        return phoneNumberUtil.isValidNumber(pn);
    }

    /**
     * 根据国家代码和手机号  判断手机运营商
     * @param phoneNumber
     * @param countryCode
     * @return
     */
    public static String getCarrier(String phoneNumber, String countryCode){

        int ccode = StringUtil.toInteger(countryCode);
        long phone = StringUtil.toLong(phoneNumber, 0L);

        PhoneNumber pn = new PhoneNumber();
        pn.setCountryCode(ccode);
        pn.setNationalNumber(phone);
        //返回结果只有英文,自己转成成中文
        String carrierEn = carrierMapper.getNameForNumber(pn, Locale.ENGLISH);
        String carrierZh = "";
        carrierZh += geocoder.getDescriptionForNumber(pn, Locale.CHINESE);
        switch (carrierEn) {
        case "China Mobile":
            carrierZh += "移动";
            break;
        case "China Unicom":
            carrierZh += "联通";
            break;
        case "China Telecom":
            carrierZh += "电信";
            break;
        default:
            break;
        }
        return carrierZh;
    }


    /**
     * 
    * @Description: 根据国家代码和手机号  手机归属地
    * @param @param phoneNumber
    * @param @param countryCode
    * @param @return    参数
    * @throws
     */
    public static String getGeo(String phoneNumber, String countryCode){

        int ccode = StringUtil.toInteger(countryCode);
        long phone = StringUtil.toLong(phoneNumber, 0L);

        PhoneNumber pn = new PhoneNumber();
        pn.setCountryCode(ccode);
        pn.setNationalNumber(phone);

        return geocoder.getDescriptionForNumber(pn, Locale.CHINESE);
    }
}





  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值