Granting Access 授予許可權
<uses-permission android:name="android.permission.READ_CONTACTS" />
Querying the contact database 連絡人資料庫查詢
Retrieving Contact Details 擷取連絡方式
本的連絡人資訊儲存在連絡人表中,而詳細資料儲存在個人表中。在 Android1.x 中查詢的連絡人記錄資料庫的URI是People.CONTENT_URI。
Java代碼
package com.test;import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;import android.os.Bundle;
import android.provider.Contacts.People;
public class TestContacts extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(People.CONTENT_URI, null, null, null, null);
if(cur.getCount()>0){
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
}
}
}
}
Phone Numbers 電話號碼
查詢的URI換成Contacts.Phones.CONTENT_URI。
Java代碼
if (cur.getInt(cur.getColumnIndex(People.PRIMARY_PHONE_ID)) > 0) {
Cursor pCur = cr.query(Contacts.Phones.CONTENT_URI,null, Contacts.Phones.PERSON_ID +" = ?",new String[]{id}, null);
int i=0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount]; String[] phoneType = new String[pCount];
while (pCur.moveToNext()) {
phoneNum[i] = pCur.getString(pCur.getColumnIndex(Contacts.Phones.NUMBER));
phoneType[i] = pCur.getString(pCur.getColumnIndex(Contacts.Phones.TYPE)); i++;
}
}
以儲存多個電話號碼,我們需要遍曆返回的結果。查詢除了返回電話號碼外還返回了其他(家庭,工作,手機等)類型。
Email Addresses 郵件地址
Java代碼
Cursor emailCur = cr.query(Contacts.ContactMethods.CONTENT_EMAIL_URI,null, Contacts.ContactMethods.PERSON_ID + " = ?",new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses }
emailCur.close();
Notes 注釋
為每個連絡人附加自訂注釋。注釋儲存在連絡人記錄中,並通過People.NOTES儲存的資料進行訪問。
String notes=cur.getString(cur.getColumnIndex(People.NOTES));
Postal Addresses 郵政地址
每個連絡人都可以儲存多個郵政地址。地址儲存在連絡方式表中,要擷取資料,需要有次要條件。添加適配Contacts.ContactMethods.CONTENT_POSTAL_ITEM_TYPE的條件Contacts.ContactMethods.KIND來訪問Contacts.ContactMethods.CONTENT_URI傳遞過來的地址。
Java代碼
String addrWhere = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] addrWhereParams = new String[]{id, Contacts.ContactMethods.CONTENT_POSTAL_ITEM_TYPE}; Cursor addrCur = cr.query(Contacts.ContactMethods.CONTENT_URI, null, addrWhere, addrWhereParams, null); while(addrCur.moveToNext()) { String addr = addrCur.getString( addrCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA)); String type = addrCur.getString( addrCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE)); } addrCur.close();