[Android] 연락처 가져오기

Hyunho·2021년 6월 9일
0

연락처 가져오기

Permission

  • AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
  • Permission Check
private boolean permissionCheck() {

    // 권한 체크
    int readContactsPermissionCheck = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_CONTACTS);
    if (readContactsPermissionCheck == PackageManager.PERMISSION_DENIED) {
      // 권한 없음
      PermissionListener permissionlistener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {
          
          //your code ~~~~

        }

        @Override
        public void onPermissionDenied(List<String> deniedPermissions) {
        }
      };

      TedPermission.with(mActivity)
          .setPermissionListener(permissionlistener)
          .setRationaleMessage(R.string.common_auth)
          .setDeniedMessage(R.string.common_auth_denined)
          .setPermissions(Manifest.permission.READ_CONTACTS)
          .check();
    } else {
      //권한 있음
    	//your code ~~~~

      return true;
    }
    
    return false;
  }

주소를 받아오는 코드

  • getContacts
public ArrayList<String> getContactsString(Context context) {
    Timber.i("ADDR=============================================");
    ArrayList<String> datas = new ArrayList<>();
    ContentResolver resolver = context.getContentResolver();

    Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    String[] projection = {
//        ContactsContract.CommonDataKinds.Phone.CONTACT_ID // 인덱스 값, 중복될 수 있음 -- 한 사람 번호가 여러개인 경우
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
        , ContactsContract.CommonDataKinds.Phone.NUMBER};

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

    Cursor cursor = resolver.query(phoneUri, projection, null, null, sortOrder);

    if (cursor != null) {
      while (cursor.moveToNext()) {
//        int idIndex = cursor.getColumnIndex(projection[0]); // 이름을 넣어주면 그 칼럼을 가져와준다.
        int nameIndex = cursor.getColumnIndex(projection[0]);
        int numberIndex = cursor.getColumnIndex(projection[1]);
//        String id = cursor.getString(idIndex);
        String name = cursor.getString(nameIndex);
        String number = cursor.getString(numberIndex);

        Contact acontact = new Contact();
        acontact.setName(name);
        // 010 으로 통일하기 위해 +82 를 0으로 변환 하여 검사한다.
        if (number.contains("+82")) {
          acontact.setMember_phone(number.replace("+82", "0"));
        } else if (number.contains("+82-")) {
          acontact.setMember_phone(number.replace("+82-", "0"));
        } else {
          acontact.setMember_phone(number);
        }

        Timber.i("전화번호 =" + name + "," + number);

        String pattern = "^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}$"; // 전화번호
        String pattern2 = "^01(?:0|1|[6-9])(?:\\d{3}|\\d{4})\\d{4}$"; // 전화번호
        boolean patternCheck = Pattern.matches(pattern, acontact.getMember_phone());
        boolean patternCheck2 = Pattern.matches(pattern2, acontact.getMember_phone());
        if (patternCheck || patternCheck2) {
          acontact.setSelect(true);
          acontact.setMember_phone(Tools.phoneNumberFormatter(number));

          datas.add(acontact.getName()+":"+acontact.getMember_phone());
//          datas.add(acontact);
        }
      }
    }
    Timber.i("ADDR=====datas========================================"+datas);

    // 데이터 계열은 반드시 닫아줘야 한다.
    cursor.close();
    return datas;
  }
  • model
@Data
public class Contact implements Parcelable {

  private String member_phone;

  private String name;

  private boolean isSelect;

  public Contact() {
  }

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.member_phone);
    dest.writeString(this.name);
    dest.writeByte(this.isSelect ? (byte) 1 : (byte) 0);
  }

  protected Contact(Parcel in) {
    this.member_phone = in.readString();
    this.name = in.readString();
    this.isSelect = in.readByte() != 0;
  }

  public static final Creator<Contact> CREATOR = new Creator<Contact>() {
    @Override
    public Contact createFromParcel(Parcel source) {
      return new Contact(source);
    }

    @Override
    public Contact[] newArray(int size) {
      return new Contact[size];
    }
  };
}
profile
hyunho

0개의 댓글