본문 바로가기

IT/안드로이드 관련

[안드로이드] File Provider 파일공유(Nougat7 + 대응)

안녕하세요 YTS 입니다.

오늘은 File Provider에 대한 사용방법에 대해 알아보려합니다.

Android 7.0 이상부터 파일공유 정책이 변경되었습니다. 그렇기에 File Provider에 대해 알아두셔야합니다.


파일에 일반 경로인  file://~ 을 참조하면 Fileuriexposedexception이 발생합니다.

파일의 공유 uricontent://로 시작되어야하며, 접근권을 줘야하며

안드로이드에서는 FileProvider 사용을 권장하고 있습니다.



1. res/xml/provider.xml 생성


<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path
name="cache"
path="." /> <!--Context.getCacheDir() 내부 저장소-->
<files-path
name="files"
path="." /> <!--Context.getFilesDir() 내부 저장소-->

<external-path
name="external"
path="."/> <!-- Environment.getExternalStorageDirectory() 외부 저장소-->
<external-cache-path
name="external-cache"
path="."/> <!-- Context.getExternalCacheDir() 외부 저장소-->
<external-files-path
name="external-files"
path="."/> <!-- Context.getExternalFilesDir() 외부 저장소-->
</paths>


2. Manifest에 해당 정보 입력 

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


3. 파일 공유 방법


Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, new File(filePath)));
Intent chooser = Intent.createChooser(intent, context.getString(R.string.share));
context.startActivity(chooser);


이상입니다.


예전에 파일공유는 정말 쉬웠었는데 


안드로이드에 보안 강화로 인하여 조금 복잡해진 기분이 있지만 한번 적어놓고 처리하면 다음부턴 손쉽게 처리 할 수있을거같습니다.



댓글과 공감은 작성자에게 큰힘이 됩니다. 마지막으로 저의 글을 읽어주셔서 감사합니다.