确定意图返回的android中的uri的Mime类型?

时间:2013-03-23 14:27:52

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

首先介绍一下我想要实现的目标 -

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

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

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

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

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

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

2 个答案:

答案 0 :(得分:20)

我找到了一种获取内容uri的mime类型的方法,但是没有其他类型的uri可用,例如'file:// .....'形式的uri。

获取mime类型的内容uri -

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

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

答案 1 :(得分:5)

  

如果您有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