Paylaşılan dosyayı isteme

Bir uygulama, başka bir uygulama tarafından paylaşılan bir dosyaya erişmek istediğinde, istekte bulunan uygulama (istemci) genellikle dosyaları paylaşan uygulamaya (sunucu) bir istek gönderir. Çoğu durumda, istek, sunucu uygulamasında paylaşabileceği dosyaları görüntüleyen bir Activity başlatır. Kullanıcı bir dosya seçer. Ardından sunucu uygulaması, dosyanın içerik URI'sını istemci uygulamasına döndürür.

Bu derste, istemci uygulamasının sunucu uygulamasından nasıl dosya isteğinde bulunduğunu, dosyanın içerik URI'sını sunucu uygulamasından nasıl aldığını ve dosyayı içerik URI'sını kullanarak nasıl açtığını öğrenebilirsiniz.

Dosya için istek gönderin

İstemci uygulaması, sunucu uygulamasından bir dosya istemek için startActivityForResult yöntemini, ACTION_PICK gibi işlemi içeren bir Intent ve istemci uygulamasının işleyebileceği bir MIME türü ile çağırır.

Örneğin, aşağıdaki kod snippet'i Dosya paylaşma bölümünde açıklanan Activity öğesini başlatmak için sunucu uygulamasına nasıl Intent gönderileceğini göstermektedir:

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

İstenen dosyaya erişme

Sunucu uygulaması, dosyanın içerik URI'sını Intent içinde istemci uygulamasına geri gönderir. Bu Intent, onActivityResult() değerini geçersiz kılma sırasında istemci uygulamasına aktarıldı. İstemci uygulaması dosyanın içerik URI'sını aldıktan sonra, FileDescriptor dosyasını alarak dosyaya erişebilir.

Bu işlemde dosya güvenliği, yalnızca istemci uygulamasının aldığı içerik URI'sını düzgün bir şekilde çözümlediğiniz sürece korunur. İçeriği ayrıştırırken, bu URI'nın amaçlanan dizinin dışındaki herhangi bir şeyi göstermediğinden emin olmalı ve böylece path traversal denenmediğinden emin olmalısınız. Dosyaya yalnızca istemci uygulaması ve sadece sunucu uygulaması tarafından verilen izinler için erişim elde edilmelidir. İzinler geçicidir, bu nedenle istemci uygulamasının görev yığını tamamlandığında dosyaya artık sunucu uygulaması dışından erişilemez.

Sonraki snippet, istemci uygulamasının sunucu uygulamasından gönderilen Intent öğesini nasıl işlediğini ve istemci uygulamasının içerik URI'sını kullanarak FileDescriptor öğesini nasıl aldığını gösterir:

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() yöntemi, dosya için bir ParcelFileDescriptor döndürür. İstemci uygulaması bu nesneden bir FileDescriptor nesnesi alır ve bu nesneyi daha sonra dosyayı okumak için kullanabilir.

Daha fazla bilgi için aşağıdaki kaynaklara bakın: