【问题标题】:Determine Mime type of a uri in android returned by an intent?确定意图返回的android中uri的Mime类型?
【发布时间】:2013-03-13 08:16:00
【问题描述】:

首先是我想要实现的一些背景 -

我正在开发一个图像共享应用程序,我需要用户从文件系统中选择一个图像。

为此,我正在使用此代码 -

    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, REQUEST_CODE_IMAGE_PICKER_INTENT);

现在,这会触发一个选择器,其中我会看到多个选项,包括我手机中的 Gallery 和 FileManager App。如果我选择画廊并从那里选择一个图像,那么我的活动会收到一个带有图像内容 uri 的意图。 但如果我选择 FileManager App,我可以选择任何可能不是图像的文件。所以,我需要的是能够确定意图中返回的 uri 的 mime 类型。 Intent 的 getType 方法返回 null 。

有没有办法从返回的意图中确定 mime 以确定内容是否为图像。

如果这不起作用,那么我可能不得不使用 MimeTypeMap 从文件扩展名中确定 mime。

【问题讨论】:

    标签: android-intent mime-types file-manager


    【解决方案1】:

    我找到了一种获取内容 uri 的 mime 类型的方法,但对于其他类型的 uri,例如 'file://.....' 形式的 uri,没有任何效果。

    获取内容 uri 的 mime 类型 -

        ContentResolver cr = this.getContentResolver();
        String mime = cr.getType(YOUR_CONTENT_URI);
    

    这仅适用于内容 uri。因此,对于其他 uri,我使用 MimeTypeMap 从文件扩展名推断他们的 mime 类型。

    【讨论】:

    • 我在onActivityResult() 中尝试了同样的方法,但getType(data.getData()) 让我返回null
    【解决方案2】:

    如果你有 URI,那么你可以得到类似的 mimetype

    Uri uri = Uri.fromFile(file);
    ContentResolver cR = context.getContentResolver();
    String mime = cR.getType(uri);
    

    或者试试 // url = 文件路径或任何你想要的合适的 URL。

    public static String getMimeType(String url)
    {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }
        return type;
    }
    

    更多详情see these Answers

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2014-08-19
      • 2011-07-10
      • 2012-01-25
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多