确定所选联系人的号码是手机还是固定电话?

时间:2015-12-07 03:11:04

标签: android contacts android-contacts contact contactscontract

我正在使用此代码让用户选择要发送短信的联系人:

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

...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == PICK_CONTACT){
        if(resultCode == RESULT_OK){
            Uri contactData = data.getData();
            Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
            if(cursor != null) {
                cursor.moveToFirst();
                String hasPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                if (hasPhone.equals("1")) {
                    Cursor phones = getContentResolver().query
                            (ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                            + " = " + contactId, null, null);
                    while (phones != null && phones.moveToNext()) {
                        number = phones.getString(phones.getColumnIndex
                                (ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
                    }
                    if(phones!=null) phones.close();

                } else {
                    Toast.makeText(getApplicationContext(), "This contact has no phone number", Toast.LENGTH_LONG).show();
                }
                cursor.close();

            }

        }
    }

当用户选择联系人时,有没有办法阅读电话号码类型,然后根据电话号码的类型采取行动?例如,如果有一个单元格编号,则将其作为字符串返回,如果有固定电话,则不执行任何操作,如果有,则只返回单元格?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用列TYPE来确定电话号码的类型。

while循环中添加if语句以检查电话号码的类型:

                while (phones != null && phones.moveToNext()) {
                    int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                    if(type != ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
                        // It's not a cellphone number, just skip
                        continue;
                    }
                    number = phones.getString(phones.getColumnIndex
                            (ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
                }