Mamata Behera
Mamata Behera

Reputation: 43

how to get country code of phone number in android?

I am getting all phone numbers from contact. Then i have checked all numbers using PhoneUtil.parse() method to get the number type. But it gets exception when the phone number is not saved with country code. For example the phone number is like 9876512343 or 09876512343 its an indian number. For this number I am getting parsing exception. If I am doing like this

PhoneNumber numberProto = phoneUtil.parse(phoneNumber, "IN");

then its not a problem for that number. But how can i know that number is an indian number, so that i can pass IN in that argument. So if I can get the country code of a given phone number(String) then it can solve my problem.

Upvotes: 3

Views: 19360

Answers (2)

Vodyanikov Andrew
Vodyanikov Andrew

Reputation: 399

There is nice library, in case you wouldn't like to READ_PHONE_STATE.

 implementation 'io.michaelrocks:libphonenumber-android:8.12.13'

Link to parent C++ library on github.

google/libphonenumber

and post for quick start here. Android. How to detect a country code by the phone number

Code example bellow:

        String NumberStr = user.getPhone();
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(this.getContext());;
    try {
        Phonenumber.PhoneNumber NumberProto = phoneUtil.parse(NumberStr, null);
        if (!phoneUtil.isValidNumber(NumberProto)) {
            showError(getResources().getString(R.string.wrong_phone_number));
            return;
        }
        String regionISO = phoneUtil.getRegionCodeForCountryCode(NumberProto.getCountryCode());
        
        
    } catch (NumberParseException e) {
        showError(e.toString());
        return;
    }

Upvotes: 3

Md. Kamruzzaman
Md. Kamruzzaman

Reputation: 1905

This is my working code:

TelephonyManager tm = (TelephonyManager) getApplicationContext()
                             .getSystemService(Context.TELEPHONY_SERVICE);
String phNo = tm.getLine1Number();
String country = tm.getSimCountryIso();

Log.d("PhoneNumber :", phNo);
Log.d("country :", country);

Add following line in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

Upvotes: 5

Related Questions