我一直在尝试使用他们的查询URI获取联系人的电话号码,但我没有让它工作。
Cursor myC = getContentResolver().query(lookupURI, null, null,
null, null);
String phoneNumber;
if (myC.moveToFirst()) {
while (myC.moveToNext()) {
phoneNumber = myC.getString(myC
.getColumnIndex(Phone.NUMBER));
Log.v("t", "phone number is: " + phoneNumber);
}
}
其中lookupURI.toString()
是此URI:content://com.android.contacts/contacts/lookup/0r1-304846522C3052482C4A3442423C3248/1
任何人都知道我做错了什么?
答案 0 :(得分:5)
不能保证这对4.0有用,因为我有一段时间没用过它但在2.3.3上工作正常:
要获取contactId,我首先让用户选择联系人:
public void clickSelectContact(View v) {
Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACTS_REQUEST_CODE);
}
当用户选择了联系人时,它会回到此方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CONTACTS_REQUEST_CODE){
if(resultCode == RESULT_OK){
Uri uri = data.getData();
System.out.println("uri: "+uri);
System.out.println("PHONE NUMBER: " + PhoneUtils.getContactPhoneNumber(this, uri.getLastPathSegment()));
}
}
}
调用我的静态util类:
private static final String TAG = "PhoneUtils";
public static String getContactPhoneNumber(Context context, String contactId) {
int type = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
String phoneNumber = null;
String[] whereArgs = new String[] { String.valueOf(contactId), String.valueOf(type) };
Log.d(TAG, "Got contact id: "+contactId);
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone._ID + " = ? and " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?",
whereArgs,
null);
int phoneNumberIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
if (cursor != null) {
Log.d(TAG, "Returned contact count: "+cursor.getCount());
try {
if (cursor.moveToFirst()) {
phoneNumber = cursor.getString(phoneNumberIndex);
}
} finally {
cursor.close();
}
}
Log.d(TAG, "Returning phone number: "+phoneNumber);
return phoneNumber;
}
其中contactId = lookupURI.getLastPathSegment();
对于这么简单的事情来说太复杂了! : - (
P.S。您可能需要在清单中使用此权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />