android中通过contentprovider访问通讯录代码实现(两种方法实现)

步骤:
                //1.获取联系人的id
//2.根据联系人的id 获取联系人名字
//3.根据联系人的id 数据的type 获取到对应的数据(电话,email);
方法一代码:
// 1.获取联系人的id
// 2.根据联系人的id 获取联系人名字
// 3.根据联系人的id 数据的type 获取到对应的数据(电话,email);
ContentResolver resolver = context.getContentResolver();
List infos = new ArrayList();
ContactInfo info;
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri datauri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, nullnullnullnull);
while (cursor.moveToNext()) {
    info = new ContactInfo();
    String id = cursor.getString(cursor.getColumnIndex("_id"));
    String name = cursor.getString(cursor
            .getColumnIndex("display_name"));
    info.setName(name);
    Cursor datacursor = resolver.query(datauri, null,
            "raw_contact_id=?"new String[] { id }, null);
    while (datacursor.moveToNext()) {
        // mimetype
        String type = datacursor.getString(datacursor
                .getColumnIndex("mimetype"));
        if ("vnd.android.cursor.item/phone_v2".equals(type)) {
            String number = datacursor.getString(datacursor
                    .getColumnIndex("data1"));
            info.setPhone(number);
        }
    }
    datacursor.close();
    infos.add(info);
    info = null;
}
cursor.close();
return infos;
方法二代码:
Uri uri = Uri.parse("content://com.android.contacts/contacts");
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(uri, new String[] { "_id" }, nullnull,
        null);
List infos = new ArrayList();
ContactInfo info = null;
while (cursor.moveToNext()) {
    String _id = cursor.getString(0);
    uri = Uri.parse("content://com.android.contacts/contacts/" + _id
            + "/data");
    Cursor dataCursor = resolver.query(uri, new String[] { "mimetype",
            "data1""data2" }, nullnullnull);
    info = new ContactInfo();
    while (dataCursor.moveToNext()) {
        String type = dataCursor.getString(dataCursor
                .getColumnIndex("mimetype"));
        String data1 = dataCursor.getString(dataCursor
                .getColumnIndex("data1"));
        if ("vnd.android.cursor.item/name".equals(type)) {// name
            info.setName(data1);
        } else if ("vnd.android.cursor.item/phone_v2".equals(type)) {// phone
            info.setPhone(data1);
        }
    }
    dataCursor.close();
    infos.add(info);
    info = null;
}
cursor.close();
return infos;

你可能感兴趣的:(android中通过contentprovider访问通讯录代码实现(两种方法实现))