使用适用于Android的ez-vcard库导入VCard文件

时间:2016-02-11 12:18:31

标签: android contacts android-contacts vcard vcf

我尝试将所有联系人数据导出到vcf文件,使用带有Android桥的ez-vcard库(直接从Github复制的类)。然后我想恢复此文件中的联系人。所以我在恢复之前手动删除手机联系人。但是,似乎已删除的联系人无法恢复。我可以看到在检查输出vcf文件时正确导出了联系人,因此恢复过程似乎出现了问题。

没有错误消息。通过Gmail导入同一文件时,它可以正常工作。但我需要在后台线程中静默完成导入过程,没有任何UI,因此我无法通过“联系人”应用程序进行导入,这就是我使用ez-vcard库的原因。

https://github.com/mangstadt/ez-vcard

https://github.com/mangstadt/ez-vcard-android

导出(为清晰起见,删除错误处理):

public void exportContacts(Context context) {
    Cursor c = context.getContentResolver()
            .query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (c != null) {
        if (c.moveToFirst()) {
            do {
                writeContactToFile(context, c);
            } while (c.moveToNext());
        }
        c.close();
    }
}

private void writeContactToFile(Context context, Cursor c) {
    String lookupKey = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
    AssetFileDescriptor fd = context.getContentResolver().openAssetFileDescriptor(uri, "r");
    FileInputStream fis = fd.createInputStream();
    byte[] buf = new byte[(int) fd.getDeclaredLength()];
    fis.read(buf);
    String vCard = new String(buf);
    FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE | Context.MODE_APPEND);
    fos.write(vCard.toString().getBytes());
}

导入:

VCardReader reader = new VCardReader(file);
reader.registerScribe(new AndroidCustomFieldScribe());
ContactOperations operations = new ContactOperations(context);
VCard vCard;
while ((vCard = reader.readNext()) != null) {
    operations.insertContact(vCard);
}

可能是某些编码问题,还是我错过了一些库的预配置?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您确定要将正确的File对象传递到VCardReader吗?如果在文件中找不到任何vCard,则永远不会调用insertContact方法,因为reader.readNext()将只返回null