我正在接收來電和接收短信的廣播意圖的android應用程序。正在使用電話號碼搜索聯繫人
然後它應該獲取傳入號碼並使用傳入號碼在用戶聯繫人上執行搜索。
這是一個更不工作,但我有一個小問題。我有它的工作,這樣的數字在聯繫人列表中搜索,如果它以+開頭的3個字符開始,並在開始時放0,或者只是一個搜索,如果它不包含+。不過,我有一個小問題,如果用戶在號碼中輸入空格,那麼應用程序不會找到聯繫人。例如,如果我將聯繫號碼保存爲07412xxxxxx
,並且來電號碼爲07412xxxxxx
或+447412xxxxxx
。但是,如果聯繫人號碼保存爲「07412 xxx xxx and the incoming number is
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;
}
}
作爲一個小點,國際國家代碼可以有1,2或3位數字(見[here](http://countrycode.org/)),因此在處理數字時可能需要檢查一些更多的選擇以「+」開始。 – Simon
@Simon謝謝你,沒有意識到這一點 – Boardy