安卓读取通讯录信息

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

//因为读取通讯录可能是耗时操作 所以另外开启线程
    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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值