使用ContentProvider管理联系人

Android系统提供了Contacts应用程序来管理联系人,而且还为联系人管理提供了ContentProvider。

下面通过一个实例来演示,实现查询系统所有联系人的姓名及其详细信息和添加联系人,代码如下:

读取联系人的Activity:

[java][/java] view plaincopy

  1. package com.lovo.activity;
  2. import java.util.ArrayList;
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.database.Cursor;
  6. import android.os.Bundle;
  7. import android.provider.ContactsContract;
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10. import android.view.ViewGroup;
  11. import android.widget.BaseExpandableListAdapter;
  12. import android.widget.Button;
  13. import android.widget.ExpandableListView;
  14. import android.widget.TextView;
  15. import com.lovo.lesson15.R;
  16. /**
  17.  * 读取联系人的Activity
  18.  *
  19.  * @author Administrator
  20.  *
  21.  */
  22. public class ReadContactActivity extends Activity {
  23.     /**
  24.      * 保存联系人的姓名集合
  25.      */
  26.     private ArrayList<String> namesList = new ArrayList<String>();
  27.     /**
  28.      * 保存联系人详细信息的集合
  29.      */
  30.     private ArrayList<ArrayList<String>> infoList = new ArrayList<ArrayList<String>>();
  31.     private ExpandableListView elv;
  32.     private Button addContactBtn;
  33.     private BaseExpandableListAdapter adapter;
  34.     /**
  35.      * 初始化集合
  36.      */
  37.     public void initData() {
  38.         namesList.clear();
  39.         infoList.clear();
  40.         // 查询联系人的基本信息
  41.         // 系统联系人的URI:ContactsContract.Contacts.CONTENT_URI
  42.         Cursor cursor = getContentResolver().query(
  43.                 ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
  44.         while (cursor.moveToNext()) {
  45.             // 获取联系人的ID
  46.             int contactId = cursor.getInt(cursor
  47.                     .getColumnIndex(ContactsContract.Contacts._ID));
  48.             // 获取联系人的姓名
  49.             String name = cursor.getString(cursor
  50.                     .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
  51.             namesList.add(name);
  52.             // 存放每个联系人里面详细信息的集合,里面有电话号码和email
  53.             ArrayList detailList = new ArrayList();
  54.             // 查找电话号码
  55.             // 获取系统联系人电话号码的URI:ContactsContract.CommonDataKinds.Phone.CONTENT_URI
  56.             // 电话号码数据中对应联系人的ID列名:ContactsContract.CommonDataKinds.Phone.CONTACT_ID
  57.             Cursor phoneCursor = getContentResolver().query(
  58.                     ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
  59.                     null,
  60.                     ContactsContract.CommonDataKinds.Phone.CONTACT_ID + “=”
  61.                             + contactId, null, null);
  62.             while (phoneCursor.moveToNext()) {
  63.                 String phoneNumber = phoneCursor
  64.                         .getString(phoneCursor
  65.                                 .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
  66.                 detailList.add(phoneNumber);
  67.             }
  68.             phoneCursor.close();
  69.             // 查找联系人的email
  70.             // 获取联系人email的URI:ContactsContract.CommonDataKinds.Email.CONTENT_URI
  71.             // email数据中对应联系人的ID列名:ContactsContract.CommonDataKinds.Email.CONTACT_ID
  72.             Cursor emailCursor = getContentResolver().query(
  73.                     ContactsContract.CommonDataKinds.Email.CONTENT_URI,
  74.                     null,
  75.                     ContactsContract.CommonDataKinds.Email.CONTACT_ID + “=”
  76.                             + contactId, null, null);
  77.             while (emailCursor.moveToNext()) {
  78.                 String email = emailCursor
  79.                         .getString(emailCursor
  80.                                 .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
  81.                 detailList.add(email);
  82.             }
  83.             emailCursor.close();
  84.             infoList.add(detailList);
  85.         }
  86.         cursor.close();
  87.     }
  88.     @Override
  89.     protected void onCreate(Bundle savedInstanceState) {
  90.         super.onCreate(savedInstanceState);
  91.         setContentView(R.layout.read_contact_main);
  92.         initData();
  93.         elv = (ExpandableListView) findViewById(R.id.read_contact_main_elv);
  94.         addContactBtn = (Button) findViewById(R.id.read_contact_main_btn_add);
  95.         addContactBtn.setOnClickListener(new OnClickListener() {
  96.             @Override
  97.             public void onClick(View v) {
  98.                 Intent intent = new Intent(ReadContactActivity.this,
  99.                         SaveContactActivity.class);
  100.                 startActivity(intent);
  101.             }
  102.         });
  103.         adapter = new BaseExpandableListAdapter() {
  104.             @Override
  105.             public boolean isChildSelectable(int groupPosition,
  106.                     int childPosition) {
  107.                 return true;
  108.             }
  109.             @Override
  110.             public boolean hasStableIds() {
  111.                 return true;
  112.             }
  113.             @Override
  114.             public View getGroupView(int groupPosition, boolean isExpanded,
  115.                     View convertView, ViewGroup parent) {
  116.                 TextView tv = new TextView(ReadContactActivity.this);
  117.                 tv.setText(namesList.get(groupPosition));
  118.                 tv.setPadding(50, 10, 10, 10);
  119.                 return tv;
  120.             }
  121.             @Override
  122.             public long getGroupId(int groupPosition) {
  123.                 return groupPosition;
  124.             }
  125.             @Override
  126.             public int getGroupCount() {
  127.                 return namesList.size();
  128.             }
  129.             @Override
  130.             public Object getGroup(int groupPosition) {
  131.                 return namesList.get(groupPosition);
  132.             }
  133.             @Override
  134.             public int getChildrenCount(int groupPosition) {
  135.                 return infoList.get(groupPosition).size();
  136.             }
  137.             @Override
  138.             public View getChildView(int groupPosition, int childPosition,
  139.                     boolean isLastChild, View convertView, ViewGroup parent) {
  140.                 TextView tv = new TextView(ReadContactActivity.this);
  141.                 tv.setText(infoList.get(groupPosition).get(childPosition));
  142.                 tv.setPadding(10, 10, 10, 10);
  143.                 return tv;
  144.             }
  145.             @Override
  146.             public long getChildId(int groupPosition, int childPosition) {
  147.                 return childPosition;
  148.             }
  149.             @Override
  150.             public Object getChild(int groupPosition, int childPosition) {
  151.                 return infoList.get(groupPosition).get(childPosition);
  152.             }
  153.         };
  154.         elv.setAdapter(adapter);
  155.     }
  156.     // 添加联系人完成后回调此方法,更新adapter数据
  157.     @Override
  158.     protected void onResume() {
  159.         super.onResume();
  160.         initData();
  161.         adapter.notifyDataSetChanged();
  162.     }
  163. }

读取联系人的布局XML:

[html][/html] view plaincopy

  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
  3.     android:layout_width=”match_parent”
  4.     android:layout_height=”match_parent”
  5.     android:orientation=”vertical” >
  6.     <Button
  7.         android:id=”@+id/read_contact_main_btn_add”
  8.         android:layout_width=”wrap_content”
  9.         android:layout_height=”wrap_content”
  10.         android:text=”增加” />
  11.     <ExpandableListView
  12.         android:id=”@+id/read_contact_main_elv”
  13.         android:layout_width=”match_parent”
  14.         android:layout_height=”wrap_content” >
  15.     </ExpandableListView>
  16. </LinearLayout>

增加联系人的Activity:

[java][/java] view plaincopy

  1. package com.lovo.activity;
  2. import android.app.Activity;
  3. import android.content.ContentUris;
  4. import android.content.ContentValues;
  5. import android.net.Uri;
  6. import android.os.Bundle;
  7. import android.provider.ContactsContract;
  8. import android.provider.ContactsContract.CommonDataKinds.Email;
  9. import android.provider.ContactsContract.CommonDataKinds.Phone;
  10. import android.provider.ContactsContract.CommonDataKinds.StructuredName;
  11. import android.provider.ContactsContract.Data;
  12. import android.provider.ContactsContract.RawContacts;
  13. import android.view.View;
  14. import android.widget.EditText;
  15. import com.lovo.lesson15.R;
  16. public class SaveContactActivity extends Activity {
  17.     private EditText nameText;
  18.     private EditText phoneText;
  19.     private EditText emailText;
  20.     @Override
  21.     protected void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.add_contact_main);
  24.         nameText = (EditText) findViewById(R.id.add_contact_main_et_name);
  25.         phoneText = (EditText) findViewById(R.id.add_contact_main_et_phone);
  26.         emailText = (EditText) findViewById(R.id.add_contact_main_et_email);
  27.     }
  28.     public void click(View v) {
  29.         if (v.getId() == R.id.add_contact_main_btn_ok) {
  30.             ContentValues values = new ContentValues();
  31.             // 添加一条空数据并获取其ID,此ID为当前增加的联系人ID
  32.             Uri uri = getContentResolver().insert(RawContacts.CONTENT_URI,
  33.                     values);
  34.             // 使用工具类ContentUris来解析Uri中的ID
  35.             long contactId = ContentUris.parseId(uri);
  36.             // 添加联系人的姓名
  37.             if (nameText.getText() != null
  38.                     && !””.equals(nameText.getText().toString().trim())) {
  39.                 // 将ContentValues里面的所有内容清空
  40.                 values.clear();
  41.                 // 增加联系人ID
  42.                 values.put(Data.RAW_CONTACT_ID, contactId);
  43.                 // 指定要添加联系人姓名的MIME类型
  44.                 values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
  45.                 // 指定要添加联系人的姓名
  46.                 values.put(StructuredName.GIVEN_NAME, nameText.getText()
  47.                         .toString());
  48.                 // 添加联系人的姓名
  49.                 getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
  50.                         values);
  51.             }
  52.             // 添加联系人的电话
  53.             if (phoneText.getText() != null
  54.                     && !””.equals(phoneText.getText().toString().trim())) {
  55.                 // 将ContentValues里面的所有内容清空
  56.                 values.clear();
  57.                 // 增加联系人ID
  58.                 values.put(Data.RAW_CONTACT_ID, contactId);
  59.                 // 指定要添加联系人电话的MIME类型
  60.                 values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
  61.                 // 指定要添加的联系人电话的类型
  62.                 values.put(Phone.TYPE, Phone.TYPE_MOBILE);
  63.                 // 制定要添加联系人的电话
  64.                 values.put(Phone.NUMBER, phoneText.getText().toString());
  65.                 // 添加联系人的电话
  66.                 getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
  67.                         values);
  68.             }
  69.             // 添加联系人的email
  70.             if (emailText.getText() != null
  71.                     && !””.equals(emailText.getText().toString().trim())) {
  72.                 // 将ContentValues里面的所有内容清空
  73.                 values.clear();
  74.                 // 增加联系人ID
  75.                 values.put(Data.RAW_CONTACT_ID, contactId);
  76.                 // 指定要添加联系人email的MIME类型
  77.                 values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
  78.                 // 指定要添加的联系人email的类型
  79.                 values.put(Email.TYPE, Email.TYPE_HOME);
  80.                 // 指定要添加的联系人的email
  81.                 values.put(Email.DATA, emailText.getText().toString());
  82.                 // 添加联系人的email
  83.                 getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
  84.                         values);
  85.             }
  86.             finish();
  87.         }
  88.         if (v.getId() == R.id.add_contact_main_btn_back) {
  89.             finish();
  90.         }
  91.     }
  92. }

增加联系人的Activity:

[html][/html] view plaincopy

  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
  3.     android:layout_width=”match_parent”
  4.     android:layout_height=”match_parent”
  5.     android:orientation=”vertical” >
  6.     <TextView
  7.         android:layout_width=”wrap_content”
  8.         android:layout_height=”wrap_content”
  9.         android:text=”联系人的姓名” />
  10.     <EditText
  11.         android:id=”@+id/add_contact_main_et_name”
  12.         android:layout_width=”match_parent”
  13.         android:layout_height=”wrap_content”
  14.         android:ems=”10″ />
  15.     <TextView
  16.         android:layout_width=”wrap_content”
  17.         android:layout_height=”wrap_content”
  18.         android:text=”联系人的电话” />
  19.     <EditText
  20.         android:id=”@+id/add_contact_main_et_phone”
  21.         android:layout_width=”match_parent”
  22.         android:layout_height=”wrap_content”
  23.         android:ems=”10″ />
  24.     <TextView
  25.         android:layout_width=”wrap_content”
  26.         android:layout_height=”wrap_content”
  27.         android:text=”联系人的email” />
  28.     <EditText
  29.         android:id=”@+id/add_contact_main_et_email”
  30.         android:layout_width=”match_parent”
  31.         android:layout_height=”wrap_content”
  32.         android:ems=”10″ />
  33.     <LinearLayout
  34.         android:layout_width=”match_parent”
  35.         android:layout_height=”wrap_content”
  36.         android:gravity=”center_horizontal”
  37.         android:orientation=”horizontal” >
  38.         <Button
  39.             android:id=”@+id/add_contact_main_btn_ok”
  40.             android:layout_width=”wrap_content”
  41.             android:layout_height=”wrap_content”
  42.             android:onClick=”click”
  43.             android:text=”保存” />
  44.         <Button
  45.             android:id=”@+id/add_contact_main_btn_back”
  46.             android:layout_width=”wrap_content”
  47.             android:layout_height=”wrap_content”
  48.             android:layout_marginLeft=”20dp”
  49.             android:onClick=”click”
  50.             android:text=”返回” />
  51.     </LinearLayout>
  52. </LinearLayout>

要读取系统联系人,不要忘了加上如下权限:

[html][/html] view plaincopy

  1. <uses-permission android:name=”android.permission.READ_CONTACTS”/>
  2. <uses-permission android:name=”android.permission.WRITE_CONTACTS”/>

标签