在项目中有时会用到获取联系人信息的功能,这里我实现的是点击按钮打开通讯录界面获取联系人姓名和电话号码
实现代码:
public void obtainLinkMan(View view){
//打开通讯录页面
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 2);
}
获取结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 2:
//获取Uri
Uri uri=data.getData();
if(null!=uri){
Cursor cur=getContentResolver().query(uri, null, null, null, null);
//如果第一条数据有
if(cur.moveToFirst()){
//获取联系人id
int contactId=cur.getInt(cur.getColumnIndex(ContactsContract.Contacts._ID));
//获取联系人姓名
String linkManName=cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//获取电话号码Cursor
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+contactId, null, null);
String numPhone;
if(phones.moveToFirst()){
numPhone=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}else{
numPhone="";
}
Toast.makeText(this, linkManName+":"+numPhone, Toast.LENGTH_SHORT).show();
}
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
布局页面就是一个按钮