检索文件信息

客户端应用尝试处理具有内容 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 关联的文件的名称和大小。默认实现会返回两列

DISPLAY_NAME
文件的名称,以 String 形式。此值与 File.getName() 返回的值相同。
SIZE
文件的字节大小,以 long 形式。此值与 File.length() 返回的值相同。

客户端应用可以通过将 query() 的所有参数都设置为 null(内容 URI 除外),获取文件的 DISPLAY_NAMESIZE。例如,以下代码片段检索文件的 DISPLAY_NAMESIZE,并在单独的 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)));
    ...

如需其他相关信息,请参阅