Android官方开发文档Training系列课程中文版:分享文件之获取文件信息
原文地址:http://android.xsoftlab.net/training/secure-file-sharing/retrieve-info.html
之前的課程講述了客戶端APP試圖與含有文件的URI一同運行,APP可以請求服務端APP的文件信息,包括文件的數據類型以及文件的大小。這些數據類型可以幫助客戶端APP來判斷該文件是否可以處理,文件的大小可以幫助客戶端APP對該文件設置相應大小的緩沖區。
這節課演示了如何查詢服務端APP返回文件的MIME類型以及大小。
獲取文件的MIME類型
一個文件的數據類型指示了客戶端APP應該如何處理這個文件的內容。為了獲取URI對應文件的數據類型,客戶端APP需要調用方法ContentResolver.getType()。這個方法返回了文件的MIME類型。默認情況下,FileProvider可以從文件的擴展名來判斷文件的MIME類型。
下面這段代碼演示了客戶端APP如何解析服務端APP返回的URI對應文件的MIME類型:
.../** 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()方法的默認實現,該方法可以返回URI相關文件的名稱與大小,不過結果位于一個Cursor對象中。默認的實現會返回兩列:
DISPLAY_NAME
- 這是文件的名稱,是字符串類型。這個值與File.getName()方法返回的值相等。
SIZE
- 這是文件的大小,以字節形式呈現,是long類型。這個值與File.length()方法返回的值相等。
客戶端APP可以通過對query()方法設置null參數的方式來獲得文件的名稱與大小,當然URI參數除外。舉個例子,下面這段代碼獲取了一個文件的名稱與大小,并且在單獨的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)));總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:分享文件之获取文件信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于法律罪行知识图谱的智能预判与客服问答
- 下一篇: Android官方开发文档Trainin