如何读取系统联系人姓名和电话号码(1)

定义一个点击事件,点击后进入系统联系人界面选择

//跳转到联系人页面
	private void contactRead() {
		// Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
		// intent.setType("vnd.android.cursor.item/phone");

		Intent intent = new Intent(Intent.ACTION_PICK,
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
		startActivityForResult(intent, 0);
	}


对返回的结果进行处理

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			switch (resultCode) {
			case Activity.RESULT_OK:
				Uri uri = data.getData();

				// 查看联系人信息
				// Cursor cursor=managedQuery(uri, null, null, null,
				// null);//和下边的结果一样,唯一区别可以用activity管理cursor的生命周期;
				Cursor cursor = getContentResolver().query(uri, null, null,
						null, null);
				// 根据返回的uri获取电话号码
				cursor.moveToFirst();
				String num = cursor
						.getString(cursor
								.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
				etnumber.setText(num);
				// 获取外键id
				String contact_id = cursor
						.getString(cursor
								.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
				// 根据外键id获取姓名
				Cursor namecursor = getContentResolver().query(
						ContactsContract.Contacts.CONTENT_URI, null,
						ContactsContract.Contacts._ID + "=" + contact_id, null,
						null);
				namecursor.moveToNext();
				String name = namecursor
						.getString(namecursor
								.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
				etname.setText(name);
				namecursor.close();
				cursor.close();
				break;
			}
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);

	}


 

你可能感兴趣的:(Andoid学习笔记)