要讓使用者從系統聯絡人挑一個人回來,網路上流傳的寫法不少,但真正能拿到返回結果的其實不多——很多範例只會跳出聯絡人介面,選完卻收不到資料。下面這份是能正常回傳的實作。
當時的場景是一個聯通服務下的應用,需要用到手機聯絡人,又不想自己刻一套聯絡人 UI,於是直接用系統自帶的。系統版本每次只能回傳一筆紀錄,若聯絡人裡有同名者會一起帶回,這部分在程式裡去掉重複即可。由於該軟體最多只能撥給 7 個人,逐個添加完全够用,不必自訂聯絡人實作。
// 添加聯絡人到介面顯示
public void addClick(View view) {
canAdd = checkCanAddPeople(call_people, datas.size());
if (canAdd) {
// 調用系統聯絡人介面並返回一筆選中的資料
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, RESULT_CODE_CONTACTS);
}
}
private boolean checkCanAddPeople(String how, int size) {
if (how != null) {
int much = Integer.parseInt(how);
if (size + 1 >= much) {
showToast(getResources().getString(R.string.canCallHow) + much + "方");
return false;
}
}
return true;
}
// 調用系統聯絡人返回的資料
private void backContact(Intent intent) {
Uri uri = intent.getData();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(uri, null, null, null, null);
while (cursor.moveToNext()) {
// 取得聯絡人名字
int nameFieldColumnIndex = cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String contact = cursor.getString(nameFieldColumnIndex);
// 取得聯絡人 ID,再據此查電話號碼
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
null, null);
// 一個聯絡人可能有多個號碼
while (phone.moveToNext()) {
String phoneNumber = phone.getString(phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (datas.size() == 7) {
showToast(getResources().getString(R.string.personInFull));
return;
}
if (datas.size() == 0) {
datas.add(new Contact(contact, phoneNumber));
} else {
// 先加後刪,去掉重複項
datas.add(new Contact(contact, phoneNumber));
for (int i = 0; i < datas.size(); i++) {
String n = datas.get(i).getName();
String p = datas.get(i).getPhone();
for (int j = i + 1; j < datas.size(); j++) {
if (n.equals(datas.get(j).getName())
&& p.equals(datas.get(j).getPhone())) {
datas.remove(j);
}
}
}
}
}
}
cursor.close();
// 更新主介面
adapter.notifyDataSetInvalidated();
}
@SuppressWarnings("unchecked")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_CODE_CONTACTS:
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
backContact(data);
}
break;
case RESULT_CODE_FOR_DIALOGLIST:
case RESULT_CODE_DETAIL_AND_DIALIST:
fromActivityToResult(data);
break;
default:
break;
}
}
關鍵在於用 Intent.ACTION_PICK 搭配 ContactsContract.Contacts.CONTENT_URI,並在 onActivityResult 中檢查 resultCode == RESULT_OK 且 data 不為 null,再交給 backContact 用兩段 query 分別取名字與號碼。另外別忘了在 manifest 中加上 READ_CONTACTS 權限。