1.需要添加的权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_CONTACTS" />
2.跳转到通讯录
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, 0);
3.回调
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case 0: if (data == null) { return; } //处理返回的data,获取选择的联系人信息** Uri uri = data.getData(); String[] contacts = getPhoneContacts(uri); phone.setText(contacts[1]); //返回的数据赋值 int length = phone.getText().length(); phone.setSelection(length); //把光标定位到最后面 break; } }
//回调中所用到的方法 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; }