开发者

android Convert phone number in International Format

I'd like to know whether it's possible to have phone numbers converted into international format when a call is outgoing.

For instance, if a french user (sorry it's the only format i know i won't make a mistake :-) try to call with the national format : 01.47.12.34.56 then a method will convert it into international format like this : +33.1.47.12.34.56

I've looked into the doc of the PhoneNumberUtils but i don't know if there开发者_如何学JAVA is a method doing what i want.


Old post, but if it helps anyone: use google's libphonenumber library to do all sorts of formatting and validating for phone numbers. In this particular case, to convert to international format use the format(PhoneNumber number, PhoneNumberFormat format) api in class PhoneNumberUtil in the same library.


Doesn't the number come as a String?

Using Java's string methods you could do this yourself easily if I'm not mistaken?

So get the String, cop the 0 off and add the +33


Use this method to convert your local number to International Format, I am using google library https://github.com/google/libphonenumber as (Aswin Kumar) mentioned

Java

   public static String formatPhoneNumber(String phoneNumber) {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber formattedNumber = null;
    String formatted = null;

    try {
        TelephonyManager manager = (TelephonyManager) sContext.getSystemService(Context.TELEPHONY_SERVICE);
        String countryCode = manager.getNetworkCountryIso();
        formattedNumber = phoneUtil.parse(phoneNumber, countryCode.toUpperCase());
        formatted = phoneUtil.format(formattedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
        return formatted;
    } catch (NumberParseException e) {
        e.printStackTrace();
    }
    return null;
}

Kotlin

    private fun formatNumber(number: String?) {
    val phoneUtil = PhoneNumberUtil.getInstance()
    var formattedNumber: PhoneNumber? = null
    var formatted: String? = null
    try {
        val manager = applicationContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val networkCountryIso: String = manager.networkCountryIso
        Log.i("SERVICE " , "ISO "+ networkCountryIso)
        formattedNumber = phoneUtil.parse(number, networkCountryIso.toUpperCase())
        formatted = phoneUtil.format(formattedNumber, PhoneNumberUtil.PhoneNumberFormat.E164)
        Log.i("SERVICE " , "phone number"+ formatted)
        findCallerId(formatted)
    } catch (e: NumberParseException) {
        e.printStackTrace()
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜