Android文件共享之检索文件信息

来源:互联网 发布:南京网络推广江苏斯点 编辑:程序博客网 时间:2024/05/20 16:13

在客户端应用程序尝试使用具有内容URI的文件之前,应用程序可以从服务器应用程序请求有关文件的信息,包括文件的数据类型和文件大小。数据类型帮助客户端应用程序确定它是否可以处理文件,文件大小有助于客户端应用程序为文件设置缓冲和缓存。

本课程演示如何查询服务器应用程序的FileProvider以检索文件的MIME类型和大小。

检索文件的MIME类型

文件的数据类型向客户端应用程序指示它应如何处理文件的内容。要获取共享文件的数据类型给定其内容URI,客户端应用程序调用ContentResolver.getType()。此方法返回文件的MIME类型。默认情况下,FileProvider从文件扩展名确定文件的MIME类型。

以下代码段演示了在服务器应用程序将内容URI返回给客户端后,客户端应用程序如何检索文件的MIME类型:

  ...    /*     *从传入的Intent获取文件的内容URI,然后     *获取文件的MIME类型     */    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_NAME和SIZE。例如,此代码段检索文件的DISPLAY_NAME和SIZE,并在单独的TextView中显示每个文件:

 ...    /*     * 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)));    ...
0 0
原创粉丝点击