安卓:如何通过电话号码获取联系人ID?

8

我需要在Android (API 1.6)doughnut版本中进行操作。


1个回答

23

尝试使用这段代码,对我来说很好用...

ContentResolver contentResolver = context.getContentResolver();

Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));

String[] projection = new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};

Cursor cursor =  
   contentResolver.query(
        uri, 
        projection, 
        null, 
        null, 
        null);

if(cursor!=null) {
  while(cursor.moveToNext()){
    String contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
    String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
    Log.d(LOGTAG, "contactMatch name: " + contactName);
    Log.d(LOGTAG, "contactMatch id: " + contactId);
  }
  cursor.close();
}

即使代码在技术上是正确的,但它可能会导致你的光标未关闭。 - zegnus
@zegnus 可以使用 finally 了! - Sanju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接