如何通过电子邮件或电话号码获取联系人

Fáb*_*llo 1 android

如何获取在Android中拥有电话号码或电子邮件的联系人列表.

我对合同有点困惑,如何加入信息.

谢谢

Ray*_*ter 9

以下是我如何通过电子邮件电话号码获取联系人.该联系对象就是我创建了一个简单的POJO.此代码位于我在用户提供访问" 联系人"权限后运行的AsyncTask中.

ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {

  do {
      // get the contact's information
      String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
      String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
      Integer hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

      // get the user's email address
      String email = null;
      Cursor ce = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
              ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
      if (ce != null && ce.moveToFirst()) {
          email = ce.getString(ce.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
          ce.close();
      }

      // get the user's phone number
      String phone = null;
      if (hasPhone > 0) {
          Cursor cp = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                  ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
          if (cp != null && cp.moveToFirst()) {
              phone = cp.getString(cp.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              cp.close();
          }
      }

      // if the user user has an email or phone then add it to contacts
      if ((!TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
              && !email.equalsIgnoreCase(name)) || (!TextUtils.isEmpty(phone))) {
          Contact contact = new Contact();
          contact.name = name;
          contact.email = email;
          contact.phoneNumber = phone;
          contacts.add(contact);
      }

  } while (cursor.moveToNext());

  // clean up cursor
  cursor.close();
}    
Run Code Online (Sandbox Code Playgroud)

对于DISPLAY_NAME,您可以使用以下内容:

private final String DISPLAY_NAME = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY : ContactsContract.Contacts.DISPLAY_NAME;
Run Code Online (Sandbox Code Playgroud)

这是我使用的AsyncTask示例的链接.