实现跳转手机通讯录获取指定姓名和手机号码
1、先添加权限
<!-- 读联系人权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
如果是android系统是6.0之后的,需要在代码中动态添加权限
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_CONTACTS);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS},REQUEST_CODE_ASK_PERMISSIONS);
return;
}
}
2、点击跳转实现
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 0);
3、在返回页面重写onActivityResult()方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data==null)
{
return;
}
if(requestCode==0) {
/* **//*/处理返回的data,获取选择的联系人信息***/
Uri uri = data.getData();
String[] contacts = getPhoneContacts(uri);
LogHelper.d(TAG,"------contacts--"+contacts[0]);//打印出的姓名
LogHelper.d(TAG,"------contacts--"+contacts[1]);//打印出来的电话
addGoodsName.setText(contacts[0]);
addGoodsPhone.setText(contacts[1]);
}
}
上面实现获取姓名电话的方法getPhoneContacts()如下
private String[] getPhoneContacts(Uri uri){
String[] contact=new String[2];
//得到ContentResolver对象**
ContentResolver cr = getContentResolver();
//取得电话本中开始一项的光标**
Cursor cursor=cr.query(uri,null,null,null,null);
if(cursor!=null)
{
cursor.moveToFirst();
//取得联系人姓名**
int nameFieldColumnIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
contact[0]=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);
if(phone != null){
phone.moveToFirst();
contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phone.close();
cursor.close();
}
else
{
return null;
}
return contact;
}
由此就可以获取通讯录中的姓名和电话了
网友评论