How to open a contact card in Android by ID

ⅰ亾dé卋堺 提交于 2019-11-28 08:26:21

use ACTION_VIEW and either build a contact URI using the contact ID or use the contact lookup URI if you already have it (preferred).

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactID));
    intent.setData(uri);
context.startActivity(intent);

You would use the following URI:

Uri.Builder newUriBuilder = ContactsContract.Contacts.CONTENT_LOOKUP_URI.buildUpon();
newUriBuilder.appendPath("/").appendPath(theContactKey)
i.setData(newUriBuilder.build());

You will find more details about how this URI works by looking at the API documentation for CONTENT_LOOKUP_URI.

I was trying to open a contact card using the listed here methods, but somehow the contacts activity was closing immediately after it was opening.

it seemed that the contact activity didn't accept my old content uri.

I resolved this problem using the getLookupUri (long contactId, String lookupKey) method of ContactsContract.Contacts class for obtaining the right content uri https://developer.android.com/reference/android/provider/ContactsContract.Contacts.html#getLookupUri(long, java.lang.String)

So the code for opening a contact card becomes:

Intent intent = new Intent(Intent.ACTION_VIEW);
String lookupKey = phonesCursor.getString(phonesCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.LOOKUP_KEY));
long contactId = phonesCursor.getLong(phonesCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
Uri uri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
intent.setData(uri);
startActivity(intent);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!