Android基础:获取手机联系人工具类

Bean:

public class ContactInfo {

	public String id;
	public String name;
	public String phone;
}

ContactUtils.java

public class ContactUtils {
	/**
	 * 获取联系人数据
	 * 
	 * @param context
	 * @return
	 */
	public static List getAllContacts(Context context) {
		List list = new ArrayList();
		// 获取解析者
		ContentResolver resolver = context.getContentResolver();
		// 访问地址
		Uri raw_contacts = Uri.parse("content://com.android.contacts/raw_contacts");
		Uri data = Uri.parse("content://com.android.contacts/data");
		// 查询语句
		// select contact_id from raw_contacts;//1 2 3 4
		// select mimetype,data1 from view_data where raw_contact_id=3;
		// Cursor cursor=resolver.query(访问地址, 返回字段 null代表全部, where 语句, 参数, 排序)
		Cursor cursor = resolver.query(raw_contacts, new String[] { "contact_id" }, null, null, null);

		while (cursor.moveToNext()) {
			// getColumnIndex根据名称查列号
			String id = cursor.getString(cursor.getColumnIndex("contact_id"));
			// 创建实例
			ContactInfo info = new ContactInfo();
			info.id = id;
			Cursor item = resolver.query(data, new String[] { "mimetype", "data1" }, "raw_contact_id=?", new String[] { id }, null);

			while (item.moveToNext()) {
				String mimetype = item.getString(item.getColumnIndex("mimetype"));
				String data1 = item.getString(item.getColumnIndex("data1"));
				if ("vnd.android.cursor.item/name".equals(mimetype)) {
					info.name = data1;
				} else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
					info.phone = data1;
				}
			}
			item.close();
			// 添加集合
			list.add(info);
		}

		cursor.close();
		return list;
	}
}


你可能感兴趣的:(Android非UI)