最近在做的项目中涉及到Android手机联系人同步,google到导出vCard格式联系人的方法
参考自 http://blog.csdn.net/ID19870510/article/details/6691383#
代码如下:
/** Exporting contacts from the phone */
public void exportContacts() throws Exception {
String path = Environment.getExternalStorageDirectory().getPath() + "/contacts.vcf";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int index = cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
FileOutputStream fout = new FileOutputStream(path);
byte[] data = new byte[1024 * 1];
while (cur.moveToNext()) {
String lookupKey = cur.getString(index);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fin = fd.createInputStream();
int len = -1;
while ((len = fin.read(data)) != -1) {
fout.write(data, 0, len);
}
fin.close();
}
fout.close();
}
在AndroidManifest中需加入获取联系人权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />