[android] 手机卫士读取联系人

获取ContentResolver内容解析器对象,通过getContentResolver()方法

调用ContentResolver对象的query()方法,得到raw_contacts表里面的数据,得到Cursor对象

参数:Uri对象,字段String数组

获取Uri对象,通过Uri.parse(“content://com.android.contacts/raw_contacts”)方法,

while循环Cursor对象,条件是Cursor对象moveToNext()方法为真

调用Cursor对象的getString()方法,参数是索引

判断不为null,查询另一张表

调用ContentResolver对象的query()方法,得到data表里面的数据,得到Cursor对象

参数:Uri对象,字段String[]数组(data1,mimetype,条件String,条件值String[]数组(contact_id

Uri对象是Uri.parse(“content://com.android.contacts/data”)

循环和上面一样

姓名对应的类型是vnd.android.cursor.item/name

电话对应的类型是vnd.android.cursor.item/phone_v2

需要权限,android.permisssion.READ_CONTACTS

调用ListView对象的setAdapter()方法,分配数据到视图,参数是Adapter对象

通过new SimpleAdapter()来获得Adapter对象

参数:上下文,数据集合,布局资源,字段String[]数组,控件int[] id数组

package com.qingguow.mobilesafe.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
/**
 * 读取手机联系人
 * @author taoshihan
 *
 */
public class PhoneContactsUtil {
    public static List<Map<String,String>> getContacts(Context context){
        ContentResolver resolver=context.getContentResolver();
        Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri=Uri.parse("content://com.android.contacts/data");
        List<Map<String,String>> contacts=new ArrayList<Map<String,String>>();
        
        //循环联系人表
        Cursor cursor=resolver.query(uri, new String[]{"contact_id"}, null, null, null);
        while(cursor.moveToNext()){
            String id=cursor.getString(cursor.getColumnIndex("contact_id"));
            if(id!=null){
                Map<String,String> contact=new HashMap<String,String>();
                //查找数据表
                Cursor dataCursor=resolver.query(dataUri, new String[]{"data1","mimetype"},"raw_contact_id=?", new String[]{id}, null);
                while(dataCursor.moveToNext()){
                    String data1=dataCursor.getString(dataCursor.getColumnIndex("data1"));
                    String mimetype=dataCursor.getString(dataCursor.getColumnIndex("mimetype")); 
                    System.out.println("data1:"+data1+",mimetype:"+mimetype);
                    if(mimetype.equals("vnd.android.cursor.item/name")){
                        contact.put("name", data1);
                    }else if(mimetype.equals("vnd.android.cursor.item/phone_v2")){
                        contact.put("phone", data1);
                    }
                }
                contacts.add(contact);
                dataCursor.close();
            }
        }
        cursor.close();
        return contacts;
    }
}
原文地址:https://www.cnblogs.com/taoshihan/p/5388857.html