下面是java 文件,主activity
package com.happyrxk.contact import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity { //定义出启动activity所用的请求码 final int PICK_CONTACT = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bn = (Button)findViewById(R.id.bn); bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); //这里设置intent的action与type,对应的就是android的电话本程序 intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("vnd.android.cursor.item/phone"); startActivityForResult(intent, PICK_CONTACT); } }); } //复写此方法,对应的是startActivityForResult @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case PICK_CONTACT: if(resultCode == Activity.RESULT_OK){ //取得返回的数据 Uri contactData = data.getData(); //根据返回的数据获得数据游标 Cursor cursor = getContentResolver().query(contactData, null, null, null, null); if(cursor.moveToFirst()){ String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); String phoneNumber = null; System.out.println(contactId+""); //获得id为contactId的游标并取得手机号码 TYPE_MOBILE指的手机号,还有TYPE_HOME等 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()){ phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); System.out.println("pnumber1 "+phoneNumber); } System.out.println("pnumber "+phoneNumber); //phones.close(); EditText show = (EditText)findViewById(R.id.show); show.setText(name); EditText phone = (EditText)findViewById(R.id.phone); phone.setText(phoneNumber); } cursor.close(); } break; default: break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
进行此操作需要在MainFest声明权限