我們備份手機聯系人時,導出到SD卡時,會在SD卡中生成一個vcf文件,用於保存聯系人姓名,手機號碼。
vCard 規范容許公開交換個人數據交換(Personal Data Interchange PDI)信息,在傳統紙質商業名片可找到這些信息。規范定義電子名片(或叫vCard)的格式。
而在Android上使用vcard就要借助第三方包:
將它復制進工程,然後Add jar即可,實現代碼很簡單,如下:
[html]
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) //判斷存儲卡是否存在
{
OutputStreamWriter writer;
File file = new File(Environment.getExternalStorageDirectory(),"example.vcf");
//得到存儲卡的根路徑,將example.vcf寫入到根目錄下
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, "已成功導入SD卡中!", 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, "寫入失敗,SD卡不存在!", Toast.LENGTH_SHORT).show();
}
由於要對存儲卡做讀寫操作,所以要加讀寫權限:
[html]
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
這樣聯系人就備份成功了,用系統自帶的聯系人軟件就可以實現導入。這裡只是個簡單的寫數據的例子,讀取vcf文件中的數據的例子我已經和一起壓縮上傳,