파일 공유

콘텐츠 URI를 사용하여 파일을 공유하도록 앱을 설정하였으면 이 파일에 대한 다른 앱의 요청에 응답할 수 있습니다. 이 요청에 응답하는 한 가지 방법은 다른 애플리케이션에서 호출할 수 있는 서버 앱에서 파일 선택 인터페이스를 제공하는 것입니다. 이 방법을 사용하면 클라이언트 애플리케이션은 사용자가 서버 앱에서 파일을 선택한 후 선택한 파일의 콘텐츠 URI를 수신하도록 할 수 있습니다.

이 과정에서는 파일 요청에 응답하는 앱에서 파일 선택 Activity를 만드는 방법을 보여줍니다.

파일 요청 수신

클라이언트 앱의 파일 요청을 수신하고 콘텐츠 URI로 응답하려면 앱에서 파일 선택 Activity를 제공해야 합니다. 클라이언트 앱은 ACTION_PICK 작업을 포함하는 IntentstartActivityForResult()를 호출하여 이 Activity를 시작합니다. 클라이언트 앱이 startActivityForResult()를 호출하면 앱에서는 사용자가 선택한 파일의 콘텐츠 URI 형태로 클라이언트 앱에 결과를 반환할 수 있습니다.

클라이언트 앱에서 파일 요청을 구현하는 방법에 관해 알아보려면 공유 파일 요청 과정을 참조하세요.

파일 선택 활동 만들기

파일 선택 Activity를 설정하려면 먼저, 매니페스트에 Activity를 지정하고 이와 함께 ACTION_PICK 작업, CATEGORY_DEFAULTCATEGORY_OPENABLE 카테고리와 일치하는 인텐트 필터도 지정합니다. 또한 앱이 다른 앱에 제공하는 파일의 MIME 유형 필터를 추가합니다. 다음 스니펫에서는 새로운 Activity 및 인텐트 필터를 지정하는 방법을 보여줍니다.

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
        ...
            <application>
            ...
                <activity
                    android:name=".FileSelectActivity"
                    android:label="@File Selector" >
                    <intent-filter>
                        <action
                            android:name="android.intent.action.PICK"/>
                        <category
                            android:name="android.intent.category.DEFAULT"/>
                        <category
                            android:name="android.intent.category.OPENABLE"/>
                        <data android:mimeType="text/plain"/>
                        <data android:mimeType="image/*"/>
                    </intent-filter>
                </activity>

코드에서 파일 선택 활동 정의

다음으로 내부 저장소에 있는 앱의 Activity 디렉터리에서 사용 가능한 파일을 표시하며 사용자가 원하는 파일을 선택하도록 하는 files/images/ 서브클래스를 정의합니다. 다음 스니펫에서는 이 Activity를 정의하고 사용자의 선택에 응답하는 방법을 보여줍니다.

Kotlin

    class MainActivity : Activity() {

        // The path to the root of this app's internal storage
        private lateinit var privateRootDir: File
        // The path to the "images" subdirectory
        private lateinit var imagesDir: File
        // Array of files in the images subdirectory
        private lateinit var imageFiles: Array<File>
        // Array of filenames corresponding to imageFiles
        private lateinit var imageFilenames: Array<String>

        // Initialize the Activity
        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            // Set up an Intent to send back to apps that request a file
            resultIntent = Intent("com.example.myapp.ACTION_RETURN_FILE")
            // Get the files/ subdirectory of internal storage
            privateRootDir = filesDir
            // Get the files/images subdirectory;
            imagesDir = File(privateRootDir, "images")
            // Get the files in the images subdirectory
            imageFiles = imagesDir.listFiles()
            // Set the Activity's result to null to begin with
            setResult(Activity.RESULT_CANCELED, null)
            /*
             * Display the file names in the ListView fileListView.
             * Back the ListView with the array imageFilenames, which
             * you can create by iterating through imageFiles and
             * calling File.getAbsolutePath() for each File
             */
            ...
        }
        ...
    }
    

자바

    public class MainActivity extends Activity {
        // The path to the root of this app's internal storage
        private File privateRootDir;
        // The path to the "images" subdirectory
        private File imagesDir;
        // Array of files in the images subdirectory
        File[] imageFiles;
        // Array of filenames corresponding to imageFiles
        String[] imageFilenames;
        // Initialize the Activity
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...
            // Set up an Intent to send back to apps that request a file
            resultIntent =
                    new Intent("com.example.myapp.ACTION_RETURN_FILE");
            // Get the files/ subdirectory of internal storage
            privateRootDir = getFilesDir();
            // Get the files/images subdirectory;
            imagesDir = new File(privateRootDir, "images");
            // Get the files in the images subdirectory
            imageFiles = imagesDir.listFiles();
            // Set the Activity's result to null to begin with
            setResult(Activity.RESULT_CANCELED, null);
            /*
             * Display the file names in the ListView fileListView.
             * Back the ListView with the array imageFilenames, which
             * you can create by iterating through imageFiles and
             * calling File.getAbsolutePath() for each File
             */
             ...
        }
        ...
    }
    

파일 선택에 응답

사용자가 공유 파일을 선택하면 애플리케이션에서는 선택된 파일을 확인한 후 파일의 콘텐츠 URI를 생성해야 합니다. Activity는 사용 가능한 파일 목록을 ListView에 표시하므로 사용자가 파일 이름을 클릭하면 시스템에서는 onItemClick() 메서드를 호출합니다. 이를 통해 선택된 파일을 가져올 수 있습니다.

인텐트를 사용하여 한 앱에서 다른 앱으로 파일의 URI를 전송할 때 다른 앱에서 읽을 수 있는 URI를 가져오도록 주의해야 합니다. Android 6.0(API 수준 23) 이상을 실행 중인 기기에서 이렇게 하려면 특별한 주의가 필요합니다. 이 Android 버전의 권한 모델이 변경되어 특히 READ_EXTERNAL_STORAGE가 수신 앱에는 없을 수 있는 위험한 권한이 되기 때문입니다.

이러한 사항을 고려할 때 몇 가지 단점이 있는 Uri.fromFile()은 사용하지 않는 것이 좋습니다. 이 메서드의 특성은 다음과 같습니다.

  • 프로필 간 파일 공유를 허용하지 않습니다.
  • Android 4.4(API 수준 19) 이하를 실행 중인 기기에서는 앱에 WRITE_EXTERNAL_STORAGE 권한이 있어야 합니다.
  • 수신 앱에 READ_EXTERNAL_STORAGE 권한이 있어야 합니다. 이 권한은 이 권한이 없는 Gmail과 같은 중요 공유 타겟에서는 실패합니다.

Uri.fromFile()을 사용하는 대신 URI 권한을 사용하여 다른 앱에 특정 URI에 액세스할 수 있는 권한을 부여할 수 있습니다. URI 권한은 Uri.fromFile()에서 생성한 file:// URI에서는 작동하지 않지만 콘텐츠 제공업체에 연결된 URI에서는 작동합니다. FileProvider API는 이러한 URI를 만드는 데 도움이 될 수 있습니다. 또한 이 방법은 외부 저장소가 아니라 인텐트를 전송하는 앱의 로컬 저장소에 있는 파일에도 사용할 수 있습니다.

onItemClick()에서 선택된 파일의 파일 이름에 관한 File 객체를 가져와 getUriForFile()에 인수로 전달합니다. 이와 함께 FileProvider<provider> 요소에서 지정한 권한도 전달합니다. 그 결과로 얻는 콘텐츠 URI에는 권한, 파일의 디렉터리(XML 메타데이터에 지정됨)에 상응하는 경로 세그먼트, 확장자가 포함된 파일 이름이 들어 있습니다. FileProvider에서 XML 메타데이터를 기반으로 디렉터리를 경로 세그먼트로 매핑하는 방식은 공유 가능 디렉터리 지정 섹션에 설명되어 있습니다.

다음 스니펫에서는 선택된 파일을 감지하고 이 파일의 콘텐츠 URI를 가져오는 방법을 보여줍니다.

Kotlin

        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            // Define a listener that responds to clicks on a file in the ListView
            fileListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                /*
                 * Get a File for the selected file name.
                 * Assume that the file names are in the
                 * imageFilename array.
                 */
                val requestFile = File(imageFilenames[position])
                /*
                 * Most file-related method calls need to be in
                 * try-catch blocks.
                 */
                // Use the FileProvider to get a content URI
                val fileUri: Uri? = try {
                    FileProvider.getUriForFile(
                            this@MainActivity,
                            "com.example.myapp.fileprovider",
                            requestFile)
                } catch (e: IllegalArgumentException) {
                    Log.e("File Selector",
                            "The selected file can't be shared: $requestFile")
                    null
                }
                ...
            }
            ...
        }
    

자바

        protected void onCreate(Bundle savedInstanceState) {
            ...
            // Define a listener that responds to clicks on a file in the ListView
            fileListView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                @Override
                /*
                 * When a filename in the ListView is clicked, get its
                 * content URI and send it to the requesting app
                 */
                public void onItemClick(AdapterView<?> adapterView,
                        View view,
                        int position,
                        long rowId) {
                    /*
                     * Get a File for the selected file name.
                     * Assume that the file names are in the
                     * imageFilename array.
                     */
                    File requestFile = new File(imageFilename[position]);
                    /*
                     * Most file-related method calls need to be in
                     * try-catch blocks.
                     */
                    // Use the FileProvider to get a content URI
                    try {
                        fileUri = FileProvider.getUriForFile(
                                MainActivity.this,
                                "com.example.myapp.fileprovider",
                                requestFile);
                    } catch (IllegalArgumentException e) {
                        Log.e("File Selector",
                              "The selected file can't be shared: " + requestFile.toString());
                    }
                    ...
                }
            });
            ...
        }
    

공유 가능 디렉터리 지정 섹션에 설명된 대로 <paths> 요소를 포함하는 메타데이터 파일에서 지정한 디렉터리에 있는 파일의 콘텐츠 URI만 생성할 수 있습니다. 지정하지 않은 경로에 있는 FilegetUriForFile()을 호출하면 IllegalArgumentException이 발생합니다.

파일의 권한 부여

이제 다른 앱과 공유하려는 파일의 콘텐츠 URI가 있으므로 클라이언트 앱이 파일에 액세스하도록 허용해야 합니다. 액세스를 허용하려면 콘텐츠 URI를 Intent에 추가한 후 Intent에 권한 플래그를 설정하여 클라이언트 앱에 권한을 부여합니다. 부여하는 권한은 일시적인 것이며 수신 앱의 작업 스택이 완료되면 자동으로 만료됩니다.

다음 코드 스니펫에서는 파일에 대한 읽기 권한을 설정하는 방법을 보여줍니다.

Kotlin

        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            // Define a listener that responds to clicks on a file in the ListView
            fileListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                ...
                if (fileUri != null) {
                    // Grant temporary read permission to the content URI
                    resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    ...
                }
                ...
            }
            ...
        }
    

자바

        protected void onCreate(Bundle savedInstanceState) {
            ...
            // Define a listener that responds to clicks in the ListView
            fileListView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView,
                        View view,
                        int position,
                        long rowId) {
                    ...
                    if (fileUri != null) {
                        // Grant temporary read permission to the content URI
                        resultIntent.addFlags(
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    ...
                 }
                 ...
            });
        ...
        }
    

주의: setFlags()를 호출하는 것은 임시 액세스 권한을 사용하여 파일 액세스 권한을 안전하게 부여할 수 있는 유일한 방법입니다. Context.grantUriPermission() 메서드는 Context.revokeUriPermission()을 호출해야만 취소 가능한 액세스 권한을 부여하므로 파일의 콘텐츠 URI에 대해 이 메서드를 호출해서는 안 됩니다.

Uri.fromFile()을 사용하지 마세요. 이 메서드는 수신 앱이 READ_EXTERNAL_STORAGE 권한을 보유하도록 강제하고, 여러 사용자에게 공유하려 하면 작동하지 않으며, 4.4(API 수준 19) 미만의 Android 버전에서는 앱에 WRITE_EXTERNAL_STORAGE가 있어야 작동합니다. 그리고 Gmail 앱과 같이 정말 중요한 공유 타겟에는 READ_EXTERNAL_STORAGE가 없어 이 호출이 실패합니다. 대신에 URI 권한을 사용하여 다른 앱에 특정 URI 액세스 권한을 부여할 수 있습니다. URI 권한은 Uri.fromFile()에서 생성한 file:// URI에서는 작동하지 않지만 콘텐츠 제공업체와 연결된 URI에서는 작동합니다. 이를 위해 직접 구현하는 대신 파일 공유에 설명된 대로 FileProvider를 사용할 수 있고, 또 사용해야 합니다.

요청 앱과 파일 공유

파일을 요청한 앱과 그 파일을 공유하려면 콘텐츠 URI 및 권한이 포함된 IntentsetResult()에 전달합니다. 방금 정의한 Activity가 완료되면 시스템에서는 콘텐츠 URI가 포함된 Intent를 클라이언트 앱으로 보냅니다. 다음 코드 스니펫에서는 이렇게 하는 방법을 보여줍니다.

Kotlin

        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            // Define a listener that responds to clicks on a file in the ListView
            fileListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                ...
                if (fileUri != null) {
                    ...
                    // Put the Uri and MIME type in the result Intent
                    resultIntent.setDataAndType(fileUri, contentResolver.getType(fileUri))
                    // Set the result
                    setResult(Activity.RESULT_OK, resultIntent)
                } else {
                    resultIntent.setDataAndType(null, "")
                    setResult(RESULT_CANCELED, resultIntent)
                }
            }
        }
    

자바

        protected void onCreate(Bundle savedInstanceState) {
            ...
            // Define a listener that responds to clicks on a file in the ListView
            fileListView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView,
                        View view,
                        int position,
                        long rowId) {
                    ...
                    if (fileUri != null) {
                        ...
                        // Put the Uri and MIME type in the result Intent
                        resultIntent.setDataAndType(
                                fileUri,
                                getContentResolver().getType(fileUri));
                        // Set the result
                        MainActivity.this.setResult(Activity.RESULT_OK,
                                resultIntent);
                        } else {
                            resultIntent.setDataAndType(null, "");
                            MainActivity.this.setResult(RESULT_CANCELED,
                                    resultIntent);
                        }
                    }
            });
    

사용자가 파일을 선택한 후 클라이언트 앱으로 즉시 돌아갈 수 있는 방법을 알려주세요. 이렇게 할 수 있는 한 가지 방법은 체크표시 또는 완료 버튼을 제공하는 것입니다. 버튼의 android:onClick 속성을 사용하여 메서드를 버튼과 연결합니다. 메서드에서 finish()를 호출합니다. 예를 들면 다음과 같습니다.

Kotlin

        fun onDoneClick(v: View) {
            // Associate a method with the Done button
            finish()
        }
    

자바

        public void onDoneClick(View v) {
            // Associate a method with the Done button
            finish();
        }
    

추가 관련 정보는 다음을 참조하세요.