我正在开始联系选择器活动以获取电话号码
val i = Intent(Intent.ACTION_PICK)
i.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
startActivityForResult(i, REQUEST_CODE_PICK_CONTACT)
如果联系人没有默认号码,则会显示电话号码选择器对话框
如果联系人有默认号码,则不会显示电话号码选择器对话框,默认情况下会采用默认号码。
所以我的问题:即使联系人有默认号码,如何显示电话选择器对话框?
答案 0 :(得分:1)
使用联系人选择器,而不是使用电话选择器,并自己显示电话对话框。
Intent intent = Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_SELECT_CONTACT);
...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_CONTACT && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
long contactId = getContactIdFromUri(contactUri);
List<String> phones = getPhonesFromContactId(contactId);
showPhonesDialog(phones);
}
}
private long getContactIdFromUri(Uri contactUri) {
Cursor cur = getContentResolver().query(contactUri, new String[]{ContactsContract.Contacts._ID}, null, null, null);
long id = -1;
if (cur.moveToFirst()) {
id = cur.getLong(0);
}
cur.close();
return id;
}
private List<String> getPhonesFromContactId(long contactId) {
Cursor cur = getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI,
new String[]{CommonDataKinds.Phone.NUMBER},
CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{String.valueOf(contactId)}, null);
List<String> phones = new ArrayList<>();
while (cur.moveToNext()) {
String phone = cur.getString(0);
phones.add(phone);
}
cur.close();
return phones;
}
private void showPhonesDialog(List<String> phones) {
String[] phonesArr = phones.toArray(new String[0]);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select a phone:");
builder.setItems(phonesArr, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.i("Phone Selection", "user selected: " + phonesArr[which]);
}
});
builder.show();
}