使用联系人卡片选择电话号码

时间:2014-07-22 21:29:13

标签: android android-intent contacts

我想从有多个电话号码的联系人中选择一个电话号码。 这可以通过Android自己的联系人列表完成吗? 我设法将所有联系人列出:

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

我选择,让我们说," John Doe"我知道,有3个电话号码。 反正有没有让Android本身向我展示那些使用意图的3个电话号码?

1 个答案:

答案 0 :(得分:0)

首先,让我们调用选择器

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

然后在onActivityResult()中让我们检查所选联系人的号码数量,如果数字> 1,则让我们显示一个对话框来选择一个:

Uri result = data.getData();
Log.v(TAG, "Got a result: " + result.toString());

// get the contact id from the Uri
String id = result.getLastPathSegment();

// query for phone numbers for the selected contact id
c = getContentResolver().query(
    Phone.CONTENT_URI, null,
    Phone.CONTACT_ID + "=?",
    new String[]{id}, null);

int phoneIdx = c.getColumnIndex(Phone.NUMBER);
int phoneType = c.getColumnIndex(Phone.TYPE);

if(c.getCount() > 1) { // contact has multiple phone numbers
    final CharSequence[] numbers = new CharSequence[c.getCount()];
    int i=0;
    if(c.moveToFirst()) {
        while(!c.isAfterLast()) { // for each phone number, add it to the numbers array
            String type = (String) Phone.getTypeLabel(this.getResources(), c.getInt(phoneType), ""); // insert a type string in front of the number
            String number = type + ": " + c.getString(phoneIdx);
            numbers[i++] = number;
            c.moveToNext();
        }
        // build and show a simple dialog that allows the user to select a number
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_contact_phone_number_and_type);
        builder.setItems(numbers, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int item) {
                String number = (String) numbers[item];
                int index = number.indexOf(":");
                number = number.substring(index + 2);
                loadContactInfo(number); // do something with the selected number
            }
        });
        AlertDialog alert = builder.create();
        alert.setOwnerActivity(this);
        alert.show();

    } else Log.w(TAG, "No results");
} else if(c.getCount() == 1) {
    // contact has a single phone number, so there's no need to display a second dialog
}