最近项目需要用到获取手机联系人的功能,百度了一下,写这篇文章不是为了充当大神,只是为了自己以后好直接拿来用,用句伟人的话“不要重复找轮子”。
1、首先添加权限
<!-- 读取联系人权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
2、
//得到ContentResolver对象
ContentResolver cr = getContentResolver();
//取得电话本中开始一项的光标
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//向下移动光标
while(cursor.moveToNext())
{
//取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String contact = cursor.getString(nameFieldColumnIndex);
//取得电话号码
String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
while(phone.moveToNext())
{
String PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//格式化手机号
PhoneNumber = PhoneNumber.replace("-","");
PhoneNumber = PhoneNumber.replace(" ","");
}
}