转载注明出处:http://blog.csdn.net/u011368551/article/details/39896477
第一步:在配置文件里加入权限,因为是要读取联系人的。
- <uses-permission android:name="android.permission.READ_CONTACTS"/>
第二步:layout文件,注意在Button 上已经添加点击事件。
- <?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:orientation="vertical" >
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/mobileTel"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="submit"
- android:onClick="getTelClick"
- />
- </LinearLayout>
第三步:。
- package com.example.test;
- import android.net.Uri;
- import android.os.Bundle;
- import android.provider.ContactsContract;
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.Intent;
- import android.database.Cursor;
- import android.view.View;
- import android.widget.EditText;
- public class MainActivity extends Activity {
- // 声明文本框
- private EditText et_mobile;
- // 声明姓名,电话
- private String username, usernumber;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 根据Id获得文本框
- et_mobile = (EditText) this.findViewById(R.id.mobileTel);
- }
- public void getTelClick(View v) {
- startActivityForResult(new Intent(Intent.ACTION_PICK,
- ContactsContract.Contacts.CONTENT_URI), 0);
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (resultCode == Activity.RESULT_OK) {
- // ContentProvider展示数据类似一个单个数据库表
- // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
- ContentResolver reContentResolverol = getContentResolver();
- // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
- Uri contactData = data.getData();
- // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
- Cursor cursor = managedQuery(contactData, null, null, null, null);
- cursor.moveToFirst();
- // 获得DATA表中的名字
- username = cursor.getString(cursor
- .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
- // 条件为联系人ID
- String contactId = cursor.getString(cursor
- .getColumnIndex(ContactsContract.Contacts._ID));
- // 获得DATA表中的电话号码,条件为联系人ID,因为手机号码可能会有多个
- Cursor phone = reContentResolverol.query(
- ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
- ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
- + contactId, null, null);
- while (phone.moveToNext()) {
- usernumber = phone
- .getString(phone
- .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
- et_mobile.setText(usernumber + " (" + username + ")");
- }
- }
- }
- }
注释已经很清楚了,不懂的欢迎留言讨论,最后附图一张。