共有ファイルのリクエスト

あるアプリが別のアプリで共有されているファイルにアクセスする必要がある場合、リクエスト元のアプリ(クライアント)は通常、ファイルを共有しているアプリ(サーバー)にリクエストを送信します。ほとんどの場合、リクエストが発生すると、共有可能なファイルを表示するサーバーアプリで Activity が開始されます。ユーザーがファイルを選択すると、サーバーアプリがファイルのコンテンツ URI をクライアント アプリに返します。

このレッスンでは、クライアント アプリがサーバーアプリにファイルをリクエストし、サーバーアプリからファイルのコンテンツ URI を受け取って、そのコンテンツ URI を使用してファイルを開く方法について説明します。

ファイルのリクエストを送信する

サーバーアプリにファイルをリクエストする場合、クライアント アプリは、ACTION_PICK などのアクションとクライアント アプリが処理できる MIME タイプを含む IntentstartActivityForResult を呼び出します。

たとえば、次のコード スニペットは、ファイルの共有に記載されている Activity を開始するために、サーバーアプリに Intent を送信する方法を示しています。

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

リクエストされたファイルにアクセスする

サーバーアプリは、Intent でファイルのコンテンツ URI をクライアント アプリに返送します。この Intent は、onActivityResult() のオーバーライドでクライアント アプリに渡されます。ファイルのコンテンツ URI を受け取ったクライアント アプリは、FileDescriptor を取得してファイルにアクセスできます。

このプロセスでは、クライアント アプリが受け取る唯一のデータがコンテンツ URI であるため、ファイルのセキュリティが維持されます。この URI にはディレクトリ パスが含まれていないため、クライアント アプリはサーバーアプリ内の他のファイルを検出して開くことはできません。クライアント アプリだけがファイルにアクセスできます。アクセスできるのは、サーバーアプリによって付与された権限のみです。権限は一時的なものであり、クライアント アプリのタスクスタックが終了すると、サーバーアプリの外部からファイルにアクセスできなくなります。

次のスニペットは、クライアント アプリがサーバーアプリから送信された Intent を処理する方法と、コンテンツ URI を使用してクライアント アプリが 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 オブジェクトを取得します。このオブジェクトを使用してファイルを読み取ることができます。

その他の関連情報については、以下をご覧ください。