我正在尝试使用此处的官方 android 文档中的功能设置联系人照片,但该功能将照片更改为完全不同的联系人,尽管我检查contactURI
并contactID
使用它来获取联系人姓名并且仍然更改错误的联系人照片。
测试示例:
选择的联系人 ID:4673
writeDisplayImage() 中 rawContactPhotoUri 的值:content://com.android.contacts/raw_contacts/4673/display_photo
照片被错误更改的联系人的ID: 147
我的过程
我选择图像,然后使用 startActivityForResult() 选择联系人,然后执行函数
我的代码
onActivityResult() 是:
else if (requestCode == SELECT_CONTACT_FOR_RESULT) {
if (resultCode == RESULT_OK) {
contactUri=data.getData();
setContactImage(contactUri, selectedImageURI, MainActivity.this)
} else {
//}
}
setContactImage()
public static void setContactImage(final Uri rawContactUri, final Uri selectedImageURI, final Activity activity, final boolean isFromShare) {
final String nameString = getContactName(rawContactUri, activity);//get name using URI
final long contactID = ContentUris.parseId(rawContactUri);
if (writeDisplayPhoto(activity, contactID, getByteFromIMGUri(activity, selectedImageURI))) {//success toast }
写显示图像()
private static boolean writeDisplayPhoto(Activity activity, long contactID, byte[] photo) {
Uri rawContactPhotoUri = Uri.withAppendedPath(
ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, contactID),
ContactsContract.RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
Debug.d(activity, "contactID: " + contactID + "rawContactPhotoUri: " + rawContactPhotoUri);
try {
AssetFileDescriptor fd =
activity.getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "rw");
OutputStream os = fd.createOutputStream();
os.write(photo);
os.close();
fd.close();
return true;
} catch (IOException e) {
Debug.e(activity, "Write Photo EXCEPTION: " + e);
return false;
// Handle error cases.
}
}
获取联系人姓名()
static String getContactName(Uri rawContactUri, Context context) {
Cursor cursor; // Cursor object
cursor = context.getContentResolver().query(rawContactUri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
String string = cursor.getString(phoneIndex);
cursor.close();
Debug.d(context, "Name: " + string + " ,ID: " + ContentUris.parseId(rawContactUri) + " ,URI: " + rawContactUri, false);
return string;
}