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

前端 未结 2 977
粉色の甜心
粉色の甜心 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:21

    It's actually quite easy to generate a .vcf file. Have a look at VCF format - it's a simple text file. All you need to do is create text file and write info into it using the VCF fields. You'll end up with something like this:

    Person p = getPerson();
    
    File vcfFile = new File(this.getExternalFilesDir(null), "generated.vcf");
    FileWriter fw = new FileWriter(vcfFile);
    fw.write("BEGIN:VCARD\r\n");
    fw.write("VERSION:3.0\r\n");
    fw.write("N:" + p.getSurname() + ";" + p.getFirstName() + "\r\n");
    fw.write("FN:" + p.getFirstName() + " " + p.getSurname() + "\r\n");
    fw.write("ORG:" + p.getCompanyName() + "\r\n");
    fw.write("TITLE:" + p.getTitle() + "\r\n");
    fw.write("TEL;TYPE=WORK,VOICE:" + p.getWorkPhone() + "\r\n");
    fw.write("TEL;TYPE=HOME,VOICE:" + p.getHomePhone() + "\r\n");
    fw.write("ADR;TYPE=WORK:;;" + p.getStreet() + ";" + p.getCity() + ";" + p.getState() + ";" + p.getPostcode() + ";" + p.getCountry() + "\r\n");
    fw.write("EMAIL;TYPE=PREF,INTERNET:" + p.getEmailAddress() + "\r\n");
    fw.write("END:VCARD\r\n");
    fw.close();
    
    Intent i = new Intent();
    i.setAction(android.content.Intent.ACTION_VIEW);
    i.setDataAndType(Uri.fromFile(vcfFile), "text/x-vcard");
    startActivity(i);
    

    (Note that this code is to be placed inside an activity. If it's not in an activity, then replace this in front of getExternalFilesDir with an instance of Context.)

    You can have more of fewer fields, as needed. If you have ,, ; or \ characters in field values, they need to be escaped with \; to put a newline character into a value, write \\n into the file (i.e. the file itself must contain \n, the second slash is for escaping the slash in the newline).

    This code is quite crude, but it should get you started. Again, have a look at the format of VCF and go from there.

    Update: Thanks to @Michael for pointing out mistakes in my original answers.

提交回复
热议问题