Android-contentprovider 获取手机联系人

                                 Android-contentprovider 获取手机联系人

一,布局文件(3个)

1,activity_main.xml



    
    
    
    
        
    
    


3,contact_list_item.xml


    
    
    
    
        
    
    

二,建实体类,
public class ContactBean {
   private int contactId;
   private String desplayName;
   private String phoneNum;
   private String sortKey;
   private Long photoId;
   private String lookUpKey;
   private int selected = 0;
   private String formattedNumber;
   private String pinyin;
   public int getContactId() {
      return contactId;
   }
   public void setContactId(int contactId) {
      this.contactId = contactId;
   }
   public String getDesplayName() {
      return desplayName;
   }
   public void setDesplayName(String desplayName) {
      this.desplayName = desplayName;
   }
   public String getPhoneNum() {
      return phoneNum;
   }
   public void setPhoneNum(String phoneNum) {
      this.phoneNum = phoneNum;
   }
   public String getSortKey() {
      return sortKey;
   }
   public void setSortKey(String sortKey) {
      this.sortKey = sortKey;
   }
   public Long getPhotoId() {
      return photoId;
   }
   public void setPhotoId(Long photoId) {
      this.photoId = photoId;
   }
   public String getLookUpKey() {
      return lookUpKey;
   }
   public void setLookUpKey(String lookUpKey) {
      this.lookUpKey = lookUpKey;
   }
   public int getSelected() {
      return selected;
   }
   public void setSelected(int selected) {
      this.selected = selected;
   }
   public String getFormattedNumber() {
      return formattedNumber;
   }
   public void setFormattedNumber(String formattedNumber) {
      this.formattedNumber = formattedNumber;
   }
   public String getPinyin() {
      return pinyin;
   }
   public void setPinyin(String pinyin) {
      this.pinyin = pinyin;
   }
}

三,写具體代码
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

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

public class Test extends AppCompatActivity {
    private ContactListAdapter adapter;
    private ListView contactList;
    private List list;
    private AsyncQueryHandler asyncQueryHandler; // 异步查询数据库类对象
//    private QuickAlphabeticBar alphabeticBar; // 快速索引条
    private List li;
    private Map contactIdMap = null;
    private EditText edit_querys;
    private TextView tv_test_contacts;
    private String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        contactList = (ListView) findViewById(R.id.contact_list);
        tv_test_contacts = (TextView) findViewById(R.id.tv_test_contacts);
      // 实例化
        asyncQueryHandler = new MyAsyncQueryHandler(getContentResolver());
        init();
    }
    public void getAllContacts(View view){
        setAdapter(list);
    }
    /**
     * 初始化数据库查询参数
     */
    private void init() {
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri;
        // 查询的字段
        String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
                ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY };
        // 按照sort_key升序查詢
        asyncQueryHandler.startQuery(0, null, uri, projection, null, null,
                "sort_key COLLATE LOCALIZED asc");
    }
    /**
     *
     * @author Administrator
     *
     */
    private class MyAsyncQueryHandler extends AsyncQueryHandler {
        public MyAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor != null && cursor.getCount() > 0) {
                contactIdMap = new HashMap();
                list = new ArrayList();
                cursor.moveToFirst(); // 游标移动到第一项
                for (int i = 0; i < cursor.getCount(); i++) {
                    cursor.moveToPosition(i);
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                    String sortKey = cursor.getString(3);
                    int contactId = cursor.getInt(4);
                    Long photoId = cursor.getLong(5);
                    String lookUpKey = cursor.getString(6);
                    if (contactIdMap.containsKey(contactId)) {
                        // 无操作
                    } else {
                        // 创建联系人对象
                        ContactBean contact = new ContactBean();
                        contact.setDesplayName(name);
                        contact.setPhoneNum(number);
                        contact.setPhotoId(photoId);
                        contact.setSortKey(sortKey);
                        Log.i("ccc",photoId+"");
                        contact.setLookUpKey(lookUpKey);
                        list.add(contact);
                        contactIdMap.put(contactId, contact);
                    }
            }
                }
            super.onQueryComplete(token, cookie, cursor);
        }
    }

    private void setAdapter(final List list) {
        adapter = new ContactListAdapter(this, list);
        contactList.setAdapter(adapter);
    }
    public void jumpContacts(View view){
        Uri uri=Uri.parse("content://contacts/people");
        Intent intent=new Intent(Intent.ACTION_PICK,uri);
        startActivityForResult(intent,0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 0:
                if(data==null)
                {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri=data.getData();
                String[] contacts=getPhoneContacts(uri);
                s = contacts[0]+":"+contacts[1];
                tv_test_contacts.setText(s);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
  private String[] getPhoneContacts(Uri uri){
        String[] contact=new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor=cr.query(uri,null,null,null,null);
        if(cursor!=null)
        {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0]=cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if(phone != null){
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        }
        else
        {
            return null;
        }
        return contact;
    }
}
三.1適配器ContactListAdapter 

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import android.content.ContentUris;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.Toast;


public class ContactListAdapter extends BaseAdapter {
   private LayoutInflater inflater;
   private List list;
   private HashMap alphaIndexer; // 字母索引
   private String[] sections; // 存储每个章节
   private Context ctx; // 上下文

   public ContactListAdapter(Context context, List list) {
      this.ctx = context;
      this.inflater = LayoutInflater.from(context);
      this.list = list;
      this.alphaIndexer = new HashMap();
      this.sections = new String[list.size()];
      for (int i = 0; i < list.size(); i++) {
         // 得到字母
         String name = getAlpha(list.get(i).getSortKey());
         if (!alphaIndexer.containsKey(name)) {
            alphaIndexer.put(name, i);
         }
      Set sectionLetters = alphaIndexer.keySet();
      }
      ArrayList sectionList = new ArrayList(sectionLetters);
      Collections.sort(sectionList);
      sections = new String[sectionList.size()];
      sectionList.toArray(sections);
   }

   @Override
   public int getCount() {
      return list.size();
   }
   @Override
   public Object getItem(int position) {

      return list.get(position);
   }
   @Override
   public long getItemId(int position) {
      return position;
   }
   public void remove(int position) {
      list.remove(position);
   }
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
         convertView = inflater.inflate(R.layout.contact_list_item, null);
         holder = new ViewHolder();
         holder.quickContactBadge = (QuickContactBadge) convertView
               .findViewById(R.id.qcb);
         holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
         holder.name = (TextView) convertView.findViewById(R.id.name);
         holder.number = (TextView) convertView.findViewById(R.id.number);
         convertView.setTag(holder);
      } else {
         holder = (ViewHolder) convertView.getTag();
      }
      ContactBean contact = list.get(position);
      String name = contact.getDesplayName();
      String number = contact.getPhoneNum();
      holder.name.setText(name);
      holder.number.setText(number);
      holder.quickContactBadge.assignContactUri(Contacts.getLookupUri(contact.getContactId(), contact.getLookUpKey()));
      if (0 == contact.getPhotoId()) {
//       holder.quickContactBadge.setImageResource(R.drawable.touxiang);
      } else {
         Uri uri = ContentUris.withAppendedId(
               Contacts.CONTENT_URI,
               contact.getContactId());
         InputStream input = Contacts
               .openContactPhotoInputStream(ctx.getContentResolver(), uri);
         Bitmap contactPhoto = BitmapFactory.decodeStream(input);
         holder.quickContactBadge.setImageBitmap(contactPhoto);
      }
      // 当前字母
      String currentStr = getAlpha(contact.getSortKey());
      // 前面的字母
      String previewStr = (position - 1) >= 0 ? getAlpha(list.get(
            position - 1).getSortKey()) : " ";
      if (!previewStr.equals(currentStr)) {
         holder.alpha.setVisibility(View.VISIBLE);
         holder.alpha.setText(currentStr);
      } else {
         holder.alpha.setVisibility(View.GONE);
      }
      return convertView;
   }

   private static class ViewHolder {
      QuickContactBadge quickContactBadge;
      TextView alpha;
      TextView name;
      TextView number;
   }
   /**
    * 获取首字母
    *
    * @param str
    * @return
    */
   private String getAlpha(String str) {
      if (str == null) {
         return "#";
      }
      if (str.trim().length() == 0) {
         return "#";
      }
      char c = str.trim().substring(0, 1).charAt(0);
      // 正则表达式匹配
      Pattern pattern = Pattern.compile("^[A-Za-z]+$");
      if (pattern.matcher(c + "").matches()) {
         return (c + "").toUpperCase(); // 将小写字母转换为大写
      } else {
         return "#";
      }
   }
}


 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   

你可能感兴趣的:(Android-contentprovider 获取手机联系人)