集册 Android&Java 技术笔记 Building Apps with Contacts & Sign-In

Building Apps with Contacts & Sign-In

欢马劈雪     最近更新时间:2020-08-04 05:37:59

235

Accessing Contacts Data

  • 官方文档上使用CursorLoader加载本地通讯录列表,然后用SimpleCursorAdapter显示在ListView中,示例比较繁琐
  • 项目实践中的代码:
Cursor cur = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
      null, null, null, null);
if (cur == null || cur.getCount() == 0) {
    if (cur != null) {
        cur.close();
    }
    throw new RuntimeException("Permission denied"); // 不同系统行为不一样,有的是cursor为null,有的是cursor数据为空
}
while (cur.moveToNext()) {
    String name = cur.getString(
            cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String phone = cur.getString(
            cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    //...
}
cur.close();
  • 可以通过发送Intent实现对通讯录的修改,会启动系统通讯录应用,在其中让用户进行确认修改,这种方式无需修改通讯录权限:
Intent intent = new Intent(Intents.Insert.ACTION);
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
intent.putExtra(Intents.Insert.EMAIL, mEmailAddress)
      .putExtra(Intents.Insert.EMAIL_TYPE, CommonDataKinds.Email.TYPE_WORK)
      .putExtra(Intents.Insert.PHONE, mPhoneNumber)
      .putExtra(Intents.Insert.PHONE_TYPE, Phone.TYPE_WORK);
startActivity(intent);
展开阅读全文