有時需要將聯系人數據導出為可共享的標準格式:
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();