クライアント アプリは、コンテンツ URI を持つファイルを操作する前に、ファイルのデータ型やファイルサイズなど、ファイルに関する情報をサーバーアプリにリクエストできます。クライアント アプリは、データ型に基づいてファイルを処理できるかどうかを判断し、ファイルサイズに基づいて、ファイルのバッファリングとキャッシュを設定します。
このレッスンでは、サーバーアプリの FileProvider
に対してクエリを実行し、ファイルの MIME タイプとサイズを取得する方法について説明します。
ファイルの MIME タイプを取得する
ファイルのデータ型は、ファイルのコンテンツの処理方法をクライアント アプリに示します。コンテンツ URI を指定して共有ファイルのデータ型を取得するために、クライアント アプリは ContentResolver.getType()
を呼び出します。このメソッドはファイルの MIME タイプを返します。デフォルトでは、FileProvider
がファイル拡張子からファイルの MIME タイプを決定します。
次のコード スニペットは、サーバーアプリがコンテンツ URI をクライアントに返した後、クライアント アプリがファイルの MIME タイプを取得する方法を示しています。
Kotlin
... /* * Get the file's content URI from the incoming Intent, then * get the file's MIME type */ val mimeType: String? = returnIntent.data?.let { returnUri -> contentResolver.getType(returnUri) } ...
Java
... /* * Get the file's content URI from the incoming Intent, then * get the file's MIME type */ Uri returnUri = returnIntent.getData(); String mimeType = getContentResolver().getType(returnUri); ...
ファイルの名前とサイズを取得する
FileProvider
クラスには query()
メソッドのデフォルト実装があります。これは、Cursor
内のコンテンツ URI に関連付けられているファイルの名前とサイズを返します。デフォルトの実装では次の 2 つの列が返されます。
DISPLAY_NAME
-
ファイルの名前(
String
)。この値は、File.getName()
によって返される値と同じです。 SIZE
-
ファイルのサイズ(バイト単位、
long
)。この値は、File.length()
が返す値と同じです。
クライアント アプリは、query()
のすべての引数(コンテンツ URI を除く)を null
に設定することで、ファイルの DISPLAY_NAME
と SIZE
の両方を取得できます。たとえば、次のコード スニペットは、ファイルの DISPLAY_NAME
と SIZE
を取得し、それぞれを個別の TextView
で表示します。
Kotlin
/* * Get the file's content URI from the incoming Intent, * then query the server app to get the file's display name * and size. */ returnIntent.data?.let { returnUri -> contentResolver.query(returnUri, null, null, null, null) }?.use { cursor -> /* * Get the column indexes of the data in the Cursor, * move to the first row in the Cursor, get the data, * and display it. */ val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) cursor.moveToFirst() findViewById<TextView>(R.id.filename_text).text = cursor.getString(nameIndex) findViewById<TextView>(R.id.filesize_text).text = cursor.getLong(sizeIndex).toString() ... }
Java
... /* * Get the file's content URI from the incoming Intent, * then query the server app to get the file's display name * and size. */ Uri returnUri = returnIntent.getData(); Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * move to the first row in the Cursor, get the data, * and display it. */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); TextView nameView = (TextView) findViewById(R.id.filename_text); TextView sizeView = (TextView) findViewById(R.id.filesize_text); nameView.setText(returnCursor.getString(nameIndex)); sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex))); ...
その他の関連情報については、以下をご覧ください。