Android开发_读取联系人信息_读取通讯录号码

import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.database.Cursor;
import android.widget.TextView;
import android.content.ContentResolver;

publicclass Activity01 extends Activity
{
    publicvoid onCreate(Bundle savedInstanceState) 
    {
        TextView tv =new TextView(this);
        String string ="";
        super.onCreate(savedInstanceState);
        
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        //向下移动光标
while(cursor.moveToNext())
        {
            //取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            String contact = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+ ContactId, null, null);
            
            while(phone.moveToNext())
            {
                String PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                string += (contact +":"+ PhoneNumber +"\n");
            }
        }
        cursor.close();
        
        //设置TextView显示的内容
        tv.setText(string);
        //显示到屏幕
        setContentView(tv);
    }
}

最后记得在AndroidManifest.xml声明读取联系人的API:

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

如果我们只想获取手机号如何操作呢?

Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+ ContactId, null, null);

把以上语句改为:

Cursor phone = cr.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);
ContactsContract.CommonDataKinds.Phone.TYPE 表示联系人电话的类型,主要对应如下:
TYPE_MOBILE : 手机号码
TYPE_HOME  : 住宅电话
TYPE_WORK : 公司电话

posted @ 2012-05-22 16:45  ConquerMobileApp  阅读(3814)  评论(0编辑  收藏  举报