Question

How would i go about getting the area code of a device?

I have an import script where im grabbing all phone numbers in there contacts list, so i can compare it to a list in my database and act accordingly. However i know some people wont put the area code for some of there contacts due to the fact that they dont need it for a local number. I need to get there area code so i can add it to the number im checking.

NOT the postal 5 digit zip code, the 3 digit area code.

All the ways i found want me to get there location then get it, i dont want to do that, thats too much work to get 3 digits.

Was it helpful?

Solution

If the contacts do not have an area code, then you assume that the area code is the local area code. If its the local area code, then the user's phone number must have this area code. Thus, you can get the user's telephone number to determine the local area code and apply that area code to any numbers that do not have an area code.

To get the user's phone number you can use this code -

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tm.getLine1Number();

Copied from this question.

Then you can extract the area code by looking at the first 3 (or possibly 4 if the length of the String is 11 chars) digits.

String areaCode = mPhoneNumer.substring(0, mPhoneNumber.length()==10 ? 3 : 4);

Note: Ensure that you add the READ_PHONE_STATE permission to the AndroidManifest.xml file by adding this line -

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top