1.在AndroidManifest中加入读写权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
2.Android系统管理联系人的URI
获取联系人的ID和NAME:ContactsContract.Contacts.CONTENT_URI
获取联系人的电话号码:ContactsContract.CommonDataKinds.Phone.CONTENT_URI
获取联系人的邮箱地址:ContactsContract.CommonDataKinds.Email.CONTENT_URI
(注:Contacts有两个表,分别是rawContact和Data,rawContact记录了用户的id和name,其中id栏名称为:ContactsContract.Contacts._ID, name名称栏为ContactContract.Contracts.DISPLAY_NAME,电话信息表的外键id为ContactsContract.CommonDataKinds.Phone.CONTACT_ID,电话号码栏名称为:ContactsContract.CommonDataKinds.Phone.NUMBER.
3.调用系统联系人获取电话号码
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0) {
String phoneNumber = "";
if(data != null) {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (null != cursor && cursor.moveToFirst()){
phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//得到纯数字电话号码
if (phoneNumber.startsWith("+86")) {
phoneNumber = phoneNumber.replace("+86", "");
}
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("-", "");
editText.setText(phoneNumber);
cursor.close();
}
}
}
}
网友评论