现在的位置: 首页 > 综合 > 正文

Android vcard使用示例,生成vcf文件

2013年11月14日 ⁄ 综合 ⁄ 共 1658字 ⁄ 字号 评论关闭

  我们备份手机联系人时,导出到SD卡时,会在SD卡中生成一个vcf文件,用于保存联系人姓名,手机号码。

vCard 规范容许公开交换个人数据交换 (Personal Data Interchange PDI)信息,在传统纸质商业名片可找到这些信息。规范定义电子名片(或叫vCard)的格式。

而在Android上使用vcard就要借助第三方包:

 

将它复制进工程,然后Add jar即可,实现代码很简单,如下:

 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();
	 }

 

由于要对存储卡做读写操作,所以要加读写权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

这样联系人就备份成功了,用系统自带的联系人软件就可以实现导入。这里只是个简单的写数据的例子,读取vcf文件中的数据的例子我已经和起压缩上传,以供各位同学下载,下载地址:http://download.csdn.net/detail/pzhtpf/4564761

 

 

抱歉!评论已关闭.