读取手机中的联系人信息(android.provider.ContactsContract)
本篇开始讲如何从Android中得到本机联系人的信息。
由于Android较快的版本升级,部分API已经发生了变化。本篇探究的通过ContentProvider机制获取联系人的API从Android2.0开始做了很大调整,原来的android.provider.Contacts类及其下相关类由android.provider.ContactsContract代替。原类体系标记为Deprecated(废弃),因为兼容的原因目前还存在,但不保证以后的更新版本中完全丢弃。
所以本文先从Android2.1以上平台的联系人读取开始说起,下面给出代码在Android2.1/2.2中运行的效果图,

首先,创建类ViewContacts继承ListActivity,并设为为应用的开始Activity。
ViewContacts.java 代码:
- package jtapp.contacts;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import android.app.ListActivity;
- import android.database.Cursor;
- import android.os.Bundle;
- import android.provider.ContactsContract;
- import android.widget.SimpleAdapter;
- public class ViewContacts extends ListActivity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- List<HashMap<String, String>> items = fillMaps();
- SimpleAdapter adapter = new SimpleAdapter(
- this,items,R.layout.list_item,
- new String[]{"name","key"},
- new int[]{R.id.item,R.id.item2});
- this.setListAdapter(adapter);
- }
- private List<HashMap<String, String>> fillMaps() {
- List<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
- Cursor cur = null;
- try {
- // Query using ContentResolver.query or Activity.managedQuery
- cur = getContentResolver().query(
- ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
- if (cur.moveToFirst()) {
- int idColumn = cur.getColumnIndex(
- ContactsContract.Contacts._ID);
- int displayNameColumn = cur.getColumnIndex(
- ContactsContract.Contacts.DISPLAY_NAME);
- // Iterate all users
- do {
- String contactId;
- String displayName;
- String phoneNumber = "";
- // Get the field values
- contactId = cur.getString(idColumn);
- displayName = cur.getString(displayNameColumn);
- // Get number of user's phoneNumbers
- int numberCount = cur.getInt(cur.getColumnIndex(
- ContactsContract.Contacts.HAS_PHONE_NUMBER));
- if (numberCount>0) {
- Cursor phones = getContentResolver().query(
- ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
- null,
- ContactsContract.CommonDataKinds.Phone.CONTACT_ID
- + " = " + contactId
- /*+ " and " + ContactsContract.CommonDataKinds.Phone.TYPE
- + "=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE*/,
- null, null);
- if (phones.moveToFirst()) {
- int numberColumn = phones.getColumnIndex(
- ContactsContract.CommonDataKinds.Phone.NUMBER);
- // Iterate all numbers
- do {
- phoneNumber += phones.getString(numberColumn) + ",";
- } while (phones.moveToNext());
- }
- }
- // Add values to items
- HashMap<String, String> i = new HashMap<String, String>();
- i.put("name", displayName);
- i.put("key", phoneNumber);
- items.add(i);
- } while (cur.moveToNext());
- } else {
- HashMap<String, String> i = new HashMap<String, String>();
- i.put("name", "Your Phone");
- i.put("key", "Have No Contacts.");
- items.add(i);
- }
- } finally {
- if (cur != null)
- cur.close();
- }
- return items;
- }
- }
复制代码
main.xml 代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="show your phone's contacts:"
- />
- <ListView android:id="@id/android:list"
- android:layout_width="fill_parent"
- android:layout_height="0dip"
- android:layout_weight="1"
- android:drawSelectorOnTop="false"
- />
- </LinearLayout>
复制代码
list_item.xml 代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TableRow android:id="@+id/TableRow01"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- <TextView android:id="@+id/item"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20px" />
- <TextView android:text=": "
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20px" />
- <TextView android:id="@+id/item2"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20px" />
- </TableRow>
- </LinearLayout>
复制代码
AndroidManifest.xml 增加uses权限READ_CONTACTS 代码:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="jtapp.contacts" android:versionCode="1" android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".ViewContacts" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
- </manifest>
复制代码
以上文件编写好后,应用就能够在Android2.1模拟器上正确运行了。
那么该app如果在android1.6上运行,会怎么样呢?1.6上并没有ContactsContract类体系,所以就会报错了。需要注意,ContactContract类是在API Level 5增加的,之前的Android版本并不支持。
在Android 1.6 (API Level 4)上,获取联系人的方法将fillMaps()实现为如下:
- private List<HashMap<String, String>> fillMaps() {
- List<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
- Cursor cur = null;
- try {
- // Form an array specifying which columns to return.
- String[] projection = new String[] {
- People._ID,
- People.NAME,
- People.NUMBER
- };
- // query using ContentResolver.query or Activity.managedQuery
- cur = getContentResolver().query(
- People.CONTENT_URI,projection, null,null, null);
- if (cur.moveToFirst()) {
- String name;
- String phoneNumber;
- int nameColumn = cur.getColumnIndex(People.NAME);
- int phoneColumn = cur.getColumnIndex(People.NUMBER);
- do {
- // Get the field values
- name = cur.getString(nameColumn);
- phoneNumber = cur.getString(phoneColumn);
- // Do something with the values.
- HashMap<String, String> i = new HashMap<String, String>();
- i.put("name", name);
- i.put("key", phoneNumber);
- items.add(i);
- } while (cur.moveToNext());
- } else {
- HashMap<String, String> i = new HashMap<String, String>();
- i.put("name", "Your Phone");
- i.put("key", "Have No Contacts.");
- items.add(i);
- }
- } finally {
- if (cur != null)
- cur.close();
- }
- return items;
- }
复制代码
那么就能在1.6上运行了,效果截图如下:

联系人API,在Android2.0后产生变化,如果使用如上1.6版本的调用,你会发现在2.1下姓名有了,但电话号码不显示了。仔细观察可以发现,People.CONTENT_URI等调用在2.0以上的sdk中都标记了Deprecated。这一点,对于编写希望能够同时兼容1.6与2.x版本的应用造成了困难。那么,如果应用涉及到联系人的读取,非得要编写多个版本的apk了吗? 其实,我们可以使用判断当前系统API Level的方法编写两套代码备用,这个就留给大家去实践了。
获得系统API level方法:
- int version = android.provider.Settings.System.getInt(context
- .getContentResolver(),
- android.provider.Settings.System.SYS_PROP_SETTING_VERSION,
- 3);
复制代码
读取手机中的联系人信息(android.provider.ContactsContract)的更多相关文章
- 在手机中预置联系人/Service Number
代码分为两部分: Part One 将预置的联系人插入到数据库中: Part Two 保证预置联系人仅仅读,无法被编辑删除(在三个地方屏蔽对预置联系人进行编辑处理:联系人详情界面.联系人多选界面.新建 ...
- Android API之android.provider.ContactsContract
android.provider.ContactsContract ContactsContract是联系人provider和app的contract.定义了已支持的URL和column.取代了之前的 ...
- Android API之android.provider.ContactsContract.Contacts
android.provider.ContactsContract.Contacts 对应contacts数据表.RawContacts的一个聚合(aggregate)代表同一个人.每个人在数据表co ...
- Android API之android.provider.ContactsContract.RawContacts
android.provider.ContactsContract.RawContacts Constants for the raw contacts table, which contains o ...
- Android API之android.provider.ContactsContract.Data
android.provider.ContactsContract.Data Constants for the data table, which contains data points tied ...
- Android 手机卫士--获取联系人信息并显示与回显
前面的文章已经实现相关的布局,本文接着进行相关的功能实现 本文地址:http://www.cnblogs.com/wuyudong/p/5951794.html,转载请注明出处. 读取系统联系人 当点 ...
- 读取iPhone中的通讯录信息
添加AddressBook这个包:然后#import <AddressBook/AddressBook.h> //取得本地通信录名柄 ABAddressBookRef addressBoo ...
- 【转】Revit二次开发——读取cad中的文字信息
Revit读取cad的文字信息需要借助Teigha的开源dll,在程序中添加下图中红色框的dll文件的引用,其他的dll文件全部放在同一个文件夹中即可,运行的时候,会自动把这些dll文件全部复制到bi ...
- IOS 获取系统通讯录中的联系人信息
- (IBAction)getAllContactFromSystem { ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, NUL ...
随机推荐
- Python os.fchdir() 方法
概述 os.fchdir() 方法通过文件描述符改变当前工作目录.高佣联盟 www.cgewang.com Unix, Windows 上可用. 语法 fchdir()方法语法格式如下: os.fch ...
- PHP imagecolorclosesthwb - 取得与指定的颜色最接近的色度的黑白色的索引
imagecolorclosesthwb — 取得与指定的颜色最接近的色度的黑白色的索引.高佣联盟 www.cgewang.com 语法 int imagecolorclosesthwb (s res ...
- luogu P6087 [JSOI2015]送礼物 二分 单调队列 决策单调性
LINK:送礼物 原本想了一个 \(nlog^2\)的做法 然后由于线段树常数过大 T到30. 以为这道题卡\(log^2\)没想到真的有神仙写\(log^2\)的过了 是我常数大了 抱歉. 能过的\ ...
- BSOJ 5445 -- 【2018雅礼】树 prufer序列 dp
BSOJ在哪我也不知道 没有链接. 对于有标号无根树的统计和有度数限制 一般采用prufer序列. 根据prufer序列 容易知道 某个点的出现次数+1为当前点的度数. 对于这道题 考虑设f[i][j ...
- Spring事务专题(三)事务的基本概念,Mysql事务处理原理
前言 本专题大纲: 我重新整理了大纲,思考了很久,决定单独将MySQL的事务实现原理跟Spring中的事务示例分为两篇文章,因为二者毕竟没有什么实际关系,实际上如果你对MySQL的事务原理不感兴趣也可 ...
- 利用python进行数据分析PDF高清完整版免费下载|百度云盘|Python基础教程免费电子书
点击获取提取码:hi2j 内容简介 [名人推荐] "科学计算和数据分析社区已经等待这本书很多年了:大量具体的实践建议,以及大量综合应用方法.本书在未来几年里肯定会成为Python领域中技术计 ...
- JavaWeb项目的部署以及远程调试
Linux环境下软件的安装 Linux环境下的程序的安装.更新.卸载和查看. rpm 命令:相当于windows程序的添加/卸载程序,进程程序的安装,查看,卸载. 本地程序安装:rpm -ivh 程序 ...
- UI自动化填写问卷(selenium)+定时任务(懒人必备)
1.自动填报 UI自动化 selenium 开发程序动机:天天有人催着填写问卷,弄的头大.主要还是懒的每天一个个去填写内容. 开发总时长:2个小时:学习+开发+修改 遇到的小问题: 在自动化填写地图的 ...
- .net+uniapp 前后端数据交互相关问题记录
uniapp 提交form表单 @submit EventHandle 携带 form 中的数据触发 submit 事件,event.detail = {value : {'name': 'value ...
- URLDecoder异常解决方法
URLDecoder对参数进行解码时候,代码如: URLDecoder.decode(param,"utf-8"); 有时候会出现类似如下的错误: URLDecoder异常Ille ...