我花了几个小时研究这个问题,但我没有找到解决方案(在StackOverflow或其他方面)。我的应用程序的目标是API 30,明斯克版本是29。我正在学习以下教程:https://developer.android.com/training/camera/photobasics
我的activity上有一个按钮,它可以通过一个意图打开相机:
fun takePhoto() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.resolveActivity(packageManager)?.also {
startActivityForResult(takePictureIntent, CAMERA_REQUEST)
}
}
}
但我还想将图片保存在设备库上。因此我将TakePhoto()
方法更改为:
fun takePhoto() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.resolveActivity(packageManager)?.also {
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
ex.printStackTrace()
null
}
photoFile?.also {
try {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"net.filiperamos.photogrid.provider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "Could not get file URI.")
ex.printStackTrace()
}
startActivityForResult(takePictureIntent, CAMERA_REQUEST)
}
}
}
}
并添加了CreateImageFile()
方法:
private fun createImageFile(): File {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
val filename = "image_$timeStamp"
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(filename, ".jpg", storageDir).apply {
currentPhotoPath = absolutePath // Save path for later use
}
}
我的舱单具有相机使用和外部写入权限:
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我添加了一个独立于应用程序标记的提供者:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
并创建了file_paths.xml
:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="my_images"
path="Android/data/net.ramos.photos/files/Pictures/" />
</paths>
当我在设备上运行此代码时,在运行FileProvider.GetUriForFile()
时会出现异常:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/net.ramos.photos/files/Pictures/image_20200823_1415398042919497737944663.jpg
如果更改file_paths.xml
文件,将external-files-path
替换为external-path
,则错误会消失,但图像不会存储在任何地方。
我错过了什么?
在清单文件中添加以下行作为'application'标记的属性,
android:requestLegacyExternalStorage="true"
这应该可以解决您面临的问题,并且例外应该会消失。