Android - 연락처 가져오기

http://blackroom.egloos.com/225754

몇 일전에 연락처 가져오기 기능이 필요하여 만든 샘플 코드.

실로 간단하다.

- 메인 Activity                      - 연락처 Activity
  1. 연락처 버튼 클릭 --------> 2. 연락처와 리스트에 뿌리기
  4. 연락처 정보 받음 <-------- 3. 연락처 선택. 

기능 구현을 위한 주요 요소를 살펴보면 
  1. AndroidManifest.xml: 당연히 연락처를 읽어 드리기 권한이 필요하다.(읽는 것만 가능, 쓰기 위해서는 따로 쓰기 권한이 필요)
      - <uses-permission android:name="android.permission.READ_CONTACTS" />

  2. 연락처 쿼리 후 가져오기 

private ArrayList<Contact> getContactList() {

Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID, // 연락처 ID -> 사진 정보 가져오는데 사용
ContactsContract.CommonDataKinds.Phone.NUMBER,        // 연락처
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME }; // 연락처 이름.

String[] selectionArgs = null;

String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";

Cursor contactCursor = managedQuery(uri, projection, null,
selectionArgs, sortOrder);

ArrayList<Contact> contactlist = new ArrayList<Contact>();

if (contactCursor.moveToFirst()) {
do {
String phonenumber = contactCursor.getString(1).replaceAll("-",
"");
if (phonenumber.length() == 10) {
phonenumber = phonenumber.substring(0, 3) + "-"
+ phonenumber.substring(3, 6) + "-"
+ phonenumber.substring(6);
} else if (phonenumber.length() > 8) {
phonenumber = phonenumber.substring(0, 3) + "-"
+ phonenumber.substring(3, 7) + "-"
+ phonenumber.substring(7);
}

Contact acontact = new Contact();
acontact.setPhotoid(contactCursor.getLong(0));
acontact.setPhonenum(phonenumber);
acontact.setName(contactCursor.getString(2));

contactlist.add(acontact);
} while (contactCursor.moveToNext());
}

return contactlist;

}

전체 샘플 소스 -> ContactsSample.zip

참조:http://egloos.zum.com/blackroom/v/225754

+ Recent posts