android 加载本地联系人实现方法

首先先建布局文件,界面很简单,就是一个搜索框和下面的联系人列表:
 


代码如下:

<?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" />

(0)

相关推荐

  • Android仿微信联系人按字母排序

    App只要涉及到联系人的界面,几乎都是按照字母排序以及导航栏的方式.既然这个需求这么火,于是开始学习相关内容,此篇文章是我通过参考网上资料独立编写和总结的,希望多多少少对大家有所帮助,写的不好,还请各位朋友指教. 效果图如下: 实现这个效果,需要三个知识点 : 1:将字符串 进行拼音分类 2:ExpandableListView 二级扩展列表 3:右边字母分类View 我们先一个一个来了解解决方案,再上代码. 实现字母分类: 字母分类又分为三个小要点:一个是将中文转化为拼音,一个是实现按照字母的

  • 使用adb命令向Android模拟器中导入通讯录联系人的方法

    本文实例讲述了使用adb命令向Android模拟器中导入通讯录联系人的方法.分享给大家供大家参考.具体实现方法如下: 使用adb提供的命令, 可以非常方便地从PC中将通讯录导入android模拟器中. 首先要先准备好固定格式的contacts.vcf文件, 该文件即android中的通讯录存储文件. 格式如下: 复制代码 代码如下: BEGIN:VCARD  VERSION:3.0  N:15200000000;;;;  TEL;TYPE=cell:15200000000  END:VCARD 

  • Android获取手机通讯录、sim卡联系人及调用拨号界面方法

    android获取手机通讯录联系人信息 复制代码 代码如下: private void getPhoneContacts() {        ContentResolver resolver = this.getContentResolver();                // 获取手机联系人       Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,                  new String[] { Phone

  • Android编程实现通讯录中联系人的读取,查询,添加功能示例

    本文实例讲述了Android编程实现通讯录中联系人的读取,查询,添加功能.分享给大家供大家参考,具体如下: 先加二个读和写权限: <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> 具体代码: package com.ebo

  • Android根据电话号码获得联系人头像实例代码

    在日常Android手机的使用过程中,根据电话号码获得联系人头像,是经常会碰到的问题.本文即以实例形式讲述了Android根据电话号码获得联系人头像是实现代码.分享给大家供大家参考之用.具体方法如下: 首先,通过ContentProvider,可以访问Android中的联系人等数据.常用的Uri有: 联系人信息Uri:content://com.android.contacts/contacts 联系人电话Uri:content://com.android.contacts/data/phone

  • Android手机联系人快速索引(手机通讯录)

    最近需要实现一个手机通讯录的快速索引功能.根据姓名首字母快速索引功能.下面是一个手机联系人快速索引的效果,总体来说代码不算难,拼音转换的地方略有复杂.下面上源码:源码中有注释. 下面是效果图: MainActivity: import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.app.Activity; import android.os.Bundle; imp

  • Android系统联系人全特效实现(上)分组导航和挤压动画(附源码)

    记得在我刚接触Android的时候对系统联系人中的特效很感兴趣,它会根据手机中联系人姓氏的首字母进行分组,并在界面的最顶端始终显示一个当前的分组.如下图所示:  最让我感兴趣的是,当后一个分组和前一个分组相碰时,会产生一个上顶的挤压动画.那个时候我思考了各种方法想去实现这种特效,可是限于功夫不到家,都未能成功.如今两年多过去了,自己也成长了很多,再回头去想想这个功能,突然发现已经有了思路,于是立刻记录下来与大家分享. 首先讲一下需要提前了解的知识点,这里我们最需要用到的就是SectionInde

  • Android保存联系人到通讯录的方法

    上一篇文章讲了如何获取所有联系人,这篇文章就讲下怎么保存联系人数据到本机通讯录.这里我就假设你已经拿到了要保存的联系人数据. 因为是一个工具类,所以我这里就只给一个方法了,也是很简单,但是写的没有读取联系人的数据那么多,要保存更多其实看下如何读取的就会了. 直接上源码: /** * 添加联系人到本机 * * @param context * @param contact * @return */ public static boolean addContact(Context context,

  • Android之联系人PinnedHeaderListView使用介绍

    Android联系人中的ListView是做得比较独特的,但是源码写得比较复制,当我们想使用他的时候再从源码中提取,实属不易啊,而且容易出错,这几天,我把他提取出来了,写成一个简单的例子,一是给自己备忘,而是跟大家分享一下,好了,先来看看效果图:  首先是封装好的带头部的PinnedHeaderListView: 复制代码 代码如下: public class PinnedHeaderListView extends ListView { public interface PinnedHeade

  • android 加载本地联系人实现方法

    首先先建布局文件,界面很简单,就是一个搜索框和下面的联系人列表:   复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layou

  • Android开发实现webview中img标签加载本地图片的方法

    本文实例讲述了Android开发实现webview中img标签加载本地图片的方法.分享给大家供大家参考,具体如下: 在网上查了很多教程,感觉很麻烦,各种方法,最后实践很简单,主要是两步: WebSettings webSettings=webView.getSettings(); //允许webview对文件的操作 webSettings.setAllowUniversalAccessFromFileURLs(true); webSettings.setAllowFileAccess(true)

  • vue中v-for加载本地静态图片方法

    vue-cli 项目中本地图片放在assets目录下(原因vue-cli最开始的vue图片就在里面,就把所有图片放在里面了): 之后v-for 动态加载图片路径就遇到了问题 源码: <ul> <li v-for="(item,index) in teamInfo" @click="trastFun(item)"> <div><img v-bind:src="item.imageurl"/></

  • django加载本地html的方法

    django加载本地html from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render,render_to_response # Create your views here. def hello(request): return render_to_response("hello.html") 传递数据到html中 pytho

  • 详解Android GLide图片加载常用几种方法

    目录 缓存浅析 GLide图片加载方法 图片加载周期 图片格式(Bitmap,Gif) 缓存 集成网络框架 权限 占位符 淡入效果 变换 启动页/广告页 banner 固定宽高 圆角 圆形 总结 缓存浅析 为啥要做缓存? android默认给每个应用只分配16M的内存,所以如果加载过多的图片,为了 防止内存溢出 ,应该将图片缓存起来. 图片的三级缓存分别是: 1.内存缓存 2.本地缓存 3.网络缓存 其中,内存缓存应优先加载,它速度最快:本地缓存次优先加载,它速度也快:网络缓存不应该优先加载,它

  • Android编程实现加载等待ProgressDialog的方法

    本文实例讲述了Android编程实现加载等待ProgressDialog的方法.分享给大家供大家参考,具体如下: 显示progressDialog的类: import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; public cl

  • ios App加载本地HTML网页,点击网页链接跳转到app页面的方法

    一.如何在APP里加载本地html文件内容: 首先准备一个html文件,比如内容如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <tit

  • 浅析Android加载字体包及封装的方法

    TextView加载字体包 在 Android 中,若需要使得某个TextView加载字体包,使用以下方式即可: Typeface typeFace =Typeface.createFromAsset(getAssets(),"fonts/Bold.otf"); textView.setTypeface(typeFace); 至于字体包的位置: 通过以上方法,可以使得一个TextView加载某种字体包,但是,还有这种需求: 部分TextView加载字体包 每个TextView加载的字体

  • vue动态加载本地图片的处理方法

    发现问题 今天遇到一个在vue文件中引入本地图片的问题,于是有了这篇文章. 通常,我们的一个img标签在html中是这么写的: <img src="../images/demo.png"> 这种写法只能引用相对路径下的图片.不能使用绝对路径.使用绝对路径的话,这类资源将会直接被拷贝,而不会经过 webpack 的处理. 如果src是变量的话,我们一般会在data中定一个变量src进行动态绑定. <img :src="src"> //data中

  • Android 加载大图及多图避免程序出现OOM(OutOfMemory)异常

    Android 加载大图及多图避免程序出现OOM(OutOfMemory)异常 1.高效加载大图片 我们在编写Android程序的时候经常要用到许多图片,不同图片总是会有不同的形状.不同的大小,但在大多数情况下,这些图片都会大于我们程序所需要的大小.比如说系统图片库里展示的图片大都是用手机摄像头拍出来的,这些图片的分辨率会比我们手机屏幕的分辨率高得多.大家应该知道,我们编写的应用程序都是有一定内存限制的,程序占用了过高的内存就容易出现OOM(OutOfMemory)异常.我们可以通过下面的代码看

随机推荐