1. 程式人生 > >ContentPrivider(內容提供者)獲取手機聯絡人

ContentPrivider(內容提供者)獲取手機聯絡人

手機中的聯絡人資料都是儲存在資料庫中的,但Android並沒有讓我們通過操作資料庫去讀取資料,而是通過一個ContractProvider這個應用提供了一個ContentProvider(內容提供者)訪問介面。

獲取email的方法與獲取電話號碼相同。

1.新增許可權

<uses-permission android:name="android.permission.READ_CONTACTS" />  
<uses-permission android:name="android.permission.WRITE_CONTACTS" />  

獲取手機聯絡人程式碼

private void getContacts() { 

// 得到ContentResolver物件    

ContentResolver cr = this.getContentResolver();      

// 取得電話本中開始一項的游標,主要就是查詢"contacts"表 

Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, nullnullnullnull);    

while (cursor.moveToNext())    

{    

StringBuilder sbLog = 

new StringBuilder(); 

// 取得聯絡人名字 (顯示出來的名字),實際內容在 ContactsContract.Contacts中 

int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);    

String name = cursor.getString(nameIndex); 

sbLog.append("name=" + name + ";"); 

// 取得聯絡人ID 

String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));    

// 根據聯絡人ID查詢對應的電話號碼 

Cursor phoneNumbers = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "   

+ contactId, nullnull);              

// 取得電話號碼(可能存在多個號碼)    

while (phoneNumbers.moveToNext())    

String strPhoneNumber = phoneNumbers.getString(phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));    

sbLog.append("Phone=" + strPhoneNumber + ";"); 

}    

phoneNumbers.close();  

// 根據聯絡人ID查詢對應的email 

Cursor emails = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "   

+ contactId, nullnull);              

// 取得email(可能存在多個email)    

while (emails.moveToNext())    

String strEmail = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));    

sbLog.append("Email=" + strEmail + ";"); 

}    

emails.close();  

Log.v(TAG, sbLog.toString()); 

cursor.close();