请求分享一个文件

    当一个应用程序希望访问由其它应用程序所共享的文件时,请求应用程序(客户端)经常会向其它应用程序(服务端)发送一个文件请求。多数情况下,该请求会导致在服务端应用程序中启动一个Activity,该Activity中会显示可以共享的文件。当服务端应用程序向客户端应用程序返回了文件的Content URI后,用户即可开始选择文件。

    本课将展示一个客户端应用程序应该如何向服务端应用程序请求一个文件,接收服务端应用程序发来的Content URI,然后使用这个Content URI打开这个文件。

    例如,下面的代码展示了如何向服务端应用程序发送一个Intent,来启动在分享文件中提到的:

    访问请求的文件

    当服务端应用程序向客户端应用程序发回包含Content URI的时,该Intent会传递给客户端应用程序重写的方法当中。一旦客户端应用程序拥有了文件的Content URI,它就可以通过获取其FileDescriptor访问文件了。

    下面的例子展示了客户端应用程序应该如何处理发自服务端应用程序的,以及客户端应用程序如何使用Content URI获取FileDescriptor

    1. * When the Activity of the app that hosts files sets a result and calls
    2. * finish(), this method is invoked. The returned Intent contains the
    3. * content URI of a selected file. The result code indicates if the
    4. * selection worked or not.
    5. */
    6. @Override
    7. public void onActivityResult(int requestCode, int resultCode,
    8. Intent returnIntent) {
    9. // If the selection didn't work
    10. // Exit without doing anything else
    11. } else {
    12. // Get the file's content URI from the incoming Intent
    13. Uri returnUri = returnIntent.getData();
    14. /*
    15. * Try to open the file for "read" access using the
    16. * returned URI. If the file isn't found, write to the
    17. * error log and return.
    18. */
    19. try {
    20. /*
    21. */
    22. mInputPFD = getContentResolver().openFileDescriptor(returnUri, "r");
    23. } catch (FileNotFoundException e) {
    24. e.printStackTrace();
    25. Log.e("MainActivity", "File not found.");
    26. return;
    27. }
    28. // Get a regular file descriptor for the file
    29. FileDescriptor fd = mInputPFD.getFileDescriptor();
    30. ...
    31. }

    方法返回一个文件的ParcelFileDescriptor对象。客户端应用程序从该对象中获取对象,然后利用该对象读取这个文件了。