728x90
안녕하세요!
앱을 만들때 기획에 따라 자신의 휴대폰에 주소록에 있는 정보가 필요할 때가 있는데요!
QuickContactBadge를 사용해서 주소록에 접근 후 해당 휴대폰번호를 기준으로 해당 정보를 가져와 보겠습니다!
<?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>
MainActivity
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
'안드로이드 자바' 카테고리의 다른 글
[Java][Android]SeekBar의 이미지 변경하기 (1) | 2024.09.13 |
---|---|
[JAVA][Android]토글버튼(ToggleButton) 사용하기 (0) | 2024.09.12 |
[JAVA][Android] TabHost를 사용하여 탭 화면 만들기 (2) | 2024.09.08 |
[Java][Android]SearchView 사용 예시 만들기 (0) | 2024.09.07 |
[JAVA][Android] 안드로이드에서 URI를 전송 가능한 데이터 형태로 변환하기 (0) | 2024.09.06 |