파일 공유
- 앱 간의 파일을 공유할 때 데이타 경우는 Intent로 전송하는데
파일을 공유하고 싶을 때 사용
(파일의 콘텐츠 URI 전송하고 수신할 앱에 대해서만 임시 액세스 권한을 부여하고 자동 만료되도록)
FileProvider 지정
- 다른 앱으로 파일을 공유하기 위해 콘텐츠 URI를 생성에 사용할 권한을 지정함
- 앱이 공유할 수 있는 디렉토리를 지정하는 XML 파일의 이름도 지정함
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
...>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
공유 가능 디렉토리 지정
- res/xml/filepaths.xml 추가
<paths>
<files-path path="images/" name="myimages" />
</paths>
content://com.example.myapp.fileprovider/myimages/default_image.jpg
위와같이 외부에서 사용할 수 있는 URI가 생성됨
공유 파일 요청
requestFileIntent = new Intent(Intent.ACTION_PICK);
requestFileIntent.setType("image/jpg");
startActivityForResult(requestFileIntent, 0);
파일 정보 가져오기
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
// Get the file's content URI from the incoming Intent
Uri returnUri = returnIntent.getData();
// get the file's MIME type
String mimeType = getContentResolver().getType(returnUri);
/*
* Try to open the file for "read" access using the
* returned URI. If the file isn't found, write to the
* error log and return.
*/
try {
/*
* Get the content resolver instance for this context, and use it
* to get a ParcelFileDescriptor for the file.
*/
inputPFD = getContentResolver().openFileDescriptor(returnUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("MainActivity", "File not found.");
return;
}
// Get a regular file descriptor for the file
FileDescriptor fd = inputPFD.getFileDescriptor();
...
}
}
참고 사이트
https://developer.android.com/training/secure-file-sharing?hl=ko
파일 공유 | Android 개발자 | Android Developers
앱에서 한 개 이상의 파일을 다른 앱에 제공해야 할 때가 자주 있습니다. 예를 들어 이미지 갤러리에서 파일을 이미지 편집기에 제공하거나 파일 관리 앱에서 사용자가 외부 저장소의 영역 간에
developer.android.com
https://developer.android.com/training/secure-file-sharing/request-file?hl=ko
'Android' 카테고리의 다른 글
★ Android 개발할 때 유용한 정보 모음 ★ (0) | 2021.07.20 |
---|---|
Android JAR vs. AAR (2) | 2021.06.24 |
Android 11 (0) | 2021.06.01 |
Dynamic Links (0) | 2021.04.13 |
DownloadManager (0) | 2021.03.16 |
댓글