【发布时间】:2020-04-23 20:04:36
【问题描述】:
随着 android 10 中与范围存储相关的所有更改,我们如何打开相机。我看到了一些建议使用文件提供程序的教程,但我不太明白。 您能否提供一段代码来启动相机意图并接收拍摄的图像?
编辑: 在这篇文章中:https://medium.com/@arkapp/accessing-images-on-android-10-scoped-storage-bbe65160c3f4 他提供了这段代码:
fun takePicture(context: Activity, imageName: String) {try {
val capturedImgFile = File(
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
imageName)
captureImgUri = FileProvider.getUriForFile(
context,
context.applicationContext.packageName + ".my.package.name.provider",
capturedImgFile)val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).also {
it.putExtra(MediaStore.EXTRA_OUTPUT, captureImgUri)
it.putExtra("return-data", true)
it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivityForResult(it, REQUEST_CODE_TAKE_PICTURE)
}
} catch (e: ActivityNotFoundException) {e.printStackTrace()}
}@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {return}
if (requestCode == REQUEST_CODE_TAKE_PICTURE) {
/*We cannot access the image directly so we again create a new File at different location and use it for futher processing.*/
Bitmap capturedBitmap = getBitmap(this, captureImgUri)
/*We are storing the above bitmap at different location where we can access it.*/ val capturedImgFile = File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES),
getTimestamp() + "_capturedImg.jpg"); convertBitmaptoFile(capturedImgFile, capturedBitmap)/*We have to again create a new file where we will save the processed image.*/ val croppedImgFile = File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES),
getTimestamp() + "_croppedImg.jpg"); startCrop(
this,
Uri.fromFile(capturedImgFile),
Uri.fromFile(croppedImgFile))}
super.onActivityResult(requestCode, resultCode, data)
}
我有两个问题:
- 这条线有什么作用: it.putExtra("return-data", true)
- 在OnActivityResulty中,他为什么不直接使用uri,他先创建了一个文件,然后将文件解析成一个uri,这是干什么用的? android 10 scoped storage 怎么做?
【问题讨论】:
-
我编辑了这个问题,因为在那篇媒体文章中,他真的让我很困惑,你能解释一下他为什么做那些事情吗?
标签: android android-camera android-10.0