طلب ملف مشترك

عندما يريد تطبيق الوصول إلى ملف شاركه تطبيق آخر، يرسل عادةً التطبيق الذي قدّم الطلب (العميل) طلبًا إلى التطبيق الذي يشارك الملفات (الخادم). في معظم الحالات، يبدأ الطلب Activity في تطبيق الخادم الذي يعرض الملفات التي يمكنه مشاركتها. يختار المستخدم ملفًا، وبعد ذلك يعرض تطبيق الخادم معرّف الموارد المنتظم (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(). بعد حصول تطبيق العميل على معرّف الموارد المنتظم للمحتوى الخاص بالملف، يمكنه الوصول إلى الملف من خلال الحصول على FileDescriptor الخاص به.

ويتم الاحتفاظ بأمان الملفات خلال هذه العملية لأن معرّف الموارد المنتظم (URI) للمحتوى هو الجزء الوحيد من البيانات التي يتلقّاها تطبيق العميل. وبما أنّ معرّف الموارد المنتظم (URI) هذا لا يحتوي على مسار دليل، لن يتمكّن تطبيق العميل من اكتشاف أي ملفات أخرى وفتحها في تطبيق الخادم. ولا يمكن سوى لتطبيق العميل الوصول إلى الملف، ويقتصر إذن الوصول إلى الملف على الأذونات التي يمنحها تطبيق الخادم فقط. تكون الأذونات مؤقتة، وبالتالي بعد الانتهاء من حزمة مهام تطبيق العميل، لن يمكن الوصول إلى الملف بعد ذلك خارج تطبيق الخادم.

يوضّح المقتطف التالي كيف يعالج تطبيق العميل Intent التي يتم إرسالها من تطبيق الخادم، وكيف يحصل تطبيق العميل على FileDescriptor باستخدام معرّف الموارد المنتظم للمحتوى:

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 الذي يمكنه استخدامه بعد ذلك لقراءة الملف.

للحصول على معلومات إضافية ذات صلة، راجع: