Android中获取联系人的基本信息,如姓名、电话

做之前需要加上这个READ_CONTACTS动态权限,我就不写了,自己补上就好,重点是如何获取和赋值。代码不多,废话不多说,直接上代码。

//点击的时候走下面这个方法
public void getLinkmanPermission() {
    Uri uri = ContactsContract.Contacts.CONTENT_URI;
    Intent intent = new Intent(Intent.ACTION_PICK, uri);
    startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == 0) {
            getPhoneContacts();
        }
    }
}
private void getPhoneContacts() {
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //要想获得什么信息,就在这个数组里添加
        String[] projection = new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
        };
        //uri               :查询地址
        //projection        :查询的数据字段名称
        //selection         :查询的条件 where id=..
        //selectionArgs     :查询条件的参数
        //sortOrder         :排序
        //contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
        while (cursor.moveToNext()) {
            //这个顺序和上面的projection数组一致
            person = cursor.getString(0);
            phone = cursor.getString(1);
            int id = cursor.getInt(2);
            Uri imgUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, id + "");
            //获取联系人头像,以流的方式返回
            is = ContactsContract.Contacts.openContactPhotoInputStream(cr, imgUri);
            bitmap = BitmapFactory.decodeStream(is);
        }
        //赋值,开发过程中记得判空
        mPerson.setText(person);
        mPhone.setText(phone);
        mImg.setImageBitmap(bitmap);
        //最后记得关闭流
        try {
            cursor.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

猜你喜欢

转载自blog.csdn.net/qq_40441190/article/details/82589667