开发者

Get incoming call country name using phone number? [duplicate]

开发者 https://www.devze.com 2023-03-22 08:45 出处:网络
This question already has answers here: Retrieve incoming call's phone number in Android (3 answers)
This question already has answers here: Retrieve incoming call's phone number in Android (3 answers) Closed 2 years ago.

开发者_C百科Hi there any way we can get the country name of the incoming call on android phone?


Using libphonenumber

public String convertPhoneNumber(String phoneNumber, PhoneNumberUtil.PhoneNumberFormat format) {
    String resultNumber = "";
    Phonenumber.PhoneNumber myNumberProto = null;
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    if (!phoneNumber.substring(0, 1).equals("+")) {
        try {
            myNumberProto = phoneUtil.parse(phoneNumber,
                    Locale.getDefault().getCountry().toUpperCase());
            resultNumber = phoneUtil.format(myNumberProto,
                    format);
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: " + e.toString());
        }
    } else {
        try {
            myNumberProto = phoneUtil.parse(phoneNumber, "ZZ");
            resultNumber = phoneUtil.format(myNumberProto,
                    format);
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: " + e.toString());
        }
    }

    return resultNumber;
}


public String getRegionOfPhoneNumber(String callNumber) {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber myNumberProto = null;
    callNumber = convertPhoneNumber(callNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
    try {
        myNumberProto = phoneUtil.parse(callNumber, "ZZ");
    } catch (NumberParseException e) {
        e.printStackTrace();
    }
    String result = "";
    if (myNumberProto != null) {
        result = phoneUtil.getRegionCodeForCountryCode(myNumberProto.getCountryCode());
    }
    return result;
}

public String getCountryNameOfPhoneNumber(String callNumber) {
    String result = "";
    String regionCode = getRegionOfPhoneNumber(callNumber);
    if (!regionCode.equals("")) {
        result = new Locale("", regionCode).getDisplayCountry(Locale.getDefault());
    }
    return result;
}

usage : getCountryNameOfPhoneNumber("phone number");

Hope this help someone

0

精彩评论

暂无评论...
验证码 换一张
取 消