我试图与Android Studio中的应用程序,可以选择在SD卡中的文件,并得到其路径,像一个OpenFileDialog
,我已经试过这样:如何挑选SD卡中的文件?
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
但是,这是行不通的,我该怎么做 ?
我试图与Android Studio中的应用程序,可以选择在SD卡中的文件,并得到其路径,像一个OpenFileDialog
,我已经试过这样:如何挑选SD卡中的文件?
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
但是,这是行不通的,我该怎么做 ?
STEP 1 - 使用隐含的意图:
要选择从设备中的文件,你应该使用一个implicit Intent
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, PICKFILE_RESULT_CODE);
第2步 - 获取文件的绝对路径:
要从Uri获取文件路径,请首先尝试使用
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uri = data.getData();
String src = uri.getPath();
// this is path of your selected file
// if you get error or invalid path try below method and call like getPath(uri);
}
其中数据在onActivityResult().
如果不工作(错误或无效URL)的意向返回,使用下面的方法:
public String getPath(Uri uri) {
String path = null;
String[] projection = { MediaStore.Files.FileColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor == null){
path = uri.getPath()
}
else{
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(column_index);
cursor.close();
}
return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
}
试试这个:
Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT);
mediaIntent.setType("*/*"); //set mime type as per requirement
startActivityForResult(mediaIntent,0);
您可以根据需要更改类型。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0
&& resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
Log.d("", "Video URI= " + videoUri);
}
}
参见[这个答案](https://stackoverflow.com/a/30827530/3681880) – Suragch