(Android/System) FileProvider — 외부 앱에 파일 URI 공유


1. 왜 FileProvider인가?

Android 7.0(API 24)부터 file:// URI를 다른 앱에 전달하면 FileUriExposedException 이 발생합니다. 내 앱의 내부 경로를 외부에 노출하면 안 되기 때문에, 임시 접근 권한이 부여되는 content:// URI로 바꿔서 전달해야 합니다.

❌ file:///data/data/com.example/files/photo.jpg   (경로 노출, 예외 발생)
✅ content://com.example.fileprovider/images/photo.jpg   (임시 권한으로 안전하게 전달)

2. Manifest 설정

<application>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>

3. 공유할 경로 정의 — file_paths.xml

공유를 허용할 폴더만 지정합니다.

<!-- res/xml/file_paths.xml -->
<paths>
    <files-path name="internal_files" path="shared/" />        <!-- context.filesDir/shared/ -->
    <cache-path name="cache_images" path="images/" />          <!-- context.cacheDir/images/ -->
    <external-files-path name="external_photos" path="Pictures/" />   <!-- getExternalFilesDir()/Pictures/ -->
</paths>
태그 실제 경로
files-path context.filesDir
cache-path context.cacheDir
external-files-path context.getExternalFilesDir(null)
external-cache-path context.externalCacheDir

path="." 로 폴더 전체를 열면 불필요한 파일까지 노출될 수 있습니다. 공유용 하위 폴더를 따로 만들어 그 폴더만 지정하세요.


4. URI 생성

val file = File(context.cacheDir, "images/photo.jpg")
val uri: Uri = FileProvider.getUriForFile(
    context,
    "${context.packageName}.fileprovider",     // Manifest의 authorities와 동일해야 함
    file
)

경로가 file_paths.xml에서 허용한 범위가 아니면 IllegalArgumentException이 발생합니다.


5. 카메라 촬영 결과 받기

private var photoUri: Uri? = null

private val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
    if (success) showPhoto(photoUri!!)
}

private fun launchCamera() {
    val file = File(cacheDir, "images").apply { mkdirs() }.let { File(it, "photo_${System.currentTimeMillis()}.jpg") }
    photoUri = FileProvider.getUriForFile(this, "$packageName.fileprovider", file)
    takePicture.launch(photoUri)               // 카메라 앱이 이 URI에 사진을 저장
}

TakePicture 계약이 쓰기 권한 부여를 자동 처리합니다.


6. 다른 앱에 공유 (ACTION_SEND)

val intent = Intent(Intent.ACTION_SEND).apply {
    type = "image/jpeg"
    putExtra(Intent.EXTRA_STREAM, uri)
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)       // 받는 앱에 읽기 권한 임시 부여
}
startActivity(Intent.createChooser(intent, "공유"))

FLAG_GRANT_READ_URI_PERMISSION을 빠뜨리면 받는 앱이 파일을 열 때 SecurityException이 발생합니다. 권한은 받는 앱의 해당 작업이 끝나면 만료됩니다.


7. 파일 열기 / APK 설치

// PDF 열기
val intent = Intent(Intent.ACTION_VIEW).apply {
    setDataAndType(uri, "application/pdf")
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(intent)

APK 설치는 추가로 REQUEST_INSTALL_PACKAGES 권한과 사용자 허용(“출처를 알 수 없는 앱”)이 필요합니다.


8. 흔한 문제

증상 원인/해결
FileUriExposedException file:// 직접 전달 → FileProvider 사용
IllegalArgumentException: Failed to find configured root file_paths.xml에 해당 경로 누락
받는 앱에서 SecurityException FLAG_GRANT_*_URI_PERMISSION 누락
authority 불일치 getUriForFile의 두 번째 인자와 Manifest의 authorities 확인
라이브러리와 충돌 다른 라이브러리도 FileProvider 선언 시 authority를 서로 다르게 또는 FileProvider 상속 클래스 사용

9. 정리



Related Posts