作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在使用 Android 2.0 并正在尝试接收所有联系人的列表。
由于 android.provider.Contacts.People 已被弃用,我必须使用 android.provider.ContactsContract,但我找不到合适的示例来说明如何使用它(例如:检索电话簿上所有联系人的列表)。
有人知道在哪里可以找到这样的例子吗?
最佳答案
首先,确保你已经添加了
<uses-permission android:name="android.permission.READ_CONTACTS"/>
到您的 AndroidManifest.xml 文件,然后您可以像这样循环访问您的手机联系人:
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
}
cursor.close();
此外,您可以循环访问您的联系人并简单地获取姓名和电话号码,如下所示:
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String number = people.getString(numberFieldColumnIndex);
}
people.close();
此外,如果您需要从联系人那里获取备注等信息,则需要使用不同的 URI,如下所示(请随意使用此方法):
private String getNote(long contactId) {
String note = null;
String[] columns = new String[] { ContactsContract.CommonDataKinds.Note.NOTE };
String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{Long.toString(contactId), ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor contacts = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, whereParameters, null);
if (contacts.moveToFirst()) {
rv = contacts.getString(0);
}
contacts.close();
return note;
}
请注意,这次我不仅使用了联系人 ID,还使用了 mime 类型进行查询。
关于android - 如何在 Android 2.0 上读取联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1721279/
我是一名优秀的程序员,十分优秀!