使用部分数据查询联系人

时间:2013-07-20 02:09:45

标签: android pattern-matching contacts contactscontract

我一直试图复制一些关于联系人匹配的OEM拨号器应用程序行为而没有太多运气。基本上,我想填充一个潜在的联系人匹配列表,因为用户在拨号器中输入的数字与输入的电话号码和名称相匹配,就像大多数手机一样。例如,在拨号器中输入323将匹配在NUMBER中任何位置具有323的联系人,例如(323)123-4567以及与爸爸或Daffy的DISPLAY_NAME的联系人等。

我知道ContactsContract.PhoneLookup.CONTENT_FILTER_URI应该用于匹配电话号码而忽略格式化(因此查询uri对5551234567会返回其号码存储为(555)123-4567的联系人)。问题是我无法使用部分数字,因此查询5551将包含相同的结果,即使我添加带有LIKE子句和通配符的选择参数。如果我使用任何其他URI,LIKE的选择arg将返回部分结果,但格式化会使事情变得复杂,以便5551不匹配,只有555)1。 任何人都可以解释我如何在忽略单个查询的格式时获得部分数字匹配吗?其他尝试使用多个查询的速度太慢而且没有提供我在大多数手机上看到的体验(I已经注意到Android源中的股票拨号器没有进行联系人匹配,只搜索,所以没有帮助)。

其次,对于名称的一部分,我有一个有效的解决方案,虽然我不确定这是最好的策略。我原本希望使用ContactsContract.Contacts.CONTENT_FILTER_URI,因为文档说这是你应该如何过滤你的类型建议的结果,但同样只能用于单个部分名称的alpha搜索,而我需要翻译323以搜索相关键盘字母(dad,dae,daf,ead,eae,eaf,fad等)的所有组合的部分匹配。我已经使用ContactsContract.CommonDataKinds.Phone.CONTENT_URI和选择参数使用LIKE来匹配所有可能性,然后后续请求根据从前一个请求返回的联系人ID缩小字段。 有没有办法利用ContactsContract.Contacts.CONTENT_FILTER_URI来进行这种类型的数字模式匹配?我没有尝试将其分解为多个请求,但是基于我经历过类似部分尝试的延迟上面描述的数字匹配,我怀疑它不会很好。

非常感谢任何建议!

谢谢, 斯科特

2 个答案:

答案 0 :(得分:3)

我现在已经挣扎了2天了,我终于得到了一个解决方案,我和Scott一起工作。

您需要使用此URI

ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI并附加URI路径,即部分字符串(名称或数字)。

Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(partial));
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);

希望这有帮助!

答案 1 :(得分:1)

这项技术适用于我,通过使用:

来解析部分号码
//encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number.substring(len-9)));

String selection = PhoneLookup.NUMBER + " LIKE %" + number.substring(len-9) + "%";

Cursor cursor = context.getContentResolver().query(contactUri, projection, selection, null, null);

完整示例:

private void getContactDetails(String number) {
    // define the columns you want the query to return
    String[] projection = new String[] {
        PhoneLookup.DISPLAY_NAME,
        PhoneLookup._ID,
        PhoneLookup.LOOKUP_KEY};
    int len = number.length();
    // encode the phone number and build the filter URI
    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number.substring(len-9)));

    String selection = PhoneLookup.NUMBER + " LIKE %" + number.substring(len-9) + "%";

    Cursor cursor = context.getContentResolver().query(contactUri, projection, selection, null, null);

    if(cursor != null) {
        if (cursor.moveToFirst()) {
            String name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
            String lookUpKey = cursor.getString(cursor.getColumnIndex(PhoneLookup.LOOKUP_KEY));
        }
        cursor.close();
    }
}

它解析并匹配最后10位数字,希望它会有所帮助!!!