读取通讯录的内容

 
public class TestContact extends AndroidTestCase {

	public void getAllContactInfo() throws Exception{
		String rawbase = "content://com.android.contacts/raw_contacts";
		String database = "content://com.android.contacts/data";
		Cursor cursor = getContext().getContentResolver().query(Uri.parse(rawbase), null, null, null, null);
		while (cursor.moveToNext()) {
			
			String id  = cursor.getString( cursor.getColumnIndex("_id"));
			System.out.println("id ="+ id);
			
			Cursor datacursor = getContext().getContentResolver().query(Uri.parse(database), 							null, "raw_contact_id=?", new String[]{id}, null);
			while (datacursor.moveToNext()) {
				
				String type = datacursor.getString(datacursor.getColumnIndex("mimetype"));
				System.out.println(type);
				
				if("vnd.android.cursor.item/email_v2".equals(type)){
					String data1 = datacursor.getString( datacursor.getColumnIndex("data1"));
					System.out.println("邮箱 "+ data1);
				}else if("vnd.android.cursor.item/name".equals(type)){
					String data1 = datacursor.getString( datacursor.getColumnIndex("data1"));
					System.out.println("姓名 "+ data1);
				}else if("vnd.android.cursor.item/phone_v2".equals(type)){
					String data1 = datacursor.getString( datacursor.getColumnIndex("data1"));
					System.out.println("电话号码 "+ data1);
				}
				
			}
			datacursor.close();
		
		}
		cursor.close();
	}
	
	
	public void writeContact() throws Exception{
		String rawbase = "content://com.android.contacts/raw_contacts";
		 ContentValues values = new ContentValues();
		 Uri  uri = getContext().getContentResolver().insert(Uri.parse(rawbase), values);
		 //返回的raw_contact 表中的_id
		 long id = ContentUris.parseId(uri);
		 
		 String database = "content://com.android.contacts/data";
		 ContentValues nameValues = new ContentValues();
		 nameValues.put("mimetype", "vnd.android.cursor.item/name");
		 nameValues.put("data1", "wangwu");
		 nameValues.put("raw_contact_id", id);
		 getContext().getContentResolver().insert(Uri.parse(database), nameValues);
		 
		 ContentValues phoneValues = new ContentValues();
		 phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
		 phoneValues.put("data1", "999999");
		 phoneValues.put("raw_contact_id", id);
		 getContext().getContentResolver().insert(Uri.parse(database), phoneValues);
		 
		 ContentValues emailValues = new ContentValues();
		 emailValues.put("mimetype", "vnd.android.cursor.item/email_v2");
		 emailValues.put("data1", "[email protected]");
		 emailValues.put("raw_contact_id", id);
		 getContext().getContentResolver().insert(Uri.parse(database), emailValues);
}
}

你可能感兴趣的:(读取通讯录的内容)