如何通过意图添加名字和姓氏的联系人

Din*_*ino 9 android contacts

我正在尝试使用表单中已有的一些数据启动Android原生"添加或编辑联系人"活动.这是我目前使用的代码:

Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);

intent.putExtra(Insert.NAME, "A name");
intent.putExtra(Insert.PHONE, "123456789");
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

我的问题是我想指定名字和姓氏.我还注意到有一个StructuredName类,它包含我需要的所有字段的常量标识符.不幸的是,我无法将StructuredName字段添加到intent ...

有人知道这是如何正确完成的吗?

注意:我不是试图直接添加联系人,但我想打开一个填充的"添加联系人"对话框!

谢谢你

Jen*_*ens 2

大多数/所有值 fromContactsContract.Intents.Insert都在默认联系人应用程序的类中进行处理model/EntityModifier.java- 这只是将值 from 填充Insert.NAME到 中StructuredName.GIVEN_NAME

您可以尝试将其导入为 vCard 2.1 (text/x-vcard),它支持所有名称组件,但要求您将 vCard 文件转储到 sdcard 上或提供ContentResolver#openInputStream(Uri)可读取的内容(通常是 sdcard 上的文件或指向您自己的 ContentProvider 的 URI)。

一个使用 ContentProvider 动态创建 vCard 的简单示例:

在您的活动中:

Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("content://some.authority/N:Jones;Bob\nTEL:123456790\n"), "text/x-vcard");
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

在您的 ContentProvider 中(注册 ACTION_VIEW Intent 中使用的权限):

public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
  try {
    FileOutputStream fos = getContext().openFileOutput("filename.txt", Context.MODE_PRIVATE);
    String vcard = "BEGIN:VCARD\nVERSION:2.1\n" +
        uri.getPath().substring(1) +
        "END:VCARD\n";
    fos.write(vcard.getBytes("UTF-8"));
    fos.close();
    return ParcelFileDescriptor.open(new File(getContext().getFilesDir(), "filename.txt"), ParcelFileDescriptor.MODE_READ_ONLY);
  } catch (IOException e) {
    throw new FileNotFoundException();
  }
}
Run Code Online (Sandbox Code Playgroud)

触发后,应将一个名为您在 Uri 路径中输入的任何名称的联系人插入到电话簿中。如果用户有多个联系人帐户,他/她将被要求选择一个。

注意: vCard 的正确编码当然完全被忽略。我想大多数版本的联系人应用程序都应该支持 vCard 3.0,它没有 vCard 2.1 那样的脑死亡编码。

从好的方面来说,此方法还允许您添加工作/手机号码和其他号码(以及更多)。