Android中獲取通訊錄的方法

代碼如下:

public class AndroidDemoActivity extends Activity{

public void 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);
}

}

註意的是:這個獲取的時間有點長,所以這個過程最好放到子線程中執行!

發佈留言