Android 代码片段---获取手机通讯录列表

public List<Contact> getContacts()
{
	List<Contact> list = new ArrayList<Contact>();
	Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
	String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER };
	String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// 	Cursor cursor = managedQuery(uri, projection, null, null, sortOrder); // 4.2.2不建议使用这种方式
	Cursor cursor = getContentResolver().query(uri, projection, null, null, sortOrder);

	while (cursor.moveToNext())
	{
		String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
		String phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
		Contact man = new Contact();
		man.setName(name);
		man.setMobile(String.valueOf(phoneNum.trim().replace(" ", "").replace("+", "")));

		list.add(man);
	}
	cursor.close();
	return list;
}
	
class Contact
{
	private String name;
	private String mobile;

	@Override
	public String toString()
	{
		return "Contact [name=" + name + ", mobile=" + mobile + "]";
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getMobile()
	{
		return mobile;
	}

	public void setMobile(String mobile)
	{
		this.mobile = mobile;
	}
}

你可能感兴趣的:(android,通讯录)