手机联系人信息获取(头像,电话,姓名)

需求 : 获取本地通讯录中的联系人数据
实现 : 通过系统定义好的常量去获取联系人数据
代码 :

public class ContactsDAO {
    public static ArrayList getAllContacts(Context context) {
        ArrayList datas =new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID};//返回的列名
        String selection = null;   //查询的条件
        String[] selectionArgs = null;//查询条件的参数
        String sortOrder = null;   //排序
        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
        if(cursor!=null){
            while (cursor.moveToNext()){
                String name = cursor.getString(0);
                String number = cursor.getString(1);
                String id = cursor.getString(2);

                NumBean bean =new NumBean();
                bean.name=name;
                bean.num=number;
                bean.iconId=id;
                datas.add(bean);
            }
            //关闭
            cursor.close();
        }
        return datas;
    }
    //获取联系人头像的bitmap   content://com.android.contacts
    public static Bitmap getBitmap(Context context, String id){
        ContentResolver cr=context.getContentResolver();
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,id);
        InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
        return BitmapFactory.decodeStream(is);
    }

}

联系人数据库地址: data/data/com.android.providers.contacts/databases/contacts2.db

URI简介

联系人电话Uri: content://com.android.contacts/data/phones
联系人Email Uri: content://com.android.contacts/data/emails
Android官方有上述将上述URI进行封装,我们可以使用API以更简单的方式获取这些URI

联系人电话Uri: ContactsContract.CommonDataKinds.Phone.CONTENT_URI
联系人名字列名常量:ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
联系人号码列名常量:ContactsContract.CommonDataKinds.Phone.NUMBER
联系人ID列名常量: ContactsContract.CommonDataKinds.Phone.CONTACT_ID
读取联系人需要添加权限


写权限

需求 : 获取联系人的图片
实现 : 通过 ContactsContract.Contacts.openContactPhotoInputStream()方法获取文件流, 然后通过BitmapFactory获取对应的Bitmap
代码 :

public static Bitmap getPhoto(Context context, String id) {
    ContentResolver cr = context.getContentResolver();
    Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, id);
    InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(cr, contactUri);
    return BitmapFactory.decodeStream(is);
}

你可能感兴趣的:(Android)