Android中获取系统通讯录联系人并显示在EditText

        好多时候,我们都要使用选择联系人的操作,自己写的话 很麻烦,倒不如直接调用系统的通讯录,这样来的直接,来的方便

       下面我们来看需求:

 

需求:
一个EditText 点击button的时候转到系统通讯录,选中其中一个通讯录item返回当前界面且把
选中的联系人号码用户名显示在EditText 上。

image

 

image

image

 

直接上代码:

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    EditText text;
    String username,usernumber;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText)findViewById(R.id.number);
    }

    
   public void click(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) {
            ContentResolver reContentResolverol = getContentResolver();
             Uri contactData = data.getData();
             @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(contactData, null, null, null, null);
             cursor.moveToFirst();
             username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._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));
                 text.setText(usernumber+" ("+username+")");
             }

         }
    }
}

 

需要添加权限:

     <uses-permission android:name="android.permission.READ_CONTACTS" /> 
     <uses-permission android:name="android.permission.WRITE_CONTACTS" />

posted @ 2013-01-02 13:54  Andye  阅读(18581)  评论(4编辑  收藏  举报