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

Vin*_*ani 6 file-manager android-intent mime-types

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

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

为此,我使用此代码 -

    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, REQUEST_CODE_IMAGE_PICKER_INTENT);
Run Code Online (Sandbox Code Playgroud)

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

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

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

Vin*_*ani 21

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

获取mime类型的内容uri -

    ContentResolver cr = this.getContentResolver();
    String mime = cr.getType(YOUR_CONTENT_URI);
Run Code Online (Sandbox Code Playgroud)

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

  • 我在我的 `onActivityResult()` 中尝试了同样的方法,但是 `getType(data.getData())` 返回 null (2认同)

Xar*_*mer 6

如果你有URI那么你可以得到像mimetype

Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
String mime = cR.getType(uri);
Run Code Online (Sandbox Code Playgroud)

或尝试// 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;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅这些答案