如何使用SHOW_OR_CREATE_CONTACT并为联系人设置照片?

How to use SHOW_OR_CREATE_CONTACT and also set a photo for the contact?

背景

我知道可以通过此意图设置各种字段,例如地址、phone 号码、姓名等...:[=​​13=]

final Intent intent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT, Uri.parse("tel:" +PhoneNumberService.formatNumber(phoneNumber, PhoneNumberFormat.NATIONAL));
intent.putExtra(ContactsContract.Intents.Insert.NAME, name);
intent.putExtra(ContactsContract.Intents.Insert.POSTAL_ISPRIMARY,address);
intent.putExtra(ContactsContract.Intents.Insert.POSTAL,address);
... //other stuff, like on this post: 

问题

我想知道是否可以添加照片。

我试过的

我已经尝试了下一个代码,但它似乎不起作用:

public static byte[] toByteArray(final Bitmap bitmap) {
    if (bitmap == null || bitmap.isRecycled())
        return null;
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    final byte[] byteArray = stream.toByteArray();
    return byteArray;
}


final byte[] imageByteArray = toByteArray(mBitmap);
intent.putExtra(ContactsContract.CommonDataKinds.Photo.PHOTO, imageByteArray);

问题

能不能把照片也放上?如果是,怎么做?

我也试图弄清楚添加是否成功,以便我可以获得联系人密钥并在需要时能够修改它,但似乎 "startActivityForResult" 没有'在这里帮忙。

简答

没有

SHOW_OR_CREATE_CONTACT 意图启动 ShowOrCreateActivity。 从 documentation:

Any extras from the ContactsContract.Intents.Insert class will be passed along to the create activity if there are no contacts to show.

所以 ContactsContract.Intents.Insert.POSTAL 应该有效,但实际上没有理由 ContactsContract.CommonDataKinds.Photo 可能有效。

长答案

从代码来看,前面的activity如果Uri是tel:则通过phone搜索联系人,如果是mailto:则通过email搜索联系人,如果none 找到,prompts the user 并且正向按钮启动 createIntent。

            final Intent createIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
            createIntent.putExtras(mCreateExtras);
            createIntent.setType(RawContacts.CONTENT_ITEM_TYPE);

其中 mCreateExtras 包含您传递给 SHOW_OR_CREATE_CONTACT 的所有额外内容(参见 onCreate

According to the AndroidManifest, this starts a ContactEditorActivity which sets up a toolbar and places a ContactEditorFragement.

旅程快结束了。数据绑定是在 bindEditorsForNewContact() and seems limited to what RawContactModifier.parseExtras() 提供的。文档似乎是正确的。

解决方法

但是,还有另一种插入联系人的方式,直接与内容提供商联系。

 ContentValues values = new ContentValues();
 values.put(RawContacts.ACCOUNT_TYPE, accountType);
 values.put(RawContacts.ACCOUNT_NAME, accountName);
 // This may work (not tested)
 values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, imageByteArray);
 Uri rawContactUri = getContentResolver().insert(ContactsContract.CONTENT_URI, values);
 long rawContactId = ContentUris.parseId(rawContactUri);

所以你可以做的是:

  1. 通过启动 SHOW_OR_CREATE_CONTACT
  2. 帮助用户创建联系人
  3. 创建联系人后,为该联系人插入一张显示照片。

我想知道您是否为此找到了可行的答案。我会发表评论,但我没有足够的 points.I 我也在寻找一个好的答案。

根据文档,无法明确创建新的触点插入。这意味着需要使用 URI 和值(隐式)插入新的联系人数据。

唯一可能的方法是使用内容提供程序创建一个新联系人并添加所有字段,包括默认图像。然后立即使用 ACTION_EDIT 让用户编辑字段。

另请查看 Intents.ATTACH_IMAGE