我正在尝试使用 Android Api 读取 VCard 格式的 Android 设备联系人。 我找到了一个相同的链接: Android contatcs vcard API
并尝试编写相同的代码但它不起作用,因为我无法获得查找键:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
int num = cur.getCount(); // I get 2 , as there are two contacts
String lookupKey = cur.getString(cur.getColumnIndex(Contacts.LOOKUP_KEY));
// The above line gives error : android.database.CursorIndexOutOfBoundsException:
// Index -1 requested, with a size of 2
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] b = new byte[(int)fd.getDeclaredLength()];
fis.read(b);
String vCard = new String(b);
sb.append(vCard);
任何人都可以告诉我如何获取上述代码的 lookupkey 或我们可以使用 Android api 获取联系人 VCard 格式的任何其他方法。
最佳答案
给你:
Cursor cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
try {
do {
String lookupKey = cursor.getString(cursor
.getColumnIndex(Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_VCARD_URI,
lookupKey);
AssetFileDescriptor fd;
try {
fd = context.getContentResolver()
.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] b = new byte[(int) fd.getDeclaredLength()];
fis.read(b);
String vCard = new String(b);
Log.i(TAG, vCard);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
} finally {
cursor.close();
}
}
关于android - 如何使用 Android native API 获取 Vcard 格式的 Android 联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035841/