android - 如何从文本文件中获取 URI?

标签 android android-intent kotlin uri mediastore

我这样做是为了获取并显示图像的路径,但我想知道如何对文本文件执行相同的操作。

val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, SELECT_IMAGE)

最佳答案

我觉得你可以试试

 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;
}

关于android - 如何从文本文件中获取 URI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054458/

相关文章:

android - overridePendingTransition 不适用于 android 2.3.5

android - 使用 Intent 或事件总线在同一个应用程序中进行通信

Android:了解 Intent 过滤器

kotlin - 通用接口(interface)继承

android - 在同一水平线上点亮两个按钮

android - 附加/分离与替换 fragment

Android GCM putExtra 打开 Intent

Android - 未找到处理 Intent 的 Activity { act=android.intent.action.VIEW - 尝试打开 PDF 文件

java - Python 客户端不接收来自 Spring websocket 服务器的消息

java - 如何使用 Kotlin 扩展 Java 类以像 static fun 一样使用?