android - 使用电话号码搜索联系人

标签 android contacts android-contacts

我正在开发 Android 应用程序,该应用程序接收来电和来电短信的广播 Intent 。

然后应该获取传入号码并使用传入号码对用户联系人执行搜索。

这更有效,但我遇到了一个小问题。我让它工作,以便在联系人列表中搜索该号码,如果它以 + 开头,则去除前 3 个字符并在开头放置一个 0,或者如果它不包含 +,则只进行搜索。但是,我有一个小问题,如果用户在号码中输入空格,那么应用程序找不到联系人。例如,如果我将联系电话保存为 07412xxxxxx,来电号码为 07412xxxxxx+447412xxxxxx。但是,如果联系人号码保存为 `07412 xxx xxx 并且来电号码为 07412xxxxxx``,则无法识别该号码,因此无法找到联系人姓名。

如何执行搜索以考虑所有数字格式。下面是我目前使用的代码。

public String getContactNameFromNumber(String number)
    {

        if (number.startsWith("+"))
        {
            number = "0" + number.substring(3);
        }

        String contactName = null;
        ContentResolver contentResolver = context.getContentResolver();

        Uri uri = Data.CONTENT_URI;
        String[] projection = new String[] {PhoneLookup._ID, PhoneLookup.DISPLAY_NAME};
        String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?";
        String[] selectionArgs = { number };
        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);

        if (cursor.moveToFirst())
        {

            contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
            cursor.close();
            return contactName;
        }
        else
        {
            cursor.close();
            return null;
        }
    }

最佳答案

尝试:

String selection = "REPLACE (" + ContactsContract.CommonDataKinds.Phone.NUMBER + ", \" \" , \"\" ) = ?";

参见 replace功能。

关于android - 使用电话号码搜索联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408466/

相关文章:

Android从url解析json并存储

android - 在 Android 上使用 "mobile phone numbers"查询联系人的最快方法

android - 从 NotificationChannel 禁用声音

android - 即使提供了通知 ID,也不会在单击操作按钮时删除通知

android - Xamarin Facebook 客户端

iphone - 获取地址簿联系人列表并导入 iPhone 和 iPhone 模拟器

android - 选择联系人详细信息,其中 People._ID = android 中的联系人 ID

android - 如何在 Android 上更新 native 联系人照片?

android CallLog.Calls._ID 与联系人 ID 相同吗?

android - 确定所选联系人的号码是手机还是固定电话?