Android

안드로이드 주소록 연락처 가져오기

Machine_웅 2021. 10. 8. 11:41
728x90
반응형

1. 권한

 String [] per = {
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };

2. 소스코드

    public void getPhoneBook(){
        String SORT_ORDER = ContactsContract.Data.MIMETYPE;

        ArrayList<PhoneModel> tmpList = new ArrayList<>();

        Cursor cursor = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                null,
                null,
                SORT_ORDER
        );

        while (cursor.moveToNext()){
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String tempNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            String match = "[^0-9]";
            String number = tempNumber.replaceAll(match,"");
            Log.d("Woongs","name : "+name+"number : "+number);

            PhoneModel tmp = new PhoneModel(name,number);
            tmpList.add(tmp);
        }
        cursor.close();
        List data = deduplication(tmpList,PhoneModel::getNumber);
    }

    /**
     * @param list 중복이 있는 리스트
     * @param key 중복 여부를 판단하는  키값
     * @param <T> 제네릭 타입
     * @return List
     */
    public <T> List<T> deduplication(ArrayList<T> list, Function<? super T,?> key){
        return list.stream().filter(deduplication(key)).collect(Collectors.toList());
    }

    public <T>Predicate<T> deduplication(Function<? super T,?> key){
        Set<Object> set = ConcurrentHashMap.newKeySet();
        return predicate ->set.add(key.apply(predicate));
    }
728x90
반응형