我正在开发 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/