我想查询 phonenumber 以获得 rawcontactID。
我唯一知道的联系人是给定的电话号码,但对于我的功能,我需要有原始联系人 ID。我得到了一个工作代码,但现在我确实使用了 2 个单独的查询。我想要的是 1 个可以同时执行这两项操作的查询,只是为了节省一些查询时间。
我的代码:
Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] columns = new String[]{Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone._ID };
Cursor cursor = contentResolver.query(uri, columns, null, null, null);
if(cursor!=null) {
int clenght = cursor.getCount();
while(cursor.moveToNext()){
//contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
id = cursor.getString(cursor.getColumnIndex(Phone.CONTACT_ID));
}
cursor.close();
}
Cursor pCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID}, ContactsContract.Data.CONTACT_ID+" = "+ id, null, null);
if(pCur!=null) {
int clenght = pCur.getCount();
while(pCur.moveToNext()){
//contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
id = pCur.getString(pCur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
}
pCur.close();
}
提前致谢
编辑:
我上面的代码工作正常,但我仍在寻求提高大量联系人的速度。因此,如果有人提供了结合我的查询的解决方案,我将悬赏。
最佳答案
private String[] getRawContactIdFromNumber(String givenNumber){
List<String> rawIds = new ArrayList<String>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID},ContactsContract.CommonDataKinds.Phone.NUMBER + "='"+ givenNumber +"'",null, ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
rawIds.add( phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)));
Log.v("contacts","Given Number: " + givenNumber + "Raw ID: " +rawIds.get(rawIds.size() - 1));
}
phones.close();
String[] ret = new String[0];
return rawIds.toArray(ret);
}
为提高效率,已编辑为仅在游标中包含原始 ID。还将返回类型更改为数组,以防多个联系人具有相同的号码。
关于Android查询电话号码获取raw contact ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032550/