앱을 기획에 따라 자신의 휴대폰에 저장한 주소록에 대한 정보를 가져올수있습니다!
저장된 휴대폰 번호 기준으로 작성해 보았습니다!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<EditText
android:id="@+id/phoneNumberInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="휴대폰 번호를 입력하세요"
android:inputType="phone"
android:layout_marginBottom="16dp" />
<Button
android:id="@+id/findContactButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="주소록 검색!" />
<TextView
android:id="@+id/contactName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="주소록 저장된 이름: "
android:textSize="18sp"
android:layout_marginTop="24dp" />
<TextView
android:id="@+id/contactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="주소록 저장된 번호: "
android:textSize="18sp"
android:layout_marginTop="8dp" />
<QuickContactBadge
android:id="@+id/quickContactBadge"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="24dp"
android:src="@drawable/no_profile"
android:contentDescription="Contact" />
</LinearLayout>
import android.content.ContentUris;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.EditText;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_READ_CONTACTS = 100;
private EditText phoneNumberInput;
private QuickContactBadge quickContactBadge;
private TextView contactName;
private TextView contactNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberInput = findViewById(R.id.phoneNumberInput);
quickContactBadge = findViewById(R.id.quickContactBadge);
contactName = findViewById(R.id.contactName);
contactNumber = findViewById(R.id.contactNumber);
Button findContactButton = findViewById(R.id.findContactButton);
// 권한 확인 및 요청
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.READ_CONTACTS},
REQUEST_READ_CONTACTS);
}
findContactButton.setOnClickListener(v -> {
String phoneNumber = phoneNumberInput.getText().toString();
if (!phoneNumber.isEmpty()) {
findAndDisplayContact(phoneNumber);
} else {
Toast.makeText(this, "전화번호를 입력하세요.", Toast.LENGTH_SHORT).show();
}
});
}
private void findAndDisplayContact(String phoneNumber) {
Uri contactUri = getContactUri(phoneNumber);
if (contactUri != null) {
quickContactBadge.assignContactUri(contactUri);
quickContactBadge.setVisibility(QuickContactBadge.VISIBLE);
// 연락처 이름과 번호 표시
getContactDetails(contactUri);
} else {
Toast.makeText(this, "연락처를 찾을 수 없습니다.", Toast.LENGTH_SHORT).show();
quickContactBadge.setVisibility(QuickContactBadge.INVISIBLE);
contactName.setText("주소록 저장된 이름: ");
contactNumber.setText("주소록 저장된 번호: ");
}
}
@Nullable
private Uri getContactUri(String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup._ID}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
long contactId = cursor.getLong(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
cursor.close();
return ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
}
if (cursor != null) {
cursor.close();
}
return null;
}
private void getContactDetails(Uri contactUri) {
// 연락처 URI에서 ID를 얻어옵니다.
String contactId = contactUri.getLastPathSegment();
// 연락처 ID로 전화번호, 이름, 프로필 사진 URI를 가져옵니다.
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_URI
},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactId},
null
);
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photoUri = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
contactName.setText("주소록 저장된 이름: " + name);
contactNumber.setText("주소록 저장된 번호: " + number);
// 프로필 사진이 있으면 QuickContactBadge에 설정하고, 없으면 기본 이미지를 설정합니다.
if (photoUri != null) {
quickContactBadge.setImageURI(Uri.parse(photoUri));
} else {
quickContactBadge.setImageResource(R.drawable.no_profile); // 기본 이미지 리소스 설정
}
cursor.close();
} else {
Toast.makeText(this, "연락처를 찾을 수 없습니다.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "권한이 허가되었습니다.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "연락처 접근 권한이 필요합니다.", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
drawable
'Android' 카테고리의 다른 글
[Java][Android] WorkManager로 백그라운드 작업 하기 (1) | 2025.05.05 |
---|---|
[Java][Android] 안드로이드 웹 스크래퍼 만들기: Jsoup (1) | 2025.01.06 |
[JAVA][Android] 채팅중 키보드에 글자가 가려지는 경우 setStackFromEnd 사용 // RecyclerView 스크롤 키보드 가려지는경우 (2) | 2024.07.13 |
[JAVA][Android] ProgressBarLoad를 사용해 로딩 다이얼로그 만들기 (1) | 2024.06.30 |
[JAVA][Android]안드로이드 interface 사용하기 (1) | 2024.06.07 |