2024.01.17(수) TIL

quinones·2024년 1월 17일

실제 전화번호 백업해서 가져오기

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

manifest추가해준다.

나는 메인액티비티에서 프래그먼트를 만들어줬고, 권한을 확인 받은 후에 프래그먼트로 넘어갔다.

    private fun initReadContactsPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
            == PackageManager.PERMISSION_GRANTED
        ) {
            // READ_CONTACTS 권한이 이미 허용된 경우
            initViewPager()
        } else {
            // READ_CONTACTS 권한이 없는 경우, 권한 요청
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_CONTACTS),
                101  // 다른 값으로 설정
            )
        }
    }

다음으로 프래그먼트 안에서

private fun updateContactList() {
        if (isDataLoaded) return

        isDataLoaded = true
        val cursor = requireActivity().contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,
            null,
            null,
            null
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val nameColumnIndex =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val phoneNumberColumnIndex =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)
                val contactIdColumnIndex =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)
                if (nameColumnIndex >= 0 && phoneNumberColumnIndex >= 0 && contactIdColumnIndex >= 0) {
                    val name = cursor.getString(nameColumnIndex)
                    val phoneNumber = cursor.getString(phoneNumberColumnIndex)
                    val rawContactId = cursor.getLong(contactIdColumnIndex)

                    // 여기서 필요한 데이터를 가져와서 MyItem 객체를 생성하여 dataList에 추가
                    val newItem = MyItem(
                        icon = getContactPhotoUri(rawContactId) ?:null,
                        name = name ?: "",
                        like = R.drawable.ic_star_blank,
                        email = getEmail(rawContactId) ?: "",
                        myMessage = "",
                        phoneNum = phoneNumber ?: ""
                    )

                    dataList.add(newItem)
                }
            }
            cursor.close()
        }

        if (!::adapter.isInitialized) {
            adapter = MyAdapter(dataList)
            binding.recyclerView.adapter = adapter
        }

        adapter.notifyDataSetChanged()
    }

    private fun getEmail(contactId: Long): String? {
        val emailCursor = requireActivity().contentResolver.query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
            null,
            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
            arrayOf(contactId.toString()),
            null
        )

        var email: String? = null
        emailCursor?.use {
            if (it.moveToFirst()) {
                val emailColumnIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS)
                email = it.getString(emailColumnIndex)
            }
        }

        emailCursor?.close()
        return email
    }

    private fun getContactPhotoUri(rawContactId: Long): Uri? {
        Log.d("ContactsFragment", "getContactPhotoUri called")

        val photoUri = ContentUris.withAppendedId(
            ContactsContract.Contacts.CONTENT_URI,
            rawContactId
        )
        Log.d("ContactsFragment", "Photo URI: $photoUri")

        val inputStream: InputStream? =
            ContactsContract.Contacts.openContactPhotoInputStream(
                requireActivity().contentResolver,
                photoUri
            )

        val result: Uri? = if (inputStream != null) {
            val bitmap = BitmapFactory.decodeStream(inputStream)
            inputStream.close()
            Log.d("ContactsFragment", "Bitmap decoded successfully")
            saveImageToInternalStorage(bitmap, rawContactId.toString()) // 저장된 파일의 Uri를 반환
        } else {
            // 연락처에 사진이 없을 경우
            Log.d("ContactsFragment", "No contact photo found, using default URI")
            Uri.parse("android.resource://com.example.anycall/drawable/user")
        }

        Log.d("ContactsFragment", "가져온 사진: $result")
        return result
    }

    private fun saveImageToInternalStorage(bitmap: Bitmap, fileName: String): Uri? {
        Log.d("ContactsFragment", "saveImageToInternalStorage called")
        // 내부 저장소에 이미지를 저장하고 해당 파일의 Uri를 반환합니다.
        val wrapper = ContextWrapper(requireContext())
        var file = wrapper.getDir("images", Context.MODE_PRIVATE)
        file = File(file, "$fileName.jpg")

        try {
            val stream: OutputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            stream.flush()
            stream.close()
            return Uri.parse(file.absolutePath)
        } catch (e: IOException) {
            e.printStackTrace()
            Log.e("ContactsFragment", "Failed to save image to internal storage: ${e.message}")
        }
        // 이미지 저장에 실패한 경우 null을 반환
        return null
    }

이렇게 사용해서 원래 휴대폰에 저장되어있던 데이터를 가져와서 리사이클러뷰에 추가해 줄 수 있다.

profile
이우진

0개의 댓글