public class ContactHelper { public ContactHelper() { }
// 전화번호에서 ContactID 획득 private static long getContactIDFromNumber(ContentResolver contactHelper, String number) { long rawContactID = -1; number = number.replaceAll("[^0-9]", ""); // 숫자만 추출 Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = { PhoneLookup._ID }; Cursor cursor = null;
try { cursor = contactHelper.query(contactUri, projection, null, null, null); if (cursor.moveToFirst()) { rawContactID = cursor.getLong(cursor.getColumnIndex(PhoneLookup._ID)); } } catch (Exception e) { e.printStackTrace(); } finally { cursor.close(); } return rawContactID; }
// 전화번호 기준으로 연락처 삭제 public static void deleteContactFromNumber(ContentResolver contactHelper, String number) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); String[] WhereArgs = new String[] { String.valueOf(getContactIDFromNumber(contactHelper, number)) };
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI) .withSelection(RawContacts.CONTACT_ID + "=?", WhereArgs).build()); try { contactHelper.applyBatch(ContactsContract.AUTHORITY, ops); } catch (RemoteException e) { e.printStackTrace(); } catch (OperationApplicationException e) { e.printStackTrace(); } }
// 성명 + 전화번호 기준으로 연락처 삭제 (동명이인 고려) public static void deleteContactFromNameAndNumber(ContentResolver contactHelper, String display_name, String number) { // 로직 개념 : 이름 검색 --> 전화번호 --> ContactID 를 구하는 순서로 로직 구현 number = number.replaceAll("[^0-9]", ""); // 숫자만 추출 Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String[] projection = { ContactsContract.CommonDataKinds.Phone.NUMBER }; String where = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = '" + display_name + "'"; String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"; Cursor cursor = null; try { if (display_name != null && !display_name.equals("") && number != null && !number.equals("")) { cursor = contactHelper.query(contactUri, projection, where, null, sortOrder); if (cursor.moveToFirst()) { do { String phoneNO = cursor.getString(cursor.getColumnIndex(Phone.NUMBER)); phoneNO = phoneNO.replaceAll("[^0-9]", ""); // 숫자만 추출 if (number.equals(phoneNO)) { // 이름으로 찾은 전화번호와 입력된 전화번호가 서로 같으면 해당 연락처 삭제 처리 deleteContactFromNumber(contactHelper, phoneNO); } } while (cursor.moveToNext()); } } } catch (Exception e) { e.printStackTrace(); } }
} |