android 获取通讯录联系人信息

  android 中获取通讯录中联系人信息,代码如下:

  

    /**
     * 获取联系人信息,包括:名称、号码、头像
     * @return
     */
    private ArrayList<PhoneContactor> getPhoneContacts(){
        
    Log.i(TAG, "getPhoneContacts");
        
    ContentResolver resolver=this.getContentResolver();
    
    ArrayList<PhoneContactor> list = new ArrayList<PhoneContactor>();
         
    String[] columns = new String[] {Phone.DISPLAY_NAME,Phone.NUMBER,Phone.PHOTO_ID,Phone.CONTACT_ID};
         
   Cursor cursor = resolver.query(Phone.CONTENT_URI, columns, null,null, null);

   Bitmap photo_default=BitmapFactory.decodeResource(getResources(), R.drawable.contact_photo_default); 
       
   while (cursor.moveToNext()) {

                PhoneContactor pc = new PhoneContactor();
                
                String name=cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
                
                String number=cursor.getString(cursor.getColumnIndex(Phone.NUMBER));


                if(TextUtils.isEmpty(number)){ //判断号码是否为空
                
                continue;
                }
                
                long photoId=cursor.getLong(cursor.getColumnIndex(Phone.PHOTO_ID));
                
                long contactId=cursor.getLong(cursor.getColumnIndex(Phone.CONTACT_ID));
                
                //得到联系人头像Bitamp   
                Bitmap contactPhoto = null;  
              
                //photoId 大于0表示联系人有头像,否则设置一个默认头像   
                if(photoId > 0 ) {  
                    
                Uri uri =ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactId);  
                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);  
                    contactPhoto = BitmapFactory.decodeStream(input);  
                
                }else {  
                
                    contactPhoto = photo_default; 
                }  
                
                pc.name(name);
                pc.number(number);
                pc.photo(contactPhoto);
                
                list.add(pc);
                 
                Log.d(TAG, "name:" + pc.name());
                Log.d(TAG, "number:" + pc.number());
        }
        
        cursor.close();
         
        return list;
    }

其中:PhoneContactor为自定义的存储联系人信息的类,最后别忘了加上权限:

<uses-permission android:name="android.permission.READ_CONTACTS"/> 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值