注:本文翻譯自Google官方的Android Developers Training文檔,譯者技術(shù)一般,由于喜愛安卓而產(chǎn)生了翻譯的念頭,純屬個人興趣愛好。
原文鏈接: http://developer.android.com/training/secure-file-sharing/retrieve-info.html
當一個客戶端應(yīng)用嘗試對一個有URI的文件進行操作時,應(yīng)用可以向服務(wù)應(yīng)用索取關(guān)于文件的信息,包括文件的數(shù)據(jù)類型和文件大小。數(shù)據(jù)類型可以幫助客戶應(yīng)用確定該文件自己能否處理,文件大小能幫助客戶應(yīng)用為文件設(shè)置合理的緩沖區(qū)。
這節(jié)課將展示如何通過查詢服務(wù)應(yīng)用的 FileProvider 來獲取文件的MIME類型和尺寸。
一). 獲取文件的MIME類型
一個文件的數(shù)據(jù)類型能夠告知客戶應(yīng)用應(yīng)該如何處理這個文件的內(nèi)容。為了得到URI所對應(yīng)文件的數(shù)據(jù)類型,客戶應(yīng)用調(diào)用 ContentResolver.getType() 。這個方法返回了文件的MIME類型。默認的,一個 FileProvider 通過文件的后綴名來確定其MIME類型。
下面的代碼展示了一個客戶應(yīng)用如何在服務(wù)應(yīng)用返回了文件的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() 方法的實現(xiàn),它返回一個 Cursor ,它包含了URI所關(guān)聯(lián)的文件的名字和尺寸。默認的實現(xiàn)返回兩列:
是文件的文件名,一個 String 。這個值和 File.getName() 所返回的值是一樣的。
SIZE
:
文件的大小,字節(jié)為單位,一個“l(fā)ong”型。這個值和 File.length() 所返回的值是一樣的。
客戶端應(yīng)用可以通過將 query() 的參數(shù)都設(shè)置為“ null ”,值保留URI這一參數(shù),來同時獲取文件的名字和尺寸。例如,下面的代碼獲取一個文件的名稱和大小,然后在兩個 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)));
...
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

