Android2.0之後讀取聯繫人——ContactsContract

當我們將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();     
}     
cursor.close();
當然,還有得到email等操作!
先寫到這裏,更多關於Android2.0的內容,有待研究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章