安卓读取通讯录信息

来源:互联网 发布:天刀洛天依捏脸数据 编辑:程序博客网 时间:2024/05/22 13:28

读取通讯录数据库的信息。

//因为读取通讯录可能是耗时操作 所以另外开启线程    private void initData() {        new Thread() {            @Override            public void run() {                //1.获取内容解析器对象                ContentResolver contentResolver = getContentResolver();                //2.做查询系统联系人过程(取得权限)                Cursor cursor = contentResolver.query(Uri.parse("content://com.android.contacts/raw_contacts"),                        new String[]{"contact_id"},                        null, null, null);                /**                 * 当集合作为成员变量使用时 在使用之前一定要清空                 */                contactList.clear();                //3.循环游标,直到没有数据为止                while (cursor.moveToNext()) {                    String id = cursor.getString(0);//                    Log.i(tag,"id=="+id);                    //4.根据用户唯一性id值,查询data表和mimetype表生成的视图,获取data和mimetype字段                    Cursor indexCursor = contentResolver.query(Uri.parse("content://com.android.contacts/data"),                            new String[]{"data1", "mimetype"},                            "raw_contact_id = ?",                            new String[]{id}, null);                    //5循环获取每一个联系人的电话号码和姓名,数据类型                    HashMap<String, String> hashMap = new HashMap<String, String>();                    while (indexCursor.moveToNext()) {                        String data = indexCursor.getString(0);                        String type = indexCursor.getString(1);                        Log.i(tag, "data" + indexCursor.getString(0));                        Log.i(tag, "mimetype" + indexCursor.getString(1));                        //区分类型填充数据                        if (type.equals("vnd.android.cursor.item/phone_v2")) {                            //数据非空判断                            if (!TextUtils.isEmpty(data)) {                                hashMap.put("phone", data);                            }                        } else if (type.equals("vnd.android.cursor.item/name")) {                            if (!TextUtils.isEmpty(data)) {                                hashMap.put("name", data);                            }                        }                    }                    indexCursor.close();                    contactList.add(hashMap);                }                cursor.close();                //7.消息机制,发送空消息告知主线程可以使用填充好的数据                mHandler.sendEmptyMessage(0);            }        }.start();    }
0 0
原创粉丝点击