2010-09-14 232 views
26

在我的應用程序中,用戶寫了一個電話號碼,我想用該電話號碼找到聯繫人姓名?按電話號碼搜索聯繫人

我通常尋找這樣的接觸:

Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, 
      null, null, null, null); 

但我這樣做是爲了訪問所有聯繫人......在這個程序,我只希望得到給定電話號碼的聯繫人姓名...如何我可以限制查詢嗎?

或者我必須去掉所有的聯繫人,看看是否有給定的電話號碼?但我認爲,這可能會很慢這樣...

+0

閱讀有關所有這些空白可與:) – 2010-09-14 20:16:29

+0

也將被替換的文件,要使用'CONTENT_FILTER_URI'。 – 2010-09-14 20:17:02

+0

對於其他人的設施,我寫了一篇文章,其中包含整個代碼,用於查詢姓名,照片,聯繫人ID等,並提供正確的解釋。該代碼包含在不同答案中發現的片段,但更多地組織和測試。希望能幫助到你。鏈接:http://hellafun.weebly.com/home/get-information-of-a-contact-from-number – Usman 2017-05-02 15:12:28

回答

32

你應該看看推薦ContactsContract.PhoneLookup提供商

表示仰視的電話號碼,例如呼叫者ID結果的表。要執行查找,您必須在CONTENT_FILTER_URI中追加想要查找的號碼。這個查詢是高度優化的。

Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); 
resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,... 
+0

謝謝。我試圖調用getContentResolver()在我的廣播接收器,但它看起來像那個函數不存在... – 2010-09-14 20:56:05

+3

嘗試前綴的上下文參數,因此它是context.getContentResolver() – Pentium10 2010-09-15 08:25:22

+3

什麼具體進入剩下的查詢?這個答案不比現有的文檔更有幫助。 – eternalmatt 2011-03-19 21:24:48

79

如果你想的完整代碼:

public String getContactDisplayNameByNumber(String number) { 
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); 
    String name = "?"; 

    ContentResolver contentResolver = getContentResolver(); 
    Cursor contactLookup = contentResolver.query(uri, new String[] {BaseColumns._ID, 
      ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null); 

    try { 
     if (contactLookup != null && contactLookup.getCount() > 0) { 
      contactLookup.moveToNext(); 
      name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); 
      //String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID)); 
     } 
    } finally { 
     if (contactLookup != null) { 
      contactLookup.close(); 
     } 
    } 

    return name; 
} 
+0

謝謝!我不會初始化'name'變量,因爲當沒有記錄時'null'是一個合適的返回值。 – 2014-04-15 17:33:01

+4

特殊情況下,用戶輸入部分號碼,但以不匹配的格式存儲號碼?例如,在以色列,國家的前綴是「+972」,對於某些手機號碼,則添加「050」,但如果是全部號碼,則變爲「97250」(沒有第一個「0」)。因此,如果用戶鍵入「050」(搜索所有電話號碼或至少以它開頭),它將不會得到任何結果... – 2015-01-04 10:19:29

+0

在我的情況下,我實現了一個函數來過濾一個原始數字並做出所有可能的組合,然後我逐一搜索。不幸的是,我認爲Android沒有辦法簡化它。我錯了嗎? – 2015-01-05 17:43:01

相關問題