How can I format a phone number using PhoneNumberUtils?
E.g.: 1234567890 → (123) 456-7890
We can easily do this by:
val tm = act.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
val formattedPhoneNumber= PhoneNumberUtils.formatNumber(phone, tm?.simCountryIso?.toUpperCase())
here, tm?.simCountryIso?.toUpperCase() returns iso code, "in" in my case and we used toUpperCase() to convert it into "IN"
you can also use networkCountryIso instead of simCountryIso.
From doc:
getNetworkCountryIso(): Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of the current registered operator or the cell nearby, if available.
getSimCountryIso(): Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.
you can also pass direct iso code, for example:
PhoneNumberUtils.formatNumber("2025550739", "US") // output: (202) 555-0739
Check the list of iso codes.