又是时隔好久才来写文章,,,,,悲惨啊...最近在项目中有一个获取手机联系人并且可以通过短信来邀请他的这么一个功能...今天来写一篇获取手机联系人和检索联系人的文章....也查看了网上很多的文章..感觉大部分都可以直接使用,所以决定自己试试...好了下面就开始吧...
1. 添加相关权限
<!-- 读取联系人权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
2.我们在画一下布局
首先是activity的布局,如下:
一个自定义的EditText ,一个listView ,一个SideBar
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="@color/light_gray"/>
<com.yuandian.wanna.view.ClearEditText
android:id="@+id/filter_edit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dip"
android:background="@color/white"
android:hint="搜索联系人"
android:paddingLeft="10dp"
android:singleLine="true"
android:textColor="@color/black"
android:textColorHint="@color/light_gray"
android:textSize="15.0dip"/>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="@color/light_gray"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/country_lvcountry"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:divider="@null"
android:scrollbars="none"/>
<TextView
android:id="@+id/title_layout_no_friends"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_gravity="right|top"
android:background="#E0E0E0"
android:gravity="center_vertical"
android:text="没有匹配的联系人"
android:textColor="#454545"
android:visibility="gone"/>
<LinearLayout
android:id="@+id/title_layout"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="right|top"
android:background="#ff303030"
android:orientation="vertical">
<TextView
android:id="@+id/title_layout_catalog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E0E0E0"
android:paddingBottom="5dip"
android:paddingLeft="5dip"
android:paddingTop="5dip"
android:textColor="#454545"/>
</LinearLayout>
<TextView
android:id="@+id/dialog"
android:layout_width="80.0dip"
android:layout_height="80.0dip"
android:layout_gravity="center"
android:background="@android:color/darker_gray"
android:gravity="center"
android:textColor="#ffffffff"
android:textSize="30.0dip"
android:visibility="invisible"/>
<com.yuandian.wanna.activity.chat.readcontacts.view.SideBar
android:id="@+id/sidrbar"
android:layout_width="30dip"
android:layout_height="match_parent"
android:layout_gravity="right|center"/>
</FrameLayout>
</LinearLayout>
下面是ListView 的item 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--android:layout_gravity="right"
android:background="?android:attr/activatedBackgroundIndicator"-->
<TextView
android:id="@+id/catalog"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:background="#E0E0E0"
android:paddingBottom="5dip"
android:paddingLeft="5dip"
android:paddingTop="5dip"
android:text="A"
android:textColor="#454545"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="62dp"
android:background="@color/white"
android:orientation="horizontal"
android:padding="6dip">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="left"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="10dp">
<TextView
android:id="@+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:text="姓名"
android:textColor="@color/black"
android:textSize="18dp"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/mBottomLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="#f2f2f2"/>
</LinearLayout>
</LinearLayout>
然后就是Activity代码:
我们通过Cursor 来获取联系人
ContentResolver cr = getContentResolver();
phoneContacts = new ArrayList<PhoneContacts>();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_ALTERNATIVE);
if (cursor != null && cursor.getCount() > 0) {
Log.d("AYD", "cursor size is " + cursor.getCount());
phonelist = new PhoneContactsList();
list = new ArrayList<>();
except = new HashMap<>();
cursor.moveToPosition(-1);
//通过while循环取出数据并放到list中
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phone = PhoneNumberFommatter.NumberFommatter(phone);
PhoneContacts contacts = new PhoneContacts(name, phone);
ContactInfoBean mContact = new ContactInfoBean(name, phone);
except.put(phone, list.size());
list.add(mContact);
phoneContacts.add(contacts);
mContact.setPhoneName(mContact.getPhoneName());
// 汉字转换成拼音
String pinyin = characterParser.getSelling(mContact.getPhoneName());
String sortString = pinyin.substring(0, 1).toUpperCase();
// 正则表达式,判断首字母是否是英文字母
if (sortString.matches("[A-Z]")) {
mContact.setSortLetters(sortString.toUpperCase());
} else {
mContact.setSortLetters("#");
}
}
cursor.close();
phonelist.setPhoneContacts(phoneContacts);
Collections.sort(list, pinyinComparator);
} else {
Toast.makeText(this, "没有联系人", Toast.LENGTH_LONG).show();
}
检索list中的数据:
/**
* 根据输入框中的值来过滤数据并更新ListView
*
* @param filterStr
*/
private void filterData(String filterStr) {
List<ContactInfoBean> filterDateList = new ArrayList<>();
if (TextUtils.isEmpty(filterStr)) {
filterDateList = list;
tvNofriends.setVisibility(View.GONE);
} else {
filterDateList.clear();
for (ContactInfoBean sortModel : list) {
String name = sortModel.getPhoneName();
if (name.indexOf(filterStr.toString()) != -1
|| characterParser.getSelling(name).startsWith(
filterStr.toString())) {
filterDateList.add(sortModel);
}
}
}
// 根据a-z进行排序
Collections.sort(filterDateList, pinyinComparator);
adapter.updateListView(filterDateList);
if (filterDateList.size() == 0) {
tvNofriends.setVisibility(View.VISIBLE);
}
}
然后就是Adapter中的数据显示附上所有的代码
public class ContactsAdapter extends BaseAdapter {
private List<ContactInfoBean> list;
// private AddressAdapter.ListItemClickHelper listener;
private Context context;
public ContactsAdapter(Context context, List<ContactInfoBean> src) {
this.context = context;
list = src;
Log.e("AYD","-------contactsAdapter" + list.size());
}
/**
* 当ListView数据发生变化时,调用此方法来更新ListView
*
* @param list
*/
public void updateListView(List<ContactInfoBean> list) {
this.list = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
LinearLayout ll;
if (convertView != null) {
ll = (LinearLayout) convertView.getTag();
} else {
ll = new LinearLayout(context);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.contacts_list_item, ll);
convertView.setTag(ll);
}
TextView name = (TextView) convertView.findViewById(R.id.contact_name);
TextView add = (TextView) convertView.findViewById(R.id.add_friend);
TextView catalog = (TextView) convertView.findViewById(R.id.catalog);
// add.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, parent, position);
// }
// });
ContactInfoBean c = list.get(position);
// 根据position获取分类的首字母的Char ascii值
int section = getSectionForPosition(position);
// 如果当前位置等于该分类首字母的Char的位置 ,则认为是第一次出现
if (position == getPositionForSection(section)) {
catalog.setVisibility(View.VISIBLE);
catalog.setText(c.getSortLetters());
} else {
catalog.setVisibility(View.GONE);
}
name.setText(c.getPhoneName());
Log.e("AYD",position + "th item is " + c.getPhoneNo() + ", contactID:" + c.getContactId() + ", memberID:" + c.getMemberId());
if (c.getMemberId() != null) {
if (c.getContactId() == null || c.getContactId().equals("")) {
add.setText("添加");
} else {
add.setText("已添加");
}
} else {
add.setText("邀请");
}
return ll;
}
/**
* 根据ListView的当前位置获取分类的首字母的Char ascii值
*/
public int getSectionForPosition(int position) {
return list.get(position).getSortLetters().charAt(0);
}
/**
* 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
*/
public int getPositionForSection(int section) {
for (int i = 0; i < getCount(); i++) {
String sortStr = list.get(i).getSortLetters();
char firstChar = sortStr.toUpperCase().charAt(0);
if (firstChar == section) {
return i;
}
}
return -1;
}
}
割-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------割
以上就是如何获取手机联系人的代码,我从项目中把这个功能提出来作为demo 一会上传,,,,有兴趣的同学看看...总之代码这东西就是要经常写,看别人的代码远不如动手自己慢慢写..好了.....这就样吧....bug还等着我呢,,我去改bug了....拜拜!!
Demo在这------------------------->点我下载