使用android实战读取手机通讯录
时间: 2023-12-05 10:05:37 浏览: 117
Android个人手机通讯录开发详解
要读取Android手机的通讯录,可以使用Android提供的ContentResolver类和ContactsContract类。下面是一个简单的示例代码:
```java
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
public class ContactReader {
public static void readContacts(Context context) {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCursor != null && phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("Name: " + name + ", Phone Number: " + phoneNumber);
}
if (phoneCursor != null) {
phoneCursor.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
```
在上面的代码中,我们首先获取ContentResolver对象,然后使用它查询ContactsContract.Contacts.CONTENT_URI来获取所有联系人的ID和名称。接着,我们使用联系人ID查询ContactsContract.CommonDataKinds.Phone.CONTENT_URI来获取联系人的电话号码。最后,我们打印联系人的名称和电话号码。调用readContacts()方法即可读取手机通讯录。
阅读全文