有时需要将联系人数据导出为可共享的标准格式:
vCard(.vcf
)格式,可被系统直接导入通讯录
一、导出联系人为 vCard(.vcf)
✅ 支持字段
我们支持导出的字段包括:
姓名
个人电话
家庭电话
工作电话
邮箱
备注(note)
组织机构(org)
✅ Contact 数据模型
public static class Contact {private String Name;private String phone;private String email;private String org;private String note;private String homePhone;private String workPhone;get set 省略
}
✅ 导出方法
public static boolean exportVaf(Context context, List<Contact> contactList) {StringBuilder sb = new StringBuilder();for (Contact c : contactList) {sb.append("BEGIN:VCARD\n").append("VERSION:3.0\n");if (!TextUtils.isEmpty(c.getName())) {sb.append("FN:").append(c.getName()).append("\n");}if (!TextUtils.isEmpty(c.getPhone())) {sb.append("TEL;TYPE=CELL:").append(c.getPhone()).append("\n");}if (!TextUtils.isEmpty(c.getHomePhone())) {sb.append("TEL;TYPE=HOME,VOICE:").append(c.getHomePhone()).append("\n");}if (!TextUtils.isEmpty(c.getWorkPhone())) {sb.append("TEL;TYPE=WORK,VOICE:").append(c.getWorkPhone()).append("\n");}if (!TextUtils.isEmpty(c.getNote())) {sb.append("NOTE:").append(c.getNote()).append("\n");}if (!TextUtils.isEmpty(c.getEmail())) {sb.append("EMAIL:").append(c.getEmail()).append("\n");}if (!TextUtils.isEmpty(c.getOrg())) {sb.append("ORG:").append(c.getOrg()).append("\n");}sb.append("END:VCARD\n");}try {File file = new File(context.getExternalFilesDir(null), "联系人.vcf");if (file.exists()) {file.delete();}FileOutputStream fos = new FileOutputStream(file);fos.write(sb.toString().getBytes(StandardCharsets.UTF_8));fos.close();Log.d("导出文件", "导出成功 path:" + file.getPath());return true;} catch (Exception e) {e.printStackTrace();}return false;}
✅ 使用方法
new Thread(new Runnable() {@Overridepublic void run() {List<ExportFile.Contact> contacts = new ArrayList<>();for (int i = 0; i < 10; i++) {ExportFile.Contact contact = new ExportFile.Contact();contact.setName("Name" + i);contact.setPhone("123 " + i);contact.setHomePhone("1234 " + i);contact.setWorkPhone("12345 " + i);contact.setEmail("1531352222@163.com");contact.setNote("备注 " + i);contact.setOrg("组织结构 " + i);contacts.add(contact);}boolean result = ExportFile.exportVaf(ActivityLianXiRen.this, contacts);}}).start();