Android 获取联系人姓名与电话号码

权限

<uses-permission android:name="android.permission.READ_CONTACTS" />

跳转通讯录界面

findViewById(R.id.btn_select_contact).setOnClickListener(v -> {
    new RxPermissions(this)
            .requestEach(Manifest.permission.READ_CONTACTS)
            .subscribe(permission -> {
                if (permission.granted) {
                    //跳转到通讯录选择界面
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                    startActivityForResult(intent, REDE_CONTACT);
                }
            });
});

处理返回数据

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REDE_CONTACT) {
        try {
            Uri uri = data.getData();
            ContentResolver cr = this.getContentResolver();
            Cursor cursor = cr.query(uri, null, null, null, null);
            //移动到游标到联系人表第一行
            if (cursor != null && cursor.moveToFirst()) {
                //联系人姓名
                String nameStr = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                //读取通讯录的号码
                String phoneStr = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                cursor.close();
                name.setText(nameStr);
                phoneNum.setText(phoneStr);
            } else {
                new Throwable("数据库游标不存在");
            }
        } catch (Throwable throwable) {
            new Throwable("未知错误");
        }
    }

效果:

Android 获取联系人姓名与电话号码_第1张图片

你可能感兴趣的:(Android)