首先先建布局文件,界面很简单,就是一个搜索框和下面的联系人列表:
复制代码 代码如下:
<?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:background="#ffd3d7df"
android:orientation="vertical"
android:padding="0dip" >
<relativelayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginleft="3dip"
android:layout_marginright="3dip"
android:layout_margintop="3dip" >
<edittext
android:id="@+id/search_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_search_contacts"
android:paddingleft="32dip"
android:singleline="true"
android:textsize="16sp" />
<imageview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignleft="@id/search_view"
android:layout_centervertical="true"
android:layout_marginleft="3dip"
android:src="@drawable/contacts" />
</relativelayout>
<listview
android:id="@+id/contact_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginbottom="0dip"
android:layout_marginleft="0dip"
android:layout_marginright="0dip"
android:layout_margintop="0dip"
android:layout_weight="1.0"
android:cachecolorhint="#00000000"
android:divider="#00000000"
android:dividerheight="0.1px"
android:fadingedge="none"
android:footerdividersenabled="false"
android:listselector="@null"
android:paddingbottom="0dip"
android:paddingleft="0dip"
android:paddingright="0dip"
android:paddingtop="0dip" />
</linearlayout>
复制代码 代码如下:
<?xml version="1.0" encoding="utf-8"?>
<linearlayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:paddingtop="2dip"
android:paddingbottom="2dip"
android:background="@color/list_item_background">
<imageview
android:id="@+id/photo"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginleft="5dip"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:src="@drawable/default_avatar"
/>
<linearlayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginleft="5dip"
android:layout_weight="100">
<textview android:id="@+id/text1"
android:typeface="serif"
android:singleline="true"
style="@style/list_font_main_text" />
<linearlayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_margintop="3dip">
<textview android:id="@+id/text2"
android:typeface="serif"
android:singleline="true"
style="@style/list_font_detail_text" />
<textview android:id="@+id/text3"
android:ellipsize="marquee"
android:layout_marginleft="3dip"
android:marqueerepeatlimit="marquee_forever"
android:scrollhorizontally="true"
style="@style/list_font_detail_text" />
</linearlayout>
</linearlayout>
</linearlayout>
然后是点击事件:(点击后要把选择的联系人号码返回到输入框里)
复制代码 代码如下:
// 获取联系人按钮对象并绑定onclick单击事件
phonebutton = (button) findviewbyid(r.id.find_phone);
phonebutton.setonclicklistener(new onclicklistener() {
public void onclick(view v) {
// 从联系人选择号码,再通过onactivityresult()方法处理回调结果
intent intent = new intent(context, contactsactivity.class);
startactivityforresult(intent, request_code);
}
});
/**
* 选择联系人的回调处理函数
*/
@override
public void onactivityresult(int reqcode, int resultcode, intent data) {
super.onactivityresult(reqcode, resultcode, data);
if (resultcode == result_ok) {
switch (reqcode) {
case request_code:
string phone = data.getstringextra("phone");
phoneedittext.settext(phone);
break;
}
}
}
下面就是联系人界面的activity了:
复制代码 代码如下:
/**
* 显示用户手机上的联系人
*
* @author mr.z
* @time 2012-3-21
*
*/
public class contactsactivity extends activity {
private context ctx = contactsactivity.this;
private textview toptitletextview;
private listview listview = null;
list<hashmap<string, string>> contactslist = null;
private edittext contactssearchview;
private progressdialog progressdialog = null;
// 数据加载完成的消息
private final int message_succ_load = 0;
// 数据查询完成的消息
private final int message_succ_query = 1;
private handler handler = new handler() {
@override
public void handlemessage(message msg) {
super.handlemessage(msg);
switch (msg.what) {
case message_succ_load:
listview.setadapter(new contactsadapter(ctx));
progressdialog.dismiss();
break;
case message_succ_query:
listview.setadapter(new contactsadapter(ctx));
break;
}
}
};
protected void oncreate(bundle savedinstancestate) {
requestwindowfeature(window.feature_no_title);
getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen);
super.oncreate(savedinstancestate);
this.setcontentview(r.layout.contacts);
// 使用listview显示联系人
listview = (listview) findviewbyid(r.id.contact_list);
loadandsavecontacts();
// 绑定listview item的单击事件
listview.setonitemclicklistener(new onitemclicklistener() {
@suppresswarnings("unchecked")
public void onitemclick(adapterview<?> adapterview, view view, int position, long _id) {
hashmap<string, string> map = (hashmap<string, string>) adapterview.getitematposition(position);
string phone = map.get("phone");
// 对手机号码进行预处理(去掉号码前的+86、首尾空格、“-”号等)
phone = phone.replaceall("^(\\+86)", "");
phone = phone.replaceall("^(86)", "");
phone = phone.replaceall("-", "");
phone = phone.trim();
// 如果当前号码并不是手机号码
if (!saleutil.isvalidphonenumber(phone))
saleutil.createdialog(ctx, r.string.dialog_title_tip, getstring(r.string.alert_contacts_error_phone));
else {
intent intent = new intent();
intent.putextra("phone", phone);
setresult(result_ok, intent);
// 关闭当前窗口
finish();
}
}
});
contactssearchview = (edittext) findviewbyid(r.id.search_view);
contactssearchview.addtextchangedlistener(new textwatcher() {
public void aftertextchanged(editable s) {
}
public void beforetextchanged(charsequence s, int start, int count, int after) {
}
public void ontextchanged(charsequence s, int start, int before, int count) {
querycontacts(s.tostring());
}
});
}
/**
* 加载并存储联系人数据
*/
private void loadandsavecontacts() {
progressdialog = progressdialog.show(ctx, null, "正在加载联系人数据...");
new thread() {
@override
public void run() {
// 获取联系人数据
contactslist = findcontacts();
// 临时存储联系人数据
dbhelper.savecontacts(ctx, contactslist);
// 发送消息通知更新ui
handler.sendemptymessage(message_succ_load);
}
}.start();
}
/**
* 根据条件从本地临时库中获取联系人
*
* @param keyword 查询关键字
*/
private void querycontacts(final string keyword) {
new thread() {
@override
public void run() {
// 获取联系人数据
contactslist = dbhelper.findcontactsbycond(ctx, keyword);
// 发送消息通知更新ui
handler.sendemptymessage(message_succ_query);
}
}.start();
}
/**
* 获取手机联系人信息
*
* @return list<hashmap<string, string>>
*/
public list<hashmap<string, string>> findcontacts() {
list<hashmap<string, string>> list = new arraylist<hashmap<string, string>>();
// 查询联系人
cursor contactscursor = ctx.getcontentresolver().query(contactscontract.contacts.content_uri, null, null, null, phonelookup.display_name + " collate localized asc");
// 姓名的索引
int nameindex = 0;
// 联系人姓名
string name = null;
// 联系人头像id
string photoid = null;
// 联系人的id索引值
string contactsid = null;
// 查询联系人的电话号码
cursor phonecursor = null;
while (contactscursor.movetonext()) {
nameindex = contactscursor.getcolumnindex(phonelookup.display_name);
name = contactscursor.getstring(nameindex);
photoid = contactscursor.getstring(contactscursor.getcolumnindex(phonelookup.photo_id));
contactsid = contactscursor.getstring(contactscursor.getcolumnindex(contactscontract.contacts._id));
phonecursor = getcontentresolver().query(contactscontract.commondatakinds.phone.content_uri, null, contactscontract.commondatakinds.phone.contact_id + " = " + contactsid, null, null);
// 遍历联系人号码(一个人对应于多个电话号码)
while (phonecursor.movetonext()) {
hashmap<string, string> phonemap = new hashmap<string, string>();
// 添加联系人姓名
phonemap.put("name", name);
// 添加联系人头像
phonemap.put("photo", photoid);
// 添加电话号码
phonemap.put("phone", phonecursor.getstring(phonecursor.getcolumnindex(contactscontract.commondatakinds.phone.number)));
// 添加号码类型(住宅电话、手机号码、单位电话等)
phonemap.put("type", getstring(contactscontract.commondatakinds.phone.gettypelabelresource(phonecursor.getint(phonecursor.getcolumnindex(contactscontract.commondatakinds.phone.type)))));
list.add(phonemap);
}
phonecursor.close();
}
contactscursor.close();
return list;
}
/**
* 获取联系人头像
*
* @param context 上下文环境
* @param photoid 头像id
* @return bitmap
*/
public static bitmap getphoto(context context, string photoid) {
bitmap bitmap = bitmapfactory.decoderesource(context.getresources(), r.drawable.default_avatar);
if (photoid != null && "".equals(photoid)) {
string[] projection = new string[] { contactscontract.data.data15 };
string selection = "contactscontract.data._id = " + photoid;
cursor cur = context.getcontentresolver().query(contactscontract.data.content_uri, projection, selection, null, null);
if (cur != null) {
cur.movetofirst();
byte[] contacticon = null;
contacticon = cur.getblob(cur.getcolumnindex(contactscontract.data.data15));
if (contacticon != null) {
bitmap = bitmapfactory.decodebytearray(contacticon, 0, contacticon.length);
}
}
}
return bitmap;
}
/**
* 自定义联系人adapter
*/
class contactsadapter extends baseadapter {
private layoutinflater inflater = null;
public contactsadapter(context ctx) {
inflater = layoutinflater.from(ctx);
}
public int getcount() {
return contactslist.size();
}
public object getitem(int position) {
return contactslist.get(position);
}
public long getitemid(int position) {
return position;
}
public view getview(int position, view convertview, viewgroup parent) {
viewholder holder = null;
if (convertview == null) {
holder = new viewholder();
convertview = inflater.inflate(r.layout.contacts_listview_item, null);
holder.text1 = (textview) convertview.findviewbyid(r.id.text1);
holder.text2 = (textview) convertview.findviewbyid(r.id.text2);
holder.text3 = (textview) convertview.findviewbyid(r.id.text3);
convertview.settag(holder);
} else {
holder = (viewholder) convertview.gettag();
}
holder.text1.settext(contactslist.get(position).get("name"));
holder.text2.settext(contactslist.get(position).get("type"));
holder.text3.settext(contactslist.get(position).get("phone"));
return convertview;
}
public final class viewholder {
private textview text1;
private textview text2;
private textview text3;
}
}
}
查询方法语句:
复制代码 代码如下:
/**
* 根据条件查询联系人数据
*
* @param context 上下文环境
* @param keyword 查询关键字
* @return list<hashmap<string, string>>
*/
public static list<hashmap<string, string>> findcontactsbycond(context context, string keyword) {
list<hashmap<string, string>> list = new arraylist<hashmap<string, string>>();
sqlitedatabase db = dbhelper.getsqlitedb(context);
string sql = "select * from contacts where name like '" + keyword + "%' or name_alias like '" + keyword + "%' order by _id";
// 查询数据
cursor cursor = db.rawquery(sql, null);
while (cursor.movetonext()) {
hashmap<string, string> map = new hashmap<string, string>();
map.put("name", cursor.getstring(cursor.getcolumnindex("name")));
map.put("phone", cursor.getstring(cursor.getcolumnindex("phone")));
map.put("type", cursor.getstring(cursor.getcolumnindex("type")));
map.put("photo", cursor.getstring(cursor.getcolumnindex("photo")));
list.add(map);
}
cursor.close();
db.close();
return list;
}
/**
* 存储联系人信息
*
* @param context 上下文环境
* @param contactslist 联系人列表
*/
public static void savecontacts(context context, list<hashmap<string, string>> contactslist) {
sqlitedatabase db = dbhelper.getsqlitedb(context);
// 开启事务控制
db.begintransaction();
try {
// 先将联系人数据清空
db.execsql("drop table if exists contacts");
db.execsql("create table contacts(_id integer not null primary key autoincrement, name varchar(50), name_alias varchar(10), phone varchar(30), type varchar(50), photo varchar(50))");
string sql = null;
for (hashmap<string, string> contactsmap : contactslist) {
sql = string.format("insert into contacts(name,name_alias,phone,type,photo) values('%s','%s','%s','%s','%s')", contactsmap.get("name"), saleutil.getpinyinfirstalphabet(contactsmap.get("name")), contactsmap.get("phone"), contactsmap.get("type"), contactsmap.get("photo"));
db.execsql(sql);
}
// 设置事务标志为成功
db.settransactionsuccessful();
} finally {
// 结束事务
db.endtransaction();
db.close();
}
}
工具类:
复制代码 代码如下:
/**
* 判断客户手机号码是否符合规则
*
* @param userphone 客户手机号码
* @return true | false
*/
public static boolean isvalidphonenumber(string userphone) {
if (null == userphone || "".equals(userphone))
return false;
pattern p = pattern.compile("^0?1[0-9]{10}");
matcher m = p.matcher(userphone);
return m.matches();
}
/**
* 获取中文的拼音首字母
*
* @param chinese 中文
* @return 拼音首字母
*/
public static string getpinyinfirstalphabet(string chinese) {
string convert = "";
for (int j = 0; j < chinese.length(); j++) {
char word = chinese.charat(j);
string[] pinyinarray = pinyinhelper.tohanyupinyinstringarray(word);
if (pinyinarray != null) {
convert += pinyinarray[0].charat(0);
} else {
convert += word;
}
}
return convert;
}
最后加上权限就行了;
复制代码 代码如下:
<!-- 访问联系人的权限 -->
<uses-permission android:name="android.permission.read_contacts" />