GetContactInfoUtils (get a phone contact name, telephone, head of the tools)

Purpose: to obtain a contact name, phone, picture
functions:
1. getContactInfo : Get a contact name, phone, picture a unique identification
2. GETIMG : Contract table to get a picture / avatar resource based on a unique identification

Little mention: the need for permission, and is required in conjunction with Javabean

//获取联系人名称,电话,头像
public class GetContactInfoUtils {
    //获取联系人名称,电话,头像唯一标识
   public static List<ContactInfo>getContactInfo(Context context){
       List<ContactInfo> list=new ArrayList<>();
       //创建获取联系人的内容解析者
       ContentResolver resolver = context.getContentResolver();
       //ContactsContract.CommonDataKinds:获取到data表 , Phone.CONTENT_URI:获取联系人数据库的URI
       Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
       //定义我们所需要查询的条件
       String[] projection=new String[]{
               ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,//获取联系人名称
               ContactsContract.CommonDataKinds.Phone.NUMBER,//获取联系人号码
               ContactsContract.CommonDataKinds.Phone.CONTACT_ID//获取联系人的唯一标识
       };
       //获取
       Cursor cursor=resolver.query(uri,projection,null,null,null);
       Log.e("YFF", "getContactInfo: ");
       //循环
       while(cursor.moveToNext()){
           String name=cursor.getString(0);
           Log.e("YFF", "getContactInfo: "+name);
           String unmber=cursor.getString(1);
           int id=cursor.getInt(2);
           //为了方便管理,将获取的信息存放到实体类中(JavaBean)
           ContactInfo contactInfo=new ContactInfo();
           contactInfo.setName(name);
           contactInfo.setUnmber(unmber);
           contactInfo.setId(id);
           //添加到容器
           list.add(contactInfo); }
       return  list;
   }
   //根据唯一标识去获取Contract表里的图片/头像资源
   public  static Bitmap getImg(Context context,int i){
       ContentResolver contentResolver=context.getContentResolver();
       //定义URl,但是不能再向上面拿名称那样去取得字段
       Uri uri=Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,i+"");
      //ContactsContract.Contacts:相当于联系人APP的数据库中Contact表,通过openContactPhotoInputStream拿到流对象
       InputStream is=ContactsContract.Contacts.openContactPhotoInputStream(contentResolver,uri);
       //将拿到的资源的转换成我们所需要的图片
       Bitmap biemap= BitmapFactory.decodeStream(is);
       //关闭流
       if (is!=null){
           try {
               is.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return biemap;
   }
}

Use ContentResolver (content resolver) to obtain a contact name, telephone, Avatar

Published 77 original articles · won praise 411 · views 270 000 +

Guess you like

Origin blog.csdn.net/qq_42761395/article/details/100039285