【问题标题】:How to pick contact's non default phone number?如何选择联系人的非默认电话号码?
【发布时间】:2018-06-24 01:11:39
【问题描述】:

我正在启动联系人选择器活动以获取电话号码

    val i = Intent(Intent.ACTION_PICK)
    i.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
    startActivityForResult(i, REQUEST_CODE_PICK_CONTACT)

如果联系人没有默认号码,则会显示电话号码选择器对话框

如果联系人有默认号码,则不会显示电话号码选择器对话框,并且默认采用默认号码。

所以我的问题:即使联系人有默认号码,如何显示电话选择器对话框?

【问题讨论】:

  • 你试过了吗?对于意图类型intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
  • @LokeshDesai,谢谢你的建议。我试过了,但没有显示电话号码选择器对话框

标签: android android-intent android-contacts contactscontract


【解决方案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();
}

【讨论】:

  • 感谢您的回答。可以添加选择参数来获取一个联系人的号码。现在它正在占用所有联系人号码。光标 cur = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?", new String[] {String.valueOf(contactId)}, null);
猜你喜欢
  • 2012-06-13
  • 1970-01-01
  • 2018-01-08
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
相关资源
最近更新 更多