Amsheer
Amsheer

Reputation: 7141

Find Country code by using Mobile Number Android

Is there any way to find the country code from my mobile number. Basically, I am working for a chat application I need to find the country code by using the mobile number. Is it possible?

For example:

My Country - India,
Country Code - +91,
My number - 9787248566

Now I have only my number . I don't know the country code. I don't know which country it is. Is it possible to achieve this in Android programmatically?

Upvotes: 1

Views: 4454

Answers (2)

Harpreet
Harpreet

Reputation: 3070

If you already have complete mobile number in a specific format e.g. +91-99xxxxxxxx and want to fetch country code = IN, then here is a reference to a solution.

Use a lib in your gradle.

//Phone Utils lib.
implementation 'com.googlecode.libphonenumber:libphonenumber:7.0'

And the code which will help to find the country code and other information is as below.

PhoneNumberUtil utils = PhoneNumberUtil.getInstance();
try {
    for (String region : utils.getSupportedRegions()) {
        // Check whether it's a valid number.
        boolean isValid = utils.isPossibleNumber(mobileNo, region);
        if (isValid) {
            Phonenumber.PhoneNumber number = util.parse(mobileNo, region);
            // Check whether it's a valid number for the given region.
            isValid = utils.isValidNumberForRegion(number, region);
            if (isValid) {
                Log.d("Region:" , region); // IN
                Log.d("Phone Code", number.getCountryCode()); // 91
                Log.d("Phone No.", number.getNationalNumber()); // 99xxxxxxxxxx  
            }
        }
    }
} catch (NumberParseException e) {
    e.printStackTrace();
}

Upvotes: 3

F43nd1r
F43nd1r

Reputation: 7759

Use TelephonyManager.getSimCountryIso().

If you want to map that to the number, see how to get country phone prefix from iso

Upvotes: 2

Related Questions