2019년 5월 15일 수요일

안드로이드 FileProvider 예제

- FileProvider를 통해 앱 내부 저장소에 저장된 파일을 외부로 공유한다.


1. 기본코드
- res/xml/file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="image"
        path="temp_image/" />

    <files-path
        name="text"
        path="temp_text/" />
</paths>


image, text 이름은 실제로 temp_image, temp_text 디렉토리명으로 연결된다.

files-path를 적용했으므로 디렉토리 경로는
/data/user/0/simple.app.simplefileprovider/files/temp_image/
/data/user/0/simple.app.simplefileprovider/files/temp_text/



- AndroidManifest.xml
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="simple.app.simplefileprovider.fileprovider"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>

android:authorities 값은 패키지명에 fileprovider를 붙이는게 일반적이다.



- Intent 파일 Uri 전달.
File dir = new File(getFilesDir(), "temp_image");
File file = new File(dir, "image.jpg");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(FileProvider.getUriForFile(getBaseContext(), AUTHORITY, file), "image/*");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);

FileProvider를 사용해서 Uri를 가져온다.
여기서 사용되는 Uri주소는
content://simple.app.simplefileprovider.fileprovider/image/image.jpg

FLAG_GRANT_READ_URI_PERMISSION를 사용해야 한다.
안드로이드 N 버전 부터 반드시 적용해야 하는 사양이다.


2. 샘플코드
소스코드
APK





댓글 없음:

댓글 쓰기