根据网上的一些资料自己学习整理的。
在查询中要注意由于android 2.0以上支持多个连续人,所以在获得联系人号码时有一定区别的。
public class GetContextActivity extends Activity {
private TextView tv = null;
private String contact_content = "";//用于保存所有查询到信息
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow();
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.tv = (TextView) this.findViewById(R.id.tt_contact_name);
this.tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv.setText(contact_content);
}
});
}
public void getContact(){//获得所有联系人的资料
ContentResolver cr =getContentResolver();
Cursor crs = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (crs.moveToNext()){
int nameFiedColumnIndex = crs.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = crs.getString(nameFiedColumnIndex);//获得联系人姓名
int numFiedColumnIndex = crs.getColumnIndex(PhoneLookup.TIMES_CONTACTED);
String times = crs.getString(numFiedColumnIndex);//获得联系次数
String contact_Id = crs.getString(crs.getColumnIndex(ContactsContract.Contacts._ID));//获得当前联系人的ID索引用于查询号码
Cursor crs_Num = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contact_Id, null, null);//注意第一个参数和上一个游标crs的参数是不同的。上一个是ContactsContract.Contacts.CONTENT_URI,并且第三个参数是为了得到和前面匹配的电话号码
this.contact_content += "contact: " + contact + " Times:" + times;
while (crs_Num.moveToNext()){
String strPhoneNum = crs_Num.getString(crs_Num.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
this.contact_content += " Number: "+strPhoneNum;
}
this.contact_content += "\n";
}
crs.close();
}
}
2.0 以下查询可以使用
int nameFiedColumnIndex = crs.getColumnIndex(PhoneLookup.NUMBER);//获得联系人电话的表头ID
String contact = crs.getString(nameFiedColumnIndex);
总的来所整个操作不是特别复杂,也是本人第一次写博文,如果有不完善的地方,请见谅。