Android中调用文件管理器并返回选中文件的路径
实际项目中经常需要调用文件管理器,选择下载路径或者上传的本地文件路径。今天就给大家做个demo示范该功能的实现过程。
一、实现效果预览

二、代码实现
package com.panhouye.selectfile; import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends AppCompatActivity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.setType(“image/*”);//选择图片
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//intent.setType(“video/*;image/*”);//同时选择视频和图片
intent.setType("*/*");//无类型限制
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1);
}
});
}
String path;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
path = uri.getPath();
tv.setText(path);
Toast.makeText(this,path+"11111",Toast.LENGTH_SHORT).show();
return;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
path = getPath(this, uri);
tv.setText(path);
Toast.makeText(this,path,Toast.LENGTH_SHORT).show();
} else {//4.4以下下系统调用方法
path = getRealPathFromURI(uri);
tv.setText(path);
Toast.makeText(MainActivity.this, path+"222222", Toast.LENGTH_SHORT).show();
}
}
} public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(null!=cursor&&cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
cursor.close();
}
return res;
} /**
* 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
*/
@SuppressLint("NewApi")
public String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0]; if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0]; Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]}; return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
} /**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) { Cursor cursor = null;
final String column = "_data";
final String[] projection = {column}; try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
} /**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
三、小结
Android中调用文件管理器并返回选中文件的路径的更多相关文章
- 关于android中调用系统拍照,返回图片是旋转90度
转载博客:http://blog.csdn.net/walker02/article/details/8211628 项目开发中遇到的一个问题,对于三星手机在做手机照片选择时出现图片显示不正常,研究后 ...
- [转]C#中调用资源管理器(Explorer.exe)打开指定文件夹 + 并选中指定文件 + 调用(系统默认的播放类)软件(如WMP)打开(播放歌曲等)文件
原文:http://www.crifan.com/csharp_call_explorer_to_open_destinate_folder_and_select_specific_file/ C#中 ...
- 在Android中调用WebService
某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互,有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查.我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数 ...
- 【转】Android 学习笔记——利用JNI技术在Android中调用、调试C++代码
原文网址:http://cherishlc.iteye.com/blog/1756762 在Android中调用C++其实就是在Java中调用C++代码,只是在windows下编译生成DLL,在And ...
- [转][android][利用JNI技术在Android中调用、调试C++代码]
在Android中调用C++其实就是在Java中调用C++代码,只是在windows下编译生成DLL,在Android中会生成Linux系统下的.so文件(好吧,其实我基本没用过Linux). 没写过 ...
- 在Android中调用C#写的WebService(附源代码)
由于项目中要使用Android调用C#写的WebService,于是便有了这篇文章.在学习的过程中,发现在C#中直接调用WebService方便得多,直接添加一个引用,便可以直接使用将WebServi ...
- Java乔晓松-android中调用系统拍照功能并显示拍照的图片
android中调用系统拍照功能并显示拍照的图片 如果你是拍照完,利用onActivityResult获取data数据,把data数据转换成Bitmap数据,这样获取到的图片,是拍照的照片的缩略图 代 ...
- Android 中调用本地命令
Android 中调用本地命令 通常来说,在 Android 中调用本地的命令的话,一般有以下 3 种情况: 调用下也就得了,不管输出的信息,比如:echo Hello World.通常来说,这种命令 ...
- Android中调用C++函数的一个简单Demo
这里我不想多解释什么,对于什么JNI和NDK的相关内容大家自己去百度或谷歌.我对Android的学习也只是个新手.废话少说直接进入正题. 一.在Eclipse中创建一个Android Applicat ...
随机推荐
- 解决VS2015 VBCSCompiler.exe 占用CPU100%的问题
使用VS2015重复编译运行会发现系统运行缓慢甚至卡死,打开windows任务管理器可以发现CPU已经飙到了100%, VBCSCompiler.exe进程出现多个实例并且占用了大量CPU. 解决方案 ...
- Ajax基础与登入
Ajax 是 Asynchronous JavaScript and XML的缩写. Ajax的优点: 优点:减轻服务器的负担,按需取数据,最大程度的减少冗余请求 局部刷新页面,减少用户心理和实际的等 ...
- kali linux /etc/apt/source.list
this list is very important , you can not download what you want like fictx , flash-plugin , vm-tool ...
- Java数据类型及其转换&&经常用到的快捷键
数据类型 基本数据类型分类 (8种) byte .short. int. long. char. float. double .boolean 1个字节占8位 整数型byte 1字节 -128~1 ...
- Eclipse 中svn 分支,主干 合并与同步:
Eclipse 中svn的合并与同步: 1. 从主干拉取到分支: 然后一直下一步,到完成就OK了. 2. 从分支代码合并到主干: 2.1.先将本地需要提交更新的代码提交更新到svn分支去 2.2. ...
- keepalived工作原理
keepalived是一个类似于Layer2,4,7交换机制的软件.是Linux集群管理中保证集群高可用的一个服务软件,其功能是用来防止单点故障. keepalived的工作原理: ...
- system()、exec()、fork()三个与进程有关的函数的比较
启动新进程(system函数) system()函数可以启动一个新的进程. int system (const char *string ) 这个函数的效果就相当于执行sh –c string. 一般 ...
- CSS中清除浮动的方法
CSS浮动,最早是为了达到文字环绕的效果提出的,也可以用来做布局,但是布局会产生很多问题(高度塌陷,漂浮在普通流上),会使当前标签产生上浮的效果,会影响前后标签,同样的代码在不同的浏览器的兼容性也不一 ...
- Jmeter新建用例图示
添加线程组 添加HTTP请求 编辑HTTP请求 添加HTTP信息头 编辑HTTP信息头 添加断言 添加查看结果树 添加聚合报告 添加响应时间 添加TPS 批量运行命令: ...
- lucene原理及源码解析--核心类
马云说:大家还没搞清PC时代的时候,移动互联网来了,还没搞清移动互联网的时候,大数据时代来了. 然而,我看到的是:在PC时代搞PC的,移动互联网时代搞移动互联网的,大数据时代搞大数据的,都是同一伙儿人 ...