我创建了一个示例here以重现此问题。我正在使用API级别29的模拟器上运行此项目,并从google照片提供程序中选择一个视频。但是我不知道如何获取所选文件的mimeType。我使用了ContentResolver的getType方法(该方法返回null)以及ContentResolver查询方法(以某种方式向我抛出IllegalArgumentException)。我已经附上了相同的屏幕截图。
注意:如果我通过浏览目录选择相同的文件,则一切正常,但是当我使用google photos provider时,它将失败。
这是我的代码::
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK && requestCode == IMAGE_VIDEO_FETCH) {
Uri selectedFileURI = intent.getData();
String type = this.getContentResolver().getType(selectedFileURI);
if (type == null || TextUtils.isEmpty(type)) {
// This shouldn't happen right?
// Since https://developer.android.com/training/secure-file-sharing/retrieve-info
// mentions a FileProvider determines the file's MIME type from its filename extension. I've to add this block
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedFileURI, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int colIndex = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
type = cursor.getString(colIndex);
}
} catch (IllegalArgumentException e) {
Log.d("Check Type :: ", type + "");
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
} else {
Log.d("Type:: ", type + "");
}
}
}
这就是我开始意图的方式::
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/*");
startActivityForResult(i, IMAGE_VIDEO_FETCH);
谁能以正确的方式帮助我找出所选文件的模仿类型吗?PS:我已经尝试过ContentResolver.getType,MimeTypeMap和ContentResolver.query。它们都不起作用。
我浪费了几天的时间试图找出问题所在。不幸的是,事实证明这是Google照片4.17版中的一个错误,该错误似乎在4.32版中已修复]
这里是链接的Google问题https://issuetracker.google.com/issues/149416521
这是我用来获取MimeType的内容:不幸的是,它在Kotlin中,但是让我们尝试更好地使用Kotlin。
@SuppressLint("DefaultLocale")
fun getMimeType(uri: Uri): String {
val mimeType: String
mimeType = if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
// Replace MyApplication.getInstance() by your context
val cr = MyApplication.getInstance().contentResolver
cr.getType(uri).toString()
} else {
val fileExtension = MimeTypeMap.getFileExtensionFromUrl(
uri
.toString()
)
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase()
).toString()
}
return mimeType
}
我希望有帮助!