Запрос на использование файла, к которому предоставлен доступ

Когда приложению требуется доступ к файлу, которым поделилось другое приложение, запрашивающее приложение (клиент) обычно отправляет запрос приложению, которое делится файлами (серверу). В большинстве случаев запрос запускает в приложении-сервере Activity, которое показывает файлы, доступные для передачи. Пользователь выбирает файл, после чего серверное приложение возвращает URI контента файла клиентскому приложению.

В этом уроке показано, как клиентское приложение запрашивает файл у серверного приложения, получает URI контента файла от серверного приложения и открывает файл с помощью URI контента.

Как отправить запрос на доступ к файлу

Чтобы запросить файл у серверного приложения, клиентское приложение вызывает метод startActivityForResult с объектом Intent, содержащим действие, например ACTION_PICK, и MIME-тип, который может обработать клиентское приложение.

Например, в следующем фрагменте кода показано, как отправить Intent в серверное приложение, чтобы запустить Activity, описанный в разделе Общий доступ к файлу:

Kotlin

class MainActivity : Activity() {
    private lateinit var requestFileIntent: Intent
    private lateinit var inputPFD: ParcelFileDescriptor
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestFileIntent = Intent(Intent.ACTION_PICK).apply {
            type = "image/jpg"
        }
        ...
    }
    ...
    private fun requestFile() {
        /**
         * When the user requests a file, send an Intent to the
         * server app.
         * files.
         */
        startActivityForResult(requestFileIntent, 0)
        ...
    }
    ...
}

Java

public class MainActivity extends Activity {
    private Intent requestFileIntent;
    private ParcelFileDescriptor inputPFD;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestFileIntent = new Intent(Intent.ACTION_PICK);
        requestFileIntent.setType("image/jpg");
        ...
    }
    ...
    protected void requestFile() {
        /**
         * When the user requests a file, send an Intent to the
         * server app.
         * files.
         */
            startActivityForResult(requestFileIntent, 0);
        ...
    }
    ...
}

Как получить доступ к запрошенному файлу

Серверное приложение отправляет URI контента файла обратно клиентскому приложению в объекте Intent. Этот объект Intent передается в клиентское приложение в переопределении метода onActivityResult(). Получив URI контента, клиентское приложение может получить доступ к файлу, запросив его FileDescriptor.

Безопасность файла обеспечивается только в том случае, если вы правильно анализируете URI контента, который получает клиентское приложение. При обработке контента убедитесь, что URI не указывает на объекты за пределами целевого каталога, то есть не выполняется попытка обхода каталога. Доступ к файлу должно получить только клиентское приложение и только в рамках разрешений, предоставленных серверным приложением. Разрешения являются временными, поэтому после завершения стека задач клиентского приложения файл больше не будет доступен за пределами серверного приложения.

В следующем фрагменте кода показано, как клиентское приложение обрабатывает Intent, отправленный из серверного приложения, и как клиентское приложение получает FileDescriptor с помощью URI контента:

Kotlin

/*
 * When the Activity of the app that hosts files sets a result and calls
 * finish(), this method is invoked. The returned Intent contains the
 * content URI of a selected file. The result code indicates if the
 * selection worked or not.
 */
public override fun onActivityResult(requestCode: Int, resultCode: Int, returnIntent: Intent) {
    // If the selection didn't work
    if (resultCode != Activity.RESULT_OK) {
        // Exit without doing anything else
        return
    }
    // Get the file's content URI from the incoming Intent
    returnIntent.data?.also { 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.
         */
        inputPFD = try {
            /*
             * Get the content resolver instance for this context, and use it
             * to get a ParcelFileDescriptor for the file.
             */
            contentResolver.openFileDescriptor(returnUri, "r")
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            Log.e("MainActivity", "File not found.")
            return
        }

        // Get a regular file descriptor for the file
        val fd = inputPFD.fileDescriptor
        ...
    }
}

Java

    /*
     * When the Activity of the app that hosts files sets a result and calls
     * finish(), this method is invoked. The returned Intent contains the
     * content URI of a selected file. The result code indicates if the
     * selection worked or not.
     */
    @Override
    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();
            /*
             * 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();
            ...
        }
    }

Метод openFileDescriptor() возвращает ParcelFileDescriptor для файла. Из этого объекта клиентское приложение получает объект FileDescriptor, который затем может использовать для чтения файла.

Дополнительную информацию можно найти в следующих статьях: