获取权限并启动“选择联系活动”的代码
Button chooseContactsBtn = (Button) findViewById(R.id.addContactButton);
chooseContactsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getPermissionToReadUserContacts();
Intent contacts = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contacts, PICK_CONTACTS);
}
});
关于活动结果
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACTS) {
if (resultCode == RESULT_OK) {
ContactDataManager contactsManager = new ContactDataManager(this, data);
try {
email = contactsManager.getContactEmail();
EditText e_mail = (EditText) findViewById(R.id.e_mail);
e_mail.setText(email);
} catch (ContactDataManager.ContactQueryException e) {
//Print Exception
}
}
}
}
联系人管理器类中的getContactEmail方法。
public String getContactEmail() throws ContactQueryException
{
Cursor cursor = null;
String email = null;
try
{
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?",
new String[]{intent.getData().getLastPathSegment()},
null);
if (cursor.moveToFirst())
{
email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
else {
System.out.println("No Email found. and leaving the method.");
}
} catch (Exception e)
{
Log.e(LOG_TAG, e.getMessage());
throw new ContactQueryException(e.getMessage());
} finally
{
if (cursor != null)
cursor.close();
}
return email;
}
这不会返回任何内容。我有返回姓名和号码的方法,他们工作正常。 联系许可是肯定的。
答案 0 :(得分:1)
您正在调用电话选择器意图(通过意图中的CommonDataKinds.Phone.CONTENT_URI
uri)。
你可以做以下两件事之一:
(a)将您的选择器意图更改为电子邮件选择器,并获得特定的电子邮件作为回报
(b)将您的选择器意图更改为联系人选择器,并使用基于{{1}的getContactEmail
获取该联系人的第一封电子邮件(如果有) }}
我选择(a),代码是:
CONTACT_ID
然后:
Intent contacts = new Intent(Intent.ACTION_PICK, CommonDataKinds.Email.CONTENT_URI); // Note the Email!
startActivityForResult(contacts, PICK_CONTACTS);
详情请见:https://developer.android.com/guide/components/intents-common.html#Contacts