Android. How to detect a country code by the phone number

Alex Misiulia
1 min readSep 16, 2019

--

Hi everyone! Last week I had a task to implement this:

I need just to gues a country code by first numbers of a phone number. After I googled a little bit I found a library libphonenumber.

To implement this logic we need to do the following:

  • Add listener to EditText.
  • Add the library libphonenumber.
  • Detect a country code by the phone number.
  • Display country code if we can detect a country code.

Add listener to EditText

Add the library libphonenumber

We need to add the following block to dependencies:

Detect a country code by the phone number

We need to create an instance of PhoneNumberUtils class:

And after that, we need to convert aString number to PhoneNumber class from the lib. Using this class we can detect a country from it:

The library has a constraint that phone number must start with “+”. That’s why we add phone validation. And finally, we can use this function inside the text change listener:

Full code

Talk is cheap. Show me the code ©. Link to the github repository.

I am a passionate Android developer, feel free to follow and contact me on LinkedIn, Facebook, and Medium.

--

--