파일 공유

콘텐츠 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>

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

그런 다음, 내부 저장소에 있는 앱의 files/images/ 디렉터리에서 사용 가능한 파일을 표시하고 사용자가 원하는 파일을 선택할 수 있게 해주는 Activity 서브클래스를 정의합니다. 다음 스니펫에서는 이 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
         */
        ...
    }
    ...
}

Java

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 객체를 가져와서 FileProvider<provider> 요소에서 지정한 권한과 함께 getUriForFile()에 인수로 전달합니다. 결과로 도출되는 콘텐츠 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
            }
            ...
        }
        ...
    }

Java

    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만 생성할 수 있습니다. 지정하지 않은 경로에서 File에 관해 getUriForFile()를 호출하면 IllegalArgumentException이 발생합니다.

파일의 권한 부여

이제 다른 앱과 공유하려는 파일의 콘텐츠 URI가 있으므로 클라이언트 앱에서 파일에 액세스하도록 허용해야 합니다. 액세스를 허용하려면 Intent에 콘텐츠 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) {
                // Grant temporary read permission to the content URI
                resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                ...
            }
            ...
        }
        ...
    }

Java

    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()를 호출하는 것은 임시 액세스 권한을 사용하여 파일 액세스 권한을 안전하게 부여할 수 있는 유일한 방법입니다. 파일의 콘텐츠 URI에 Context.grantUriPermission() 메서드를 호출하지 마세요. 이 메서드는 Context.revokeUriPermission() 호출을 통해서만 취소할 수 있는 액세스 권한을 부여하기 때문입니다.

Uri.fromFile()을 사용하지 마세요. 이 메서드는 앱이 READ_EXTERNAL_STORAGE 권한을 갖도록 강제하고 여러 사용자와 공유하려는 경우에는 전혀 작동하지 않으며 Android 버전 4.4 (API 수준 19) 미만에서는 앱에 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)
            }
        }
    }

Java

    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()
    }

Java

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

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