Android 获取联系人列表 (转)

package brian.android.ContactList;

import android.app.ListActivity;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

/**
 *
 * data comes from a cursor.
 */
@SuppressWarnings("deprecation")
public class ContactList extends ListActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get a cursor with all people
        Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI ,null, null, null, null);
        startManagingCursor(c);

        ListAdapter adapter = new SimpleCursorAdapter(this,
                // Use a template that displays a text view
                android.R.layout.simple_list_item_1,
                // Give the cursor to the list adatper
                c,
                // Map the NAME column in the people database to...
                new String[] {PhoneLookup.DISPLAY_NAME} ,
                // The "text1" view defined in the XML template
                new int[] {android.R.id.text1});
        setListAdapter(adapter);
    }
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Andorid1.5及其以前的项目放到Android2.0上时,如果代码中有
import android.provider.Contacts;  
Eclipse会提示“建议不使用”,那是因为在Android2.0中,联系人api发生了变化,需要使用ContactsContract。
直接看下面一个最简单的例子,读取联系人的姓名和电话号码:
读取联系人的名字很简单,但是在读取电话号码时,就需要先去的联系人的ID,然后在通过ID去查找电话号码!一个联系人可能存在多个电话号码!

//得到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 name = cursor.getString(nameFieldColumnIndex);   
    string += (name);   
    // 取得联系人ID   
    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 strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));   
        string += (":" + strPhoneNumber);   
    }   
    string += "\n";   
    phone.close();   
posted @ 2011-08-17 12:03  木木小强  阅读(343)  评论(0编辑  收藏  举报