我这样做是为了获取并显示图像的路径,但是我想知道如何处理文本文件。
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, SELECT_IMAGE)
答案 0 :(得分:1)
我认为您可以尝试
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
获得uri
@Override
protected void onActivityResult(..., Intent data) {
//do your validation
switch (requestCode) {
case PICKFILE_RESULT_CODE:
...
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
try {
Log.d(TAG, "File path: " + getPath(this, uri));
} catch (URISyntaxException e) {
e.printStackTrace();
}
//do your work
...
break;
}
}
添加实用程序
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}