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österen bir Activity başlatır. Kullanıcı bir dosya seçer. Ardından sunucu uygulaması, dosyanın içerik URI'sini istemci uygulamasına döndürür.

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

Dosya için istek gönderin

Sunucu uygulamasından dosya istemek için istemci uygulaması, ACTION_PICK gibi işlemi ve istemci uygulamasının işleyebileceği MIME türünü içeren bir Intent ile startActivityForResult kodunu çağırır.

Örneğin, aşağıdaki kod snippet'i, Dosya paylaşma bölümünde açıklanan Activity öğesinin başlatılması 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şim

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

İçerik URI'si istemci uygulamasının aldığı tek veri parçası olduğundan dosya güvenliği bu süreçte korunur. Bu URI bir dizin yolu içermediğinden, istemci uygulaması sunucu uygulamasındaki başka dosyaları keşfedip açamaz. Dosyaya yalnızca istemci uygulaması tarafından erişim sağlanır ve bu izinler yalnızca sunucu uygulaması tarafından verilen izinler için geçerlidir. İ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'sini 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.

İlgili daha fazla bilgi için aşağıdaki konulara bakın: