2013-10-07 54 views
0

我正在使用类似下面的联系人选择器来获取联系人的ID。试图将黑名单列入黑名单时,不匹配联系人ID

public void pickContact() { 
    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); 
    intent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers 
    startActivityForResult(intent, PICK_CONTACT_REQUEST); 
} 

然后我从上面使用这个返回的uri检索联系人ID。并将其作为参考存储。

public static long getContactIdByUri(Context context, Uri uri) 
{ 
    Log.d(TAG, uri.toString()); 
    String[] projection = { Contacts._ID }; 
    Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); 
    try 
    { 
     cursor.moveToFirst(); 
     int idx = cursor.getColumnIndex(Contacts._ID); 
     long id = -1; 

     if(idx != -1) 
     { 
      id = cursor.getLong(idx); 
     } 
     return id; 
    } 
    finally 
    { 
     cursor.close(); 
    } 
} 

后来当短信来取我的电话号码,并根据我尝试使用以下查找联系人ID上。

public static long getContactIdByPhoneNumber(Context context, String phoneNumber) { 
    ContentResolver contentResolver = context.getContentResolver(); 
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); 
    String[] projection = new String[] { PhoneLookup._ID }; 
    Cursor cursor = contentResolver.query(uri, projection, null, null, null); 
    if (cursor == null) { 
     return -1; 
    } 
    int idx = cursor.getColumnIndex(PhoneLookup._ID); 
    long id = -1; 
    if(cursor.moveToFirst()) { 
     id = cursor.getLong(idx); 
    } 
    if(cursor != null && !cursor.isClosed()) { 
     cursor.close(); 
    } 
    return id; 
} 

问题是这两个id不匹配!

因此,基本上问题是我怎样才能从联系人选择器中获得一个id,当使用PhoneLookup.CONTENT_FILTER_URI查找电话号码时,我可以匹配它。我也可以使用它来获取有关联系人的其他信息?

回答

0

从联系人选择器返回的url是指ContactsContract.Data提供程序,该提供程序与ContactsContract.RawContacts联合,该联系人又包含CONTACT_ID。

因此,使用下面的方法提取实际的联系人ID是微不足道的。

public static long getContactIdByDataUri(Context context, Uri uri) 
    { 
      String[] projection = new String[] { Data.CONTACT_ID }; 
      Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); 
      long id = -1; 
      if(cursor.moveToFirst()) { 
       id = cursor.getLong(0); 
      } 
      return id; 
    }