首先看一個簡單的例子,這個函數獲取設備上所有的聯系人ID和聯系人NAME:
public void fetchAllContacts() { ContentResolver contentResolver = this.getContentResolver(); Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null, null, null); cursor.getCount(); while(cursor.moveToNext()) { System.out.println(cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID))); System.out.println(cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME))); } cursor.close(); }
運行結果:
11-05 14:13:09.987: I/System.out(4692): 13
11-05 14:13:09.987: I/System.out(4692): 張三
11-05 14:13:09.987: I/System.out(4692): 31
11-05 14:13:09.987: I/System.out(4692): 李四
解釋:
ContentResolver contentResolver = this.getContentResolver();
this在這里指的是context,ContentResolver直譯為內容解析器,什么東西?Android中程序間數據的共享是通過Provider/Resolver進行的。提供數據(內容)的就叫Provider,Resovler提供接口對這個內容進行解讀。
在這里,系統提供了聯系人的Provider,那么我們就需要構建一個Resolver來讀取聯系人的內容。
Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
根據Android文檔,
public final Cursor query (Uri uri, String[] projection,String selection,String[] selectionArgs, String sortOrder)
uri : 上面我們提到了Android提供內容的叫Provider,那么在Android中怎么區分各個Provider?有提供聯系人的,有提供圖片的等等。所以就需要有一個唯一的標識來標識這個Provider,Uri就是這個標識,android.provider.ContactsContract.Contacts.CONTENT_URI就是提供聯系人的內容的地址,可惜這個內容提供者提供的數據很少。
projection : 真不知道為什么要用這個單詞,這個參數告訴查詢要返回的列(Column),比如Contacts Provider提供了聯系人的ID和聯系人的NAME等內容,如果我們只需要NAME,那么我們就應該使用:
projection=new String[]{android.provider.ContactsContract.Contacts.DISPLAY_NAME};
selection :查詢where字句
selectionArgs : 查詢條件屬性值
sortOrder :結果排序規則