訪問通訊錄並返回號碼(多個號碼可以選擇)
阿新 • • 發佈:2019-02-06
Intent i = new Intent(Intent.ACTION_PICK, android.provider.ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, 1);
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { Uri contactData = data.getData(); Cursor cursor = managedQuery(contactData, null, null, null, null); cursor.moveToFirst(); String num = this.getContactPhone(cursor); } } private String getContactPhone(Cursor cursor) { int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); int phoneNum = cursor.getInt(phoneColumn); final List<String> result = new ArrayList<>(); position = 0; if (phoneNum > 0) { int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);// 獲得聯絡人的ID號 String contactId = cursor.getString(idColumn); // 獲得聯絡人電話的cursor Cursor phone = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null); if (phone.moveToFirst()) { for (; !phone.isAfterLast(); phone.moveToNext()) { int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int typeindex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); String phoneNumber = phone.getString(index); result.add(phoneNumber); } if (!phone.isClosed()) { phone.close(); } } } if (result.size() > 1) {//如果號碼多於2個,則彈出對話方塊讓他選擇 AlertDialog.Builder builder = new AlertDialog.Builder(this); int size = result.size(); builder.setTitle("請選擇一個號碼").setItems(result.toArray(new String[size]), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { position = which; } }).create().show(); } return result.get(position); }