1. 程式人生 > >android 獲取單個通訊錄聯絡人資訊(無許可權跳轉許可權設定頁面)

android 獲取單個通訊錄聯絡人資訊(無許可權跳轉許可權設定頁面)

首先說一下,在魅族手機上需要使用者手動開啟許可權,不然獲取到的cursor.moveToFirst()會返回false,反過來,如果cursor.moveToFirst()返回false,一般都是許可權問題,那麼如何解決這個問題呢?一般解決方案是彈窗提示,需要開啟聯絡人許可權,點選確定就跳轉到設定許可權的頁面。

點選跳轉到通訊錄頁面

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(intent, 1);

在onActivityResult方法裡獲取資訊

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
			boolean permission = ContactUtil.getPermission(getApplicationContext(), data);
			if (permission) {
				HashMap<String, String> params = ContactUtil.getContactInfo(getApplicationContext(), data);
				if (params != null) {
					if (params.containsKey("name")) {
						idTextEditName.setEditText(params.get("name"));
					}
					if (params.containsKey("mobile")) {
						idTextEditContractInfo.setEditText(params.get("mobile"));
					}
					if (params.containsKey("email")) {
						idTextEditEmail.setEditText(params.get("email"));
					}
					if (params.containsKey("momo")) {
						idTextEditRemarks.setEditText(params.get("momo"));
					}
				} else {
					showToast("獲取聯絡人資訊失敗");
				}
			} else {
				showPermissionDialog();
			}
		}
	}

彈窗提示需要使用者手動設定開啟聯絡人許可權

/***
	 * 跳往許可權設定介面
	 */
	private void showPermissionDialog() {
		new AlertDialog(this).builder().setMsg("應用需要讀取聯絡人許可權").setPositiveButton(0, new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getPackageName()));
				startActivity(intent);
			}
		}).setNegativeButton(0,null).show();
	}

工具類:判斷許可權和獲取聯絡人資訊

public class ContactUtil {

	/***
	 * 判斷許可權
	 * 
	 * @param context
	 * @param data
	 * @return
	 */
	public static boolean getPermission(Context context, Intent data) {
		// 獲取聯絡人id遊標
		Cursor idCursor = context.getContentResolver().query(data.getData(), null, null, null, null);
		if (!idCursor.moveToFirst()) {
			if (!idCursor.isClosed()) idCursor.close();
			return false;
		}
		if (!idCursor.isClosed()) idCursor.close();
		return true;
	}

	/**
	 * 獲取單個聯絡的詳細資訊
	 *
	 * @param context
	 * @param data
	 *            呼叫系統聯絡人返回的Intent
	 */
	public static HashMap<String, String> getContactInfo(Context context, Intent data) {
		Cursor cursor = null;
		try {
			// 獲取聯絡人id遊標
			Cursor idCursor = context.getContentResolver().query(data.getData(), null, null, null, null);
			if (!idCursor.moveToFirst()) {
				return null;
			}
			// 獲取聯絡人的id,用於篩選
			String contactId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
			if (!idCursor.isClosed()) idCursor.close();
			// 獲取系統的所有聯絡人中篩選出id為“contactId”的所有資訊
			cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + " = " + contactId, null, null);
			HashMap<String, String> params = new HashMap<>();
			// 遍歷所有內容
			while (cursor.moveToNext()) {
				// 獲取mimetype,通過mimetype來判斷當前資料的型別
				String mimetype = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
				switch (mimetype) {
					// 聯絡人名稱
					case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
						String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
						params.put("name", name);
						break;
					// 聯絡人電話號碼,注意電話號碼有多個且型別可能不同
					case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:

						int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
						int phoneTypeIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
						int phoneType = cursor.getInt(phoneTypeIndex);
						String number = cursor.getString(phoneIndex).trim();

						params.put("mobile", number.replaceAll(" ", ""));
						switch (phoneType) {
							// 移動手機
							case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
								String mobile = number;
								break;
							// 家用座機
							case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
								String phone = number;
								break;
							// 家用傳真
							case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME:
								String faxHome = number;
								break;

							default:
								break;
							// 一共有20種類型
							// public static final int TYPE_HOME = 1;
							// public static final int TYPE_MOBILE = 2;
							// public static final int TYPE_WORK = 3;
							// public static final int TYPE_FAX_WORK = 4;
							// public static final int TYPE_FAX_HOME = 5;
							// public static final int TYPE_PAGER = 6;
							// public static final int TYPE_OTHER = 7;
							// public static final int TYPE_CALLBACK = 8;
							// public static final int TYPE_CAR = 9;
							// public static final int TYPE_COMPANY_MAIN = 10;
							// public static final int TYPE_ISDN = 11;
							// public static final int TYPE_MAIN = 12;
							// public static final int TYPE_OTHER_FAX = 13;
							// public static final int TYPE_RADIO = 14;
							// public static final int TYPE_TELEX = 15;
							// public static final int TYPE_TTY_TDD = 16;
							// public static final int TYPE_WORK_MOBILE = 17;
							// public static final int TYPE_WORK_PAGER = 18;
							// public static final int TYPE_ASSISTANT = 19;
							// public static final int TYPE_MMS = 20;
						}
						break;
					// 獲取email
					case ContactsContract.CommonDataKinds.Email.CONTENT_TYPE:
						String email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
						params.put("email", email);
						break;
					// 獲取備註
					case ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE:
						String note = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
						params.put("momo", note);
						break;
					// 獲取通訊地址
					case ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE:

						String street = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));

						String poBox = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));

						String city = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));

						String country = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));

						String region = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));

						String neighborhood = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD));

						String postcode = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));

						// 判斷通訊地址型別
						int structuredPostalIndexTypeIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE);
						int structuredPostalIndexType = cursor.getInt(structuredPostalIndexTypeIndex);
						switch (structuredPostalIndexType) {
							// 家庭地址
							case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME:
								break;

							// 單位地址
							case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK:
								break;

							// 其他
							case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER:
								break;

							default:
								break;
						}
						break;
					default:
						break;
				}
			}

			return params;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return null;
	}

}

完成