我正试图在一个以Android Q为目标的项目中实现从相机拍照。
val mediaFile = mediaManager.createImageFile() // creates a file to store the image and returns Uri
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
type = MIME_TYPE_IMAGE //"image/*"
intent.putExtra(MediaStore.EXTRA_OUTPUT, mediaFile)
}
startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO)
createImageFile:
override fun createImageFile(): Uri? {
return createFile(mimeType = MIME_IMAGE_JPG, isImage = true)
}
private fun createFile(mimeType: String, isImage: Boolean): Uri? {
val mediaFileName = createTempName()
val path = if (isImage) {
Environment.DIRECTORY_PICTURES
} else {
Environment.DIRECTORY_MOVIES
}
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, mediaFileName)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, path)
}
val resolver = context.contentResolver
val contentUri = if (isImage) {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else {
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
return resolver.insert(contentUri, contentValues)
}
然而,我得到的是 android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.media.action.IMAGE_CAPTURE typ=image/* flg=0x3 clip={text/uri-list U:content://media/external/images/media/109855} (has extras) }
我找了几个小时,并按所说的做了所有的事情,但仍然没有任何收获.有趣的是。createImageFile()
返回 null
三星Galaxy S8(上帝,我讨厌三星,它总是一些特殊情况下的那些).我在这里做错了什么?
摄像机上的MIME类型 Intent
构成了确定哪些活动有意义的标准的一部分。<intent-filter>
吻合 Intent
. 添加一个MIME类型在一个 Intent
在MIME类型出乎意料的情况下,会导致你所看到的问题。
在 ACTION_IMAGE_CAPTURE
文件 没有说要在请求中提供 MIME 类型。因此,相机应用程序与 ACTION_IMAGE_CAPTURE
<intent-filter>
结构不会宣传它们支持任何特定的MIME类型。因此,当Android试图为你的 Intent
,结果是空的。
所以,去掉MIME类型来清除 ActivityNotFoundException
.