Android官方开发文档Training系列课程中文版:分享文件之请求一个共享文件
原文地址:http://android.xsoftlab.net/training/secure-file-sharing/request-file.html
當APP需要訪問一個被其它APP所共享的文件時,這個APP通常需要發送一個請求給共享文件的那個APP(服務端),在大多數的情況下,這個請求會啟動一個服務端的Activity,這個Activity會展示可以共享的文件。用戶可以選擇一個文件,稍后服務端APP會將這個文件以URI的形式返回給客戶端APP。
這節課展示了客戶端APP如何向服務端APP請求一個共享文件,以及從服務端APP接收這個URI,和通過這個URI打開被選中的文件。
發送文件請求
如果要請求服務端的文件,客戶端APP需要調用startActivityForResult方法并傳入一個Intent對象,這個Intent對象包含了一個行為比如ACTION_PICK以及一個MIME類型,這個類型是指客戶端APP可以處理的類型。
舉個例子,下面這段代碼演示了如何發送一個Intent給服務端APP并啟動展示共享文件的那個Activity:
public class MainActivity extends Activity {private Intent mRequestFileIntent;private ParcelFileDescriptor mInputPFD;...@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mRequestFileIntent = new Intent(Intent.ACTION_PICK);mRequestFileIntent.setType("image/jpg");...}...protected void requestFile() {/*** When the user requests a file, send an Intent to the* server app.* files.*/startActivityForResult(mRequestFileIntent, 0);...}... }訪問請求到的文件
服務端給客戶端返回了一個帶有文件URI的Intent。這個Intent會從客戶端中的onActivityResult()方法返回。一旦客戶端有了這個文件的URI,那么它就可以通過FileDescriptor來訪問這個文件。
在這個過程中,文件的安全性一直被保留,因為客戶端接收到的URI只是數據的一部分。既然這個URI沒有包含目錄路徑,那么客戶端APP不可能發現并打開任何服務端上的任何其它文件。只有客戶端APP可以訪問文件,且僅僅是由服務器APP授予的權限。這個權限是個臨時的權限,所以一旦客戶端APP的任務終止,那么這個文件就不可被服務端APP之外的地方所訪問。
下面這段代碼演示了客戶端APP如何處理從服務端返回的Intent,以及如何使用URI來獲得FileDescriptor對象:
/** When the Activity of the app that hosts files sets a result and calls* finish(), this method is invoked. The returned Intent contains the* content URI of a selected file. The result code indicates if the* selection worked or not.*/@Overridepublic void onActivityResult(int requestCode, int resultCode,Intent returnIntent) {// If the selection didn't workif (resultCode != RESULT_OK) {// Exit without doing anything elsereturn;} else {// Get the file's content URI from the incoming IntentUri returnUri = returnIntent.getData();/** Try to open the file for "read" access using the* returned URI. If the file isn't found, write to the* error log and return.*/try {/** Get the content resolver instance for this context, and use it* to get a ParcelFileDescriptor for the file.*/mInputPFD = getContentResolver().openFileDescriptor(returnUri, "r");} catch (FileNotFoundException e) {e.printStackTrace();Log.e("MainActivity", "File not found.");return;}// Get a regular file descriptor for the fileFileDescriptor fd = mInputPFD.getFileDescriptor();...}}方法openFileDescriptor()返回了一個文件的ParcelFileDescriptor對象。客戶端APP可以根據這個對象得到FileDescriptor對象,這個對象便可以用來讀取文件了。
總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:分享文件之请求一个共享文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: Android官方开发文档Trainin