Android官方開發文件Training系列課程中文版:分享檔案之獲取檔案資訊
阿新 • • 發佈:2019-02-19
之前的課程講述了客戶端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);
...
獲取檔案的名稱與大小
- 這是檔案的名稱,是字串型別。這個值與File.getName()方法返回的值相等。
- 這是檔案的大小,以位元組形式呈現,是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)));