比较Android中的电话号码

时间:2012-09-05 13:27:38

标签: java android string phone-number

我需要比较两个电话号码,以确定它们是否来自同一发件人/收件人。用户可以向联系人发送消息,该联系人可以回复。

回复通常会出现 +[country-code][area-code-if-any][and-then-the-actual-number]格式。例如, +94 71 2593276获取斯里兰卡电话号码。

当用户发送消息时,他通常会输入格式(对于上面的示例)0712593276(假设他也在斯里兰卡)。< / p>

所以我需要的是,我需要检查这两个数字是否相同。此应用将在国际上使用。所以我不能用0替换前2位数(那么对于像美国这样的国家来说这将是一个问题)。有没有办法在Java或Android专门做到这一点?

感谢。

4 个答案:

答案 0 :(得分:16)

Android有很好的PhoneNumberUtils,我猜你在寻找:

    public static boolean compare (String a, String b)
看看: http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html

使用它应该如下所示:

String phone1   
String phone2 

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

答案 1 :(得分:9)

android.telephony.PhoneNumberUtils课程提供几乎所有必要的功能来处理电话号码和标准。

对于您的情况,解决方案是PhoneNumberUtils.compare(Context context, String number1, String number2)PhoneNumberUtils.compare(String number1, String number2)。前者检查资源以确定是否使用严格或松散的比较算法,因此在大多数情况下是更好的选择。 / p>

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

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

查看官方documentation。还有source code

答案 2 :(得分:3)

如何检查号码是否是接收者号码的子串?

例如,假设我的巴西数字是888-777-666,而你的巴西数字是111-222-333。 要打电话给你,我需要拨打其他号码拨打国际长途电话。假设我需要添加9999 + your_number,结果为9999111222333.

如果RawNumber.substring(your_number)返回true,我可以说我正在打电话给你。

答案 3 :(得分:-1)

只需应用你的逻辑删除()和 - 并按照PhoneNumberUtils