1. 程式人生 > >Android檔案共享之檢索檔案資訊

Android檔案共享之檢索檔案資訊

在客戶端應用程式嘗試使用具有內容URI的檔案之前,應用程式可以從伺服器應用程式請求有關檔案的資訊,包括檔案的資料型別和檔案大小。資料型別幫助客戶端應用程式確定它是否可以處理檔案,檔案大小有助於客戶端應用程式為檔案設定緩衝和快取。

本課程演示如何查詢伺服器應用程式的FileProvider以檢索檔案的MIME型別和大小。

檢索檔案的MIME型別

檔案的資料型別向客戶端應用程式指示它應如何處理檔案的內容。要獲取共享檔案的資料型別給定其內容URI,客戶端應用程式呼叫ContentResolver.getType()。此方法返回檔案的MIME型別。預設情況下,FileProvider從副檔名確定檔案的MIME型別。

以下程式碼段演示了在伺服器應用程式將內容URI返回給客戶端後,客戶端應用程式如何檢索檔案的MIME型別:

  ...
    /*
     *從傳入的Intent獲取檔案的內容URI,然後
     *獲取檔案的MIME型別
     */
    Uri returnUri = returnIntent.getData();
    String mimeType = getContentResolver().getType(returnUri);
    ...

檢索檔案的名稱和大小

FileProvider類具有query()方法的預設實現,該方法返回與游標(Cursor)中的內容URI相關聯的檔案的名稱和大小。預設實現返回兩列:

DISPLAY_NAME

  • 檔案的名稱,String。此值與File.getName()返回的值相同。

SIZE

  • 檔案的大小(以位元組為單位),long,此值與File.length()返回的值相同。

通過將query()的所有引數設定為null(除了內容URI),客戶端應用程式可以獲取檔案的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))); ...