Search code examples
androidsmspdu

Android SmsMessage country code


I'm currently working on a app to blacklist SMS from a specific country, I already created my BroadcastReceiver class, which start a service to compare the phone number to the ones stored in the database. My database contains mobile country code, and I would like to compare the received country code to those in the database, unfortunately I didn't find any method to retrieve the country code from the number. I thought that I could retrieve it with a simple substring call, but I noticed that not all the country codes are the same length, so I couldn't do this like that. I was wondering if the prefixes were unique (that is to say if a prefix could be the prefix of another), if no, then could I start by taking the maximum size prefix and then a shorter prefix and so on ? Could you give me a hint on how to do this ?

Thank you


Solution

  • Phone number rules are rather complicated and there are many special cases. To extract country code reliably, I'd suggest to use a specialized library. There's a well-known library from Google, called libphonenumber:

    https://code.google.com/p/libphonenumber/

    Take a look at extractCountryCode method from PhoneNumberUtil, or PhoneNumberUtil.parse which returns a PhoneNumber object on which you can call getCountryCode.

    It's open source, so, alternatively, if you don't want to mess with additional libraries, you can take a look at its implementation for hints on how to handle country codes by yourself.