和其他App分享文件(3)请求一个共享文件
2015-01-06 14:34
288 查看
这小节主要是展示一个客户端如何从一个服务端App请求一个文件,接收服务端App文件content URI,最后使用content URI 打开文件。
发送一个文件请求
客户端调用带有action为 ACTION_PICK 和客户端可以处理的MIME类型等的
下面的小片段代码展示的是客户端App如何处理服务端传递过来的Intent,并且客户端使用content URI 获得
发送一个文件请求
客户端调用带有action为 ACTION_PICK 和客户端可以处理的MIME类型等的
Intent的startActivityForResult()方法。
例子如下:
public class MainActivity extends Activity { private Intent mRequestFileIntent; private ParcelFileDescriptor mInputPFD; ... @Override protected 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); ... } ... }访问请求文件
下面的小片段代码展示的是客户端App如何处理服务端传递过来的Intent,并且客户端使用content 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. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent returnIntent) { // If the selection didn't work if (resultCode != RESULT_OK) { // Exit without doing anything else return; } else { // Get the file's content URI from the incoming Intent Uri 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 file FileDescriptor fd = mInputPFD.getFileDescriptor(); ... } }
openFileDescriptor() 烦hi一个文件的 ParcelFileDescriptor 对象。客户端通过这个对象得到 FileDescriptor可以读取文件的对象。
相关文章推荐
- 和其他App分享文件(1)设置文件共享
- Android官方开发文档Training系列课程中文版:分享文件之请求一个共享文件
- 和其他App分享文件(4)获取文件信息
- 背水一战 Windows 10 (101) - 应用间通信: 通过协议打开指定的 app 并传递数据以及获取返回数据, 将本 app 沙盒内的文件共享给其他 app 使用
- 请求分享一个文件
- Google Android开发者文档系列-创建有内容分享特性的应用之请求共享文件
- 【iOS_GitHub】文档/文件查看器(支持本地或者其他app分享过来的word、excel、pdf、rtf等格式文件)
- 和其他App分享简单的数据(3)添加一个简单的分享Action
- 和其他App分享文件(2)共享一个文件(内部文件也是可以共享的哦)
- 将本地的一个文件目录复制/移动到局域网上的其他机器上的方法
- 发布网站后,会生成一个PrecompiledApp.config文件的作用
- VSTS中如何ignore一个app.config之类的文件
- 分享一个格式化文件大小的 C# 方法(转)
- 一个共享XP、2003上文件与打印机简单易行的方法
- 本人刚刚写的一个bat文件,是可以删除系统的默认共享
- 多个 JS 文件共享一个命名空间
- 推荐Dropbox一个很不错的文件存储和共享服务
- 分享一个.NET版的多选文件上传操作示例
- Firefox添加web浏览端口 "此地址访问受限 此地址使用了一个通常应该用于其他网页浏览的端口。由于安全原因,Firefox 取消了该请求。"
- 分享一个好东东,动态Include文件 (Dynamic File Includes)