原文鏈接:Retrieving File Information
本課程教你:
- 獲取文件的MIME類型
- 獲取文件的名字和大小
在一個客戶端應(yīng)用嘗試使用content URI讀寫文件之前,這個應(yīng)用可以從服務(wù)端應(yīng)用獲取關(guān)于這個文件的信息溃论,包括文件的數(shù)據(jù)類型和大小屎蜓。文件類型幫助客戶端應(yīng)用判斷它是否能處理這個文件;文件的大小幫助客戶端應(yīng)用對這個文件設(shè)置緩沖和緩存钥勋。
本課程展示了如何向服務(wù)端應(yīng)用的 FileProvider 獲取它的文件的MIME類型和大小炬转。
獲取文件的MIME類型
一個文件的數(shù)據(jù)類型會指導(dǎo)客戶端應(yīng)用該怎么處理這個文件的內(nèi)容。為了獲取content URI代表的文件的數(shù)據(jù)類型算灸,客戶端應(yīng)用調(diào)用 ContentResolver.getType()扼劈。這個方法返回文件的MIME類型。默認(rèn)情況下菲驴,一個 FileProvider 根據(jù)這個文件的擴(kuò)展名決定這個文件的MIME類型荐吵。
下面這段代碼展示了一個客戶端應(yīng)用如何從服務(wù)端應(yīng)用返回的content 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 類擴(kuò)展了 [query()](https://developer.android.com/reference/android/support/v4/content/FileProvider.html#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)) 方法在 Cursor 中默認(rèn)返回與content URI對應(yīng)的文件的名字和大小。默認(rèn)實(shí)現(xiàn)方法有兩欄:
DISPLAY_NAME
字符串形式的文件名赊瞬。這個值與通過 File.getName() 返回的值保持一致先煎。
SIZE
文件字節(jié)的大小,以long
形式返回森逮。這個值與 File.length() 返回的值保持一致榨婆。
客戶端應(yīng)用通過在 [query()](https://developer.android.com/reference/android/support/v4/content/FileProvider.html#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)) 中設(shè)置除了content URI之外的其他值為null
,能夠獲取到文件的 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)));
...