android4.0获取联系人个人档案库的邮件地址和头像

public static Bitmap getPhoto(Context context, String mailAddress) {
        Bitmap selfContactPhoto = null;
        ContentResolver resolver = context.getContentResolver();

        String[] CONTACTS_COLUMNS = new String[] {
                ContactsContract.Contacts._ID,//查询的ID,主键唯一
                ContactsContract.Contacts.PHOTO_ID,//查询图片的ID
                ContactsContract.Contacts.PHOTO_FILE_ID,
                ContactsContract.Contacts.LOOKUP_KEY//用来转换地址获取邮件地址
            };

           //查询游标
        Cursor cur = resolver.query(Profile.CONTENT_URI, CONTACTS_COLUMNS,
                null, null, null);
        Uri lookupUri = null;
        try {
            if (cur.moveToFirst()) {
                final long contactId = cur.getLong(ContactQuery.Contacts._ID);
                final long photoId = cur.getLong(ContactQuery.Contacts.PHOTO_ID);
                final long photoFileId = cur.getLong(ContactQuery.Contacts.PHOTO_FILE_ID);
                final String lookupKey = cur.getString(ContactQuery.Contacts.LOOKUP_KEY);

                //得到uri地址
                lookupUri = Contacts.getLookupUri(contactId, lookupKey);

                //得到邮件地址的列表
                List mailList = loadProfileMailAdress(resolver, lookupUri);
                if (mailList.contains(mailAddress)) {
                    if (photoId > 0) {//得到头像
                        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
                        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
                        selfContactPhoto = BitmapFactory.decodeStream(input);
                    }
                    return selfContactPhoto;
                }
            }
        } finally {
            cur.close();
        }
        return selfContactPhoto;
    }

 

private static List loadProfileMailAdress(ContentResolver resolver, Uri contactUri) {
        Uri entityUri = Uri.withAppendedPath(contactUri, Contacts.Entity.CONTENT_DIRECTORY);
        Cursor cursor = resolver.query(entityUri,
                ContactQuery.Data.DATA_COLUMNS,
                ContactsContract.Data.MIMETYPE + "=?",
                new String[] {Email.CONTENT_ITEM_TYPE},
                Contacts.Entity.RAW_CONTACT_ID);
        List addressList = new ArrayList();
        try {
            while (cursor.moveToNext()) {
                String address = cursor.getString(ContactQuery.Data.DATA1);
                addressList.add(address);
            }
        } finally {
            cursor.close();
        }
        return addressList;
    }

你可能感兴趣的:(android应用)