How to generate a .vcf file from an object which contains contact detail and object is not in the phone book

前端 未结 2 976
粉色の甜心
粉色の甜心 2021-02-06 05:30

I want to generate a .vcf file for an object which contains contact information like name, image, phone number, fax number, email id, address etc. This object is not added in th

2条回答
  •  鱼传尺愫
    2021-02-06 06:24

    You might be interested in using a vCard library instead of creating the vCard string by hand. That way, you don't have to worry about all the formatting details, like which characters to escape. ez-vcard is one such library.

    Using ez-vcard, the vCard in @AleksG's code sample would be generated like so:

    Person p = getPerson();
    
    File vcfFile = new File(this.getExternalFilesDir(null), "generated.vcf");
    
    VCard vcard = new VCard();
    vcard.setVersion(VCardVersion.V3_0);
    
    StructuredNameType n = new StructuredNameType();
    n.setFamily(p.getSurname());
    n.setGiven(p.getFirstName());
    vcard.setStructuredName(n);
    
    vcard.setFormattedName(new FormattedNameType(p.getFirstName() + " " + p.getSurname()));
    
    OrganizationType org = new OrganizationType();
    org.addValue(p.getCompanyName());
    vcard.setOrganization(org);
    
    vcard.addTitle(new TitleType(p.getTitle()));
    
    TelephoneType tel = new TelephoneType(p.getWorkPhone());
    tel.addType(TelephoneTypeParameter.WORK));
    tel.addType(TelephoneTypeParameter.VOICE));
    vcard.addTelephoneNumber(tel);
    
    tel = new TelephoneType(p.getHomePhone());
    tel.addType(TelephoneTypeParameter.HOME));
    tel.addType(TelephoneTypeParameter.VOICE));
    vcard.addTelephoneNumber(tel);
    
    AddressType adr = new AddressType();
    adr.setStreetAddress(p.getStreet());
    adr.setLocality(p.getCity());
    adr.setRegion(p.getState());
    adr.setPostalCode(p.getPostcode());
    adr.setCountry(p.getCountry());
    adr.addType(AddressTypeParameter.WORK);
    vcard.addAddress(adr);
    
    EmailType email = new EmailType(p.getEmailAddress());
    email.addType(EmailTypeParameter.PREF);
    email.addType(EmailTypeParameter.INTERNET);
    vcard.addEmail(email);
    
    vcard.write(vcfFile);
    
    Intent i = new Intent();
    i.setAction(android.content.Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(vcfFile), "text/x-vcard");
    startActivity(i);
    

提交回复
热议问题