Android 开发工具类 37_ ContactInfoProvider

Android 手机中的联系人信息保存在  data\data\com.android.providers.contacts\databases\contacts2.db 中。主要有

raw_contacts 表:用来存放联系人的 id;

data 表:用来存放联系人的具体数据;

mimetypes 表:保存数据类型。

 1 public class ContactInfoProvider {
 2 
 3     private Context context;
 4 
 5     public ContactInfoProvider(Context context) {
 6         this.context = context;
 7     }
 8 
 9     /**
10      * 返回所有的联系人的信息
11      * 
12      * @return
13      */
14     public List<ContactInfo> getContactInfos() {
15     
16         // 将所有联系人存入该集合
17         List<ContactInfo> infos = new ArrayList<ContactInfo>();
18         // 获取 raw_contacts 表所对应的 Uri
19         Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
20         // 获取 data 表所对应的 Uri
21         Uri datauri = Uri.parse("content://com.android.contacts/data");
22         // 参数二:所要查询的列,即联系人的id。获取一个查询数据库所返回的结果集
23         Cursor cursor = context.getContentResolver().query(uri,    new String[] { "contact_id" }, null, null, null);
24         // 移动游标
25         while (cursor.moveToNext()) {
26             // 因为我们只需要查询一列数据-联系人的id,所以我们传入0
27             String id = cursor.getString(0);
28             // 用于封装每个联系人的具体信息
29             ContactInfo info = new ContactInfo();
30             // 得到 id 后,我们通过该 id 来查询 data 表中的联系人的具体数据(data表中的data1中的数据)。
31             // 参数二:null,会将所有的列返回回来
32             // 参数三:选择条件    返回一个在data表中查询后的结果集
33             Cursor dataCursor = context.getContentResolver().query(datauri,    null, "raw_contact_id=?", new String[] { id }, null);
34             while (dataCursor.moveToNext()) {
35                 //dataCursor.getString(dataCursor.getColumnIndex("mimetype"))获取data1列中具体数据的数据类型,这里判断的是联系人的姓名
36                 if ("vnd.android.cursor.item/name".equals(dataCursor.getString(dataCursor.getColumnIndex("mimetype")))) {
37                     //dataCursor.getString(dataCursor.getColumnIndex("data1"))获取data1列中的联系人的具体数据
38                     info.setName(dataCursor.getString(dataCursor.getColumnIndex("data1")));
39                 } else if ("vnd.android.cursor.item/phone_v2".equals(dataCursor.getString(dataCursor.getColumnIndex("mimetype")))) {//数据类型是否是手机号码
40                     info.setPhone(dataCursor.getString(dataCursor.getColumnIndex("data1")));
41                 }
42             }
43             // 每查询一个联系人后就将其添加到集合中
44             infos.add(info);
45             info = null;
46             // 关闭结果集
47             dataCursor.close();
48         }
49         cursor.close();
50         return infos;
51     }
52 }

 

posted @ 2015-08-20 16:41  壬子木  阅读(377)  评论(0编辑  收藏  举报