【实用篇】获取Android通讯录中联系人信息

第一步,在Main.xml布局文件中声明一个Button控件,布局文件代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/query_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="点击查询联系人信息"/>

</LinearLayout>

第二步:在Activity中写入代码,读取联系人姓名和联系人电话信息,Activity代码如下:

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 指定页面布局
    setContentView(R.layout.main);
    // 声明一个Button按钮
    Button queryBtn = (Button) findViewById(R.id.query_btn);
    // 新建一个点击事件监听器对象
    OnClickListener ocl = new OnClickListener() {

      @Override
      public void onClick(View v) {
      ContentResolver contentResolver = getContentResolver();
      // 获得所有的联系人
      Cursor cursor = contentResolver.query(
      ContactsContract.Contacts.CONTENT_URI, null, null,
      null, null);
      // 循环遍历
      if (cursor.moveToFirst()) {

        int idColumn = cursor
        .getColumnIndex(ContactsContract.Contacts._ID);

        int displayNameColumn = cursor
        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

        do {
          // 获得联系人的ID号
          String contactId = cursor.getString(idColumn);
          // 获得联系人姓名
          String disPlayName = cursor
          .getString(displayNameColumn);
          // 查看该联系人有多少个电话号码。如果没有这返回值为0
          int phoneCount = cursor
          .getInt(cursor
          .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
          //在联系人数量不为空的情况下执行
          if (phoneCount > 0) {
            // 获得联系人的电话号码列表
            Cursor phonesCursor = getContentResolver()
            .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
            + " = " + contactId, null,
            null);
            if (phonesCursor.moveToFirst()) {
              do {
                // 遍历所有的电话号码
                String phoneNumber = phonesCursor
                .getString(phonesCursor
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                Toast.makeText(MainActivity.this,
                "联系人姓名:" + disPlayName+"\n联系人电话:" + phoneNumber,
                Toast.LENGTH_LONG).show();
               } while (phonesCursor.moveToNext());
              }
            }

          } while (cursor.moveToNext());
        }
      }
    };
    // 为按钮设置监听器
    queryBtn.setOnClickListener(ocl);
  }

}

第三步:在AndroidManifest.xml中添加<uses-permission android:name="android.permission.READ_CONTACTS" />来获得访问通讯录的权限,添加完成或即可运行程序获取联系人信息.

 

 

posted on 2013-08-23 10:50  土鳖程序员  阅读(4058)  评论(6编辑  收藏  举报

导航