在Android1.6及以前的版本中查詢手機中的電話用android.provider.Contacts.People.CONTENT_URI
在Android2.0及以後(目前到了2.1,再往後不能保證無變化)用android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI
Android2.0中獲取手機裡聯系人的方法:
public void getContact(){
//獲得所有的聯系人
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//循環遍歷
if (cur.moveToFirst()) {
int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);
int displayNameColumn = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
//獲得聯系人的ID號
String contactId = cur.getString(idColumn);
//獲得聯系人姓名
String disPlayName = cur.getString(displayNameColumn);
//查看該聯系人有多少個電話號碼。如果沒有這返回值為0
int phoneCount = cur.getInt(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if(phoneCount>0){
//獲得聯系人的電話號碼
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
if(phones.moveToFirst()){
do{
//遍歷所有的電話號碼
String phoneNumber= phones.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(phoneNumber);
}while(phones.moveToNext());
}
}
} while (cur.moveToNext());
}
}
在聯系人的電話號碼中有很多種,如果只想獲得手機號碼。代碼如下:
Java代碼
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId +" and "+ContactsContract.CommonDataKinds.Phone.TYPE+"="+ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, null, null);
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId +" and "+ContactsContract.CommonDataKinds.Phone.TYPE+"="+ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, null, null);