When we back up a mobile phone contact and export it to the SD card, a vcf file is generated in the SD card to save the contact name and mobile phone number.
The vCard specification allows the public exchange of Personal Data Interchange PDI information, which can be found in traditional paper business cards. Define the format of an electronic business card (or vCard.
Third-party packages must be used to use vcard on Android:
Copy it to the project and Add jar. The implementation code is very simple, as follows:
[Html]
If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) // determine whether the memory card exists
{
OutputStreamWriter writer;
File file = new File (Environment. getExternalStorageDirectory (), "example. vcf ");
// Obtain the root path of the memory card and write example. vcf to the root directory.
Try {
Writer = new OutputStreamWriter (new FileOutputStream (file), "UTF-8 ");
// Create a contact
VCardComposer composer = new VCardComposer ();
ContactStruct contact1 = new ContactStruct ();
Contact1.name = "John ";
Contact1.company = "The Company ";
Contact1.addPhone (Contacts. Phones. TYPE_MOBILE, "15651865008", null, true );
// Create vCard representation
String vcardString;
VcardString = composer. createVCard (contact1, VCardComposer. VERSION_VCARD30_INT );
// Write vCard to the output stream
Writer. write (vcardString );
// Writer. write ("/n"); // add empty lines between contacts
// Repeat for other contacts
//...
Writer. close ();
Toast. makeText (c, "the SD card has been imported! ", Toast. LENGTH_SHORT). show ();
} Catch (UnsupportedEncodingException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (FileNotFoundException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (VCardException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
Else {
Toast. makeText (c, "Write failed, SD card does not exist! ", Toast. LENGTH_SHORT). show ();
}
To perform read and write operations on the memory card, you must grant the read and write permissions:
[Html]
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"> </uses-permission>
In this way, the contacts are backed up and imported using the contact software that comes with the system. Here is just a simple example of writing data. The example of reading data in The vcf file has been compressed and uploaded together,