Comparing phone numbers in Android

我是研究僧i 提交于 2019-12-17 16:45:24

问题


I need to compare two phone numbers to determine if they're from the same sender/receiver. The user may send a message to a contact, and that contact may reply.

The reply usually comes in +[country-code][area-code-if-any][and-then-the-actual-number] format. For example, +94 71 2593276 for a Sri Lankan phone number.

And when the user sends a message, he will usually enter in the format (for the above example) 0712593276 (assume he's also in Sri Lanka).

So what I need is, I need to check if these two numbers are the same. This app will be used internationally. So I can't just replace the first 2 digits with a 0 (then it will be a problem for countries like the US). Is there any way to do this in Java or Android-specifically?

Thanks.


回答1:


Android has nice PhoneNumberUtils, and i guess your looking for :

    public static boolean compare (String a, String b)

look in : http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html

using it should look like this :

String phone1   
String phone2 

 if (PhoneNumberUtils.compare(phone1, phone2)) {
    //they are the same do whatever you want!
   }



回答2:


android.telephony.PhoneNumberUtils class provides almost all necessary functions to deal with phone numbers and standards.

For your case, the solution is PhoneNumberUtils.compare(Context context, String number1, String number2) or else PhoneNumberUtils.compare(String number1, String number2).The former one checks a resource to determine whether to use a strict or loose comparison algorithm, thus the better choice in most cases.

PhoneNumberUtils.compare("0712593276", "+94712593276") // always true
PhoneNumberUtils.compare("0712593276", "+44712593276") // always true

// true or false depends on the context
PhoneNumberUtils.compare(context, "0712593276", "+94712593276") 

Take a look at the official documentation. And the source code.




回答3:


How about checking if the number is a substring of the receiver's number?

For instance, let's say my Brazilian number is 888-777-666 and yours is 111-222-333. To call you, from here, I need to dial additional numbers to make international calls. Let's say I need to add 9999 + your_number, resulting in 9999111222333.

If RawNumber.substring(your_number) returns true I can say that I'm calling you.




回答4:


just apply your logic to remove () and - and follow PhoneNumberUtils



来源:https://stackoverflow.com/questions/12282569/comparing-phone-numbers-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!