編寫:jdneo - 原文:http://developer.android.com/training/secure-file-sharing/retrieve-info.html
當一個客戶端應(yīng)用程序擁有了文件的Content URI之后,它就可以獲取該文件并進行下一步的工作了,但在此之前,客戶端應(yīng)用程序還可以向服務(wù)端應(yīng)用程序獲取關(guān)于文件的信息,包括文件的數(shù)據(jù)類型和文件大小等等。數(shù)據(jù)類型可以幫助客戶端應(yīng)用程序確定自己能否處理該文件,文件大小能幫助客戶端應(yīng)用程序為文件設(shè)置合理的緩沖區(qū)。
本課將展示如何通過查詢服務(wù)端應(yīng)用程序的FileProvider來獲取文件的MIME類型和文件大小。
客戶端應(yīng)用程序可以通過文件的數(shù)據(jù)類型判斷自己應(yīng)該如何處理這個文件的內(nèi)容。客戶端應(yīng)用程序可以通過調(diào)用ContentResolver.getType()方法獲得Content URI所對應(yīng)的文件數(shù)據(jù)類型。該方法返回文件的MIME類型。默認情況下,一個FileProvider通過文件的后綴名來確定其MIME類型。
下例展示了當服務(wù)端應(yīng)用程序?qū)ontent URI返回給客戶端應(yīng)用程序后,客戶端應(yīng)用程序應(yīng)該如何獲取文件的MIMIE類型:
...
/*
* 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()方法的默認實現(xiàn),它返回一個Cursor對象,該Cursor對象包含了Content URI所關(guān)聯(lián)的文件的名稱和大小。默認的實現(xiàn)返回下面兩列信息:
文件名,String類型。這個值和File.getName()所返回的值一樣。
文件大小,以字節(jié)為單位,long類型。這個值和File.length()所返回的值一樣。
客戶端應(yīng)用可以通過將query()的除了Content URI之外的其他參數(shù)都設(shè)置為“null”,來同時獲取文件的名稱(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)));
...