Yêu cầu một tệp được chia sẻ

Khi một ứng dụng muốn truy cập vào một tệp do một ứng dụng khác chia sẻ, ứng dụng yêu cầu đó (ứng dụng) thường gửi yêu cầu đến ứng dụng chia sẻ tệp đó (máy chủ). Trong hầu hết trường hợp, yêu cầu sẽ bắt đầu Activity trong ứng dụng máy chủ hiển thị các tệp mà ứng dụng này có thể chia sẻ. Người dùng chọn một tệp, sau đó ứng dụng máy chủ sẽ trả về URI nội dung của tệp cho ứng dụng khách.

Bài học này sẽ hướng dẫn bạn cách một ứng dụng khách yêu cầu một tệp từ một ứng dụng máy chủ, nhận URI nội dung của tệp từ ứng dụng máy chủ và mở tệp bằng URI nội dung.

Gửi yêu cầu về tệp

Để yêu cầu một tệp từ ứng dụng máy chủ, ứng dụng khách sẽ gọi startActivityForResult với Intent chứa thao tác như ACTION_PICK và loại MIME mà ứng dụng khách có thể xử lý.

Ví dụ: đoạn mã sau đây minh hoạ cách gửi Intent đến một ứng dụng máy chủ để khởi động Activity được mô tả trong phần Chia sẻ tệp:

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);
        ...
    }
    ...
}

Truy cập vào tệp được yêu cầu

Ứng dụng máy chủ sẽ gửi URI nội dung của tệp trở lại ứng dụng khách trong một Intent. Intent này được truyền đến ứng dụng khách trong cơ chế ghi đè onActivityResult(). Sau khi có URI nội dung của tệp, ứng dụng khách có thể truy cập vào tệp bằng cách lấy FileDescriptor của tệp.

Tính bảo mật của tệp được giữ nguyên trong quá trình này vì URI nội dung là phần dữ liệu duy nhất mà ứng dụng khách nhận được. Vì URI này không chứa đường dẫn thư mục, nên ứng dụng khách không thể khám phá và mở bất kỳ tệp nào khác trong ứng dụng máy chủ. Chỉ ứng dụng khách mới có quyền truy cập vào tệp, và chỉ đối với các quyền do ứng dụng máy chủ cấp. Các quyền này là tạm thời, do đó sau khi ngăn xếp tác vụ của ứng dụng khách hoàn tất, bên ngoài ứng dụng máy chủ sẽ không truy cập được tệp nữa.

Đoạn mã tiếp theo minh hoạ cách ứng dụng khách xử lý Intent được gửi từ ứng dụng máy chủ và cách ứng dụng khách lấy FileDescriptor bằng URI nội dung:

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

Phương thức openFileDescriptor() sẽ trả về ParcelFileDescriptor cho tệp. Từ đối tượng này, ứng dụng khách sẽ nhận được đối tượng FileDescriptor mà sau đó có thể dùng để đọc tệp.

Để biết thêm thông tin liên quan, hãy tham khảo: