在 android 中共享联系人

Sharing contacts in android

我正在尝试使用我的 android 应用程序分享联系人,我有库存。有没有办法直接使用意图共享联系人?或者我是否必须发送联系信息并在其他设备中重新构建它?另外,有没有其他方法可以不使用意图来做到这一点?

我将使用的策略是在本地获取所需的联系人。然后,将这些解析为具有所需字段的 JSON 个对象。要么将 JSON 发送到其他用户从中下载的服务器,要么通过蓝牙将 JSON 发送到其他设备。

您可以使用 ContactsContract API 将联系人作为 vcard 文件共享(例如通过 Whatsapp 发送)。

(我假设你已经有联系人的 lookupKey,如果你没有,请告诉我,我会添加从 contactId 获取它的代码)

UPDATE 添加了从 ContactId 获取 LookupKey 的方法

(确保从 ContactsContract.Contacts 导入 Contacts

private String getLookupKey(long contactId) {
    String lookupKey = null;
    String[] projection = new String[]{Contacts.LOOKUP_KEY};
    String selection = Contacts._ID + "=" + contactId;
    Cursor c = getContentResolver().query(Contacts.CONTENT_URI, projection, selection, null, null);
    if (c != null) {
        if (c.moveToFirst()) {
            lookupKey = c.getString(0);
        }
        c.close();
    }
    return lookupKey;
}

String lookupKey = getLookupKey(long contactId);
if (TextUtils.isEmpty(lookupKey)) {
    Log.e(TAG, "couldn't get lookupKey");
    return;
}
Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(Contacts.CONTENT_VCARD_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, shareUri);
intent.putExtra(Intent.EXTRA_SUBJECT, "Share a contact");
startActivity(intent);