파일 공유

콘텐츠 URI를 사용하여 파일을 공유하도록 앱을 설정하고 나면 다른 앱의 요청에 응답할 수 있습니다. 요청할 수 있습니다 이러한 요청에 응답하는 한 가지 방법은 인터페이스를 호출할 수 있습니다. 이 접근 방식을 사용하면 클라이언트가 사용자가 서버 앱에서 파일을 선택하고 선택한 파일의 콘텐츠 URI입니다.

이 과정에서는 앱에서 파일 선택 Activity를 만드는 방법을 보여줍니다. 응답을 생성하는 역할을 합니다

파일 요청 수신

클라이언트 앱에서 파일 요청을 수신하고 콘텐츠 URI로 응답하려면 앱이 파일 선택 Activity를 제공합니다. 클라이언트 앱이 이를 시작함 작업이 포함된 IntentstartActivityForResult()를 호출하여 Activity ACTION_PICK입니다. 클라이언트 앱이 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() 몇 가지 단점이 있습니다 이 메서드의 특성은 다음과 같습니다.

  • 프로필 간 파일 공유를 허용하지 않습니다.
  • 앱에 다음이 필요합니다. WRITE_EXTERNAL_STORAGE 권한이 필요합니다.
  • 수신 앱에 READ_EXTERNAL_STORAGE 권한 해당 권한이 없는 Gmail과 같은 중요한 공유 대상에서는 실패합니다.

Uri.fromFile()를 사용하는 대신 URI 권한을 사용하여 다른 앱에 특정 URI에 액세스할 수 있습니다 URI 권한은 file:// URI에서 작동하지 않습니다. Uri.fromFile()에 의해 생성됩니다. 콘텐츠 제공자와 연결된 URI에서 작동합니다. 이 FileProvider API는 이러한 URI를 만들 수 있습니다. 이 방법은 외부 저장소이지만 인텐트를 전송하는 앱의 로컬 저장소에 저장됩니다.

onItemClick()에서 선택한 파일의 파일 이름에 대한 File 객체를 가져오고 이를 인수로 전달 getUriForFile() 및 귀하가 FileProvider<provider> 요소 결과로 도출되는 콘텐츠 URI에는 권한(파일의 디렉토리 (XML 메타데이터에 지정된 대로) 및 확장자가 포함됩니다. FileProvider가 디렉터리를 경로에 매핑하는 방법 세그먼트에 대한 설명은 이 섹션에 공유 가능 디렉터리 지정

다음 스니펫에서는 선택된 파일을 감지하고 이 파일의 콘텐츠 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());
                }
                ...
            }
        });
        ...
    }

디렉터리에 있는 파일에 대해서만 콘텐츠 URI를 생성할 수 있다는 점에 유의하세요. <paths> 요소가 포함된 메타데이터 파일에서 지정한 공유 가능 디렉터리 지정 섹션에 설명된 대로 URL을 지정합니다. 만약 가격: getUriForFile() File를 지정하지 않은 경우 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)
                ...
            }
            ...
        }
        ...
    }

자바

    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() 메서드를 사용하여 파일의 콘텐츠 URI에서 이 메서드가 취소 가능한 액세스 권한을 부여하므로 Context.revokeUriPermission() 호출

Uri.fromFile()을 사용하지 마세요. 앱 수신을 강제합니다. READ_EXTERNAL_STORAGE 권한 보유 여러 사용자 및 여러 버전에서 의 경우 WRITE_EXTERNAL_STORAGE을(를) 사용할 수 있습니다. 그리고 Gmail 앱과 같이 정말 중요한 공유 대상은 READ_EXTERNAL_STORAGE으로 인해 발생 이 호출이 실패합니다. 대신에 URI 권한을 사용하여 다른 앱에 특정 URI 액세스 권한을 부여할 수 있습니다. URI 권한은 Uri.fromFile()님, 그렇습니다. 콘텐츠 제공자와 연결된 URI에서 작동합니다. 이를 위해 자체 구현을 구현하는 대신 FileProvider를 사용할 수 있으며 사용해야 합니다 이를 파일 공유에 설명된 대로 공유할 수 있습니다.

요청 앱과 파일 공유

파일을 요청한 앱과 파일을 공유하려면 Intent setResult()에 대한 권한이 포함됩니다. 방금 정의한 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();
    }

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