我正在使用此代码让用户选择要向其发送短信的联系人:
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();
}
}
}
有没有办法在用户选择联系人时读取电话号码类型,然后根据电话号码的类型采取行动?例如,如果有手机号,则将其作为字符串返回,如果有固定电话,则什么也不做,如果两者都有,则只返回手机号?
最佳答案
是的,您可以使用列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("[-() ]", "");
}
关于android - 确定所选联系人的号码是手机还是固定电话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34125819/