Extract code country from phone number [libphonenumber]
In here you can save the phone number as international formatted phone number
internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);
it return the phone number as International format +94 71 560 4888
so now I have get country code as this
String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();
Hope this will help you
Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.
I don't need to set the country in parameter if my phone number begins with "+". Here is an example :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
PhoneNumber numberProto = phoneUtil.parse(phone, "");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
I have got kept a handy helper method to take care of this based on one answer posted above:
Imports:
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
Function:
fun parseCountryCode( phoneNumberStr: String?): String {
val phoneUtil = PhoneNumberUtil.getInstance()
return try {
// phone must begin with '+'
val numberProto = phoneUtil.parse(phoneNumberStr, "")
numberProto.countryCode.toString()
} catch (e: NumberParseException) {
""
}
}