你试过这个吗?它适用于我(仅适用于图像文件)。
public static String getMimeTypeOfUri(Context context, Uri uri) {
BitmapFactory.Options opt = new BitmapFactory.Options();
/* The doc says that if inJustDecodeBounds set to true, the decoder
* will return null (no bitmap), but the out... fields will still be
* set, allowing the caller to query the bitmap without having to
* allocate the memory for its pixels. */
opt.inJustDecodeBounds = true;
InputStream istream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(istream, null, opt);
istream.close();
return opt.outMimeType;
}
当然你也可以使用其他方法,比如BitmapFactory.decodeFile
或者BitmapFactory.decodeResource
像这样:
public static String getMimeTypeOfFile(String pathName) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, opt);
return opt.outMimeType;
}
如果无法确定 MIME 类型,它将返回 null。