1

I am working on android application where I want to detect the country code from my phone book where by default country code is not added. For example:

+971529090909,
00971529730000,
0529090909

In "+" and "00" state, I have country codes, but in case of "0" my country code is not available. I want to detect the country code of all contacts even if someone didn't put the country code.

How to detect country code/ Area code with any library or with any code snippet.

James Z
  • 12,209
  • 10
  • 24
  • 44
Usman Khan
  • 3,739
  • 6
  • 41
  • 89

1 Answers1

-1

You can parse any number with any format using the libphonenumber library (maintained by Google), just specify the default Locale while parsing so it'll know what country code to default into.

You can play with an online version of it here.

TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String simCountryIso = telephony.getSimCountryIso();
if (simCountryIso != null) 
    return simCountryIso.toUpperCase(loc);
} else {
    Locale loc = Locale.getDefault();
    return telephony.getNetworkCountryIso().toUpperCase(loc);
}
marmor
  • 27,641
  • 11
  • 107
  • 150
  • thanks for your answer here. I want to ask you that, I don't know the default Locale. If I have 1000 list of contacts, some have country code and some don't have. I want to know the country codes of all 1000 contacts. Online version example is asking for country= field. – Usman Khan Mar 19 '18 at 14:05
  • the code i posted in my answer shows how to get the default `region` or default `country` from the sim card, you'll use that value in your Android code – marmor Mar 19 '18 at 14:46
  • how do you have access to other peoples sim cards? the idea is to pull the contacts from the phone and if they save there friends number as 083-123-1234, then what? how do you know what country they are in? – loekTheDreamer Jun 05 '20 at 10:29
  • 1
    the idea is that if a number was saved in the contacts DB without a country code it's usually safe to assume that phone's country is there same as the user's country, otherwise that number would not be dialable. of course there are edge cases like a user that it's currently traveling, but that's less likely – marmor Jun 05 '20 at 11:37