[英]How to get a contact's number from contact name in android
我有一個聯系人姓名並想要他的號碼。如何在 Android 中獲取相應姓名的聯系人號碼?
一個較短的版本; 您仍然需要該權限(android.permission.READ_CONTACTS)
public String getPhoneNumber(String name, Context context) {
String ret = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
ret = c.getString(0);
}
c.close();
if(ret==null)
ret = "Unsaved";
return ret;
}
以下代碼將注銷以記錄顯示名稱為 contactName 的聯系人的所有手機號碼:
Cursor cursor = null;
try {
cursor = getContentResolver().query(Data.CONTENT_URI,
new String [] { Data.RAW_CONTACT_ID },
StructuredName.DISPLAY_NAME + "=? AND "
+ Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'",
new String[] { contactName}, null);
if (cursor != null && cursor.moveToFirst()) {
do {
String rawContactId = cursor.getString(0);
Cursor phoneCursor = null;
try {
phoneCursor = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER},
Data.RAW_CONTACT_ID + "=?" + " AND "
+ Phone.TYPE + "=" + Phone.TYPE_MOBILE + " AND "
+ Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
new String[] {rawContactId}, null);
if (phoneCursor != null && phoneCursor.moveToFirst()) {
String number = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER));
Log.d(TAG, "Mobile Number: " + number);
}
} finally {
if (phoneCursor != null) {
phoneCursor.close();
}
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
試試這個代碼
people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, "person_name"+"='"+name+"'", null, null);
people.moveToFirst();
{
{
try{
String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mConno.add(position,phoneNumber);
}
phones.close();
}
if(hasPhone=="false")
{ mConname.remove(position);
}
else
position++;
}
catch(Exception e)
{
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.