![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLkV2Zu9mc39CX0xWdhZWZk9CX09Wbl9lcvRXakVGa49CXy9GdpRWZoh3LcRXZu5ibkN3Yuc2bsJmLjlGdhR3cvw1LcpDc0RHaiojIsJye.gif)
又是時隔好久才來寫文章,,,,,悲慘啊...最近在項目中有一個擷取手機聯系人并且可以通過短信來邀請他的這麼一個功能...今天來寫一篇擷取手機聯系人和檢索聯系人的文章....也檢視了網上很多的文章..感覺大部分都可以直接使用,是以決定自己試試...好了下面就開始吧...
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在這------------------------->點我下載下傳