Get E 164 format of contacts in Android API less than 16

2.1k views Asked by At

I retrieve the list of contact numbers from the phone using the following code:

Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

while(c.moveToNext()){
      Log.d(TAG,"NO.: "+ c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER)));
}

In API 16 and above, this would work perfectly for me, as I want ALL the contacts formatted in the E 164 format, no matter how they are stored by the user.

  1. However, for APIs below 16, the above code won't work and I am not able to get the E 164 format for all contacts by using the following line:

     c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    

The 'PhoneNumberUtils' class could not come to any use.

Also, I cannot use the libphonenumber library to convert numbers to their E 164 format, as I don't know the ISO 3166-1 two letter country-code of the contacts.

Is there any way in which I can obtain the ISO 3166-1 two letter country-code for each contact in Android, so that I can use the libphonenumber library ?

Or is there any other solution to achieve point 1. ?

The numbers retrieved from the phone can be of any format eg.

  • Local : 965XXXXXXX
  • National : 0965XXXXXXX
  • International : +91 96 5X XXXXXX
  • and other

whereas the E 164 is +91XXXXXXXXXX where 91 is the country code.

Any help would be much appreciated !

2

There are 2 answers

6
Jaffa On

You can use the network language for the default country code, available using getNetworkCountryIso. This method may be unreliable on CDMA networks (use getPhoneType to determine if on a CDMA network).

It will be the same value used when phoning the contact, so you should get the correct value.

For local to national numbers, I can't help you as I don't have such features in my country and don't know how it works in yours.

0
corsair992 On

Android didn't store the number in E.16 format before Honeycomb. Therefore, you need to format it yourself using the libphonenumber library if you are supporting lower API levels. The Contacts app uses the CountryDetector service for determining the country code if none is provided, which uses comprehensive heuristics based on the information available on the device. This service is not part of the public API, and wasn't available pre-Honeycomb in any case, but you can copy the code in the ComprehensiveCountryDetector class to reuse in your own app.

Note that since Honeycomb's source is not available, and I didn't have the opportunity to test on a Honeycomb device, I can't comment on what the state is on Honeycomb related to these issues.