android - 在 Android 10 中使用相机拍照

标签 android android-camera android-10.0

随着 Android 10 中与范围存储相关的所有更改,我们如何打开相机。我看到一些教程建议使用文件提供程序,但我不太明白。 您能否提供一段代码来启动相机 Intent 并接收拍摄的图像?

编辑: 在本文中: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 范围存储?

最佳答案

What does this line do : it.putExtra("return-data", true)

通常没什么。某些相机应用程序可能会在收到此未记录且(通常)不受支持的 Intent 额外信息时执行某些操作。

in OnActivityResulty, why didn't he just use the uri directly

在之前的步骤中,他做到了。最后,他想使用 uCrop 来允许用户裁剪图像。也许他想保留原始照片和裁剪后的照片。

关于android - 在 Android 10 中使用相机拍照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61396019/

相关文章:

android - Toast 未在 Android Q 中显示

java - 为什么我的 Activity 无法启动?

Android 3.x EditText 光标颜色

java - 更改数组中的值不会传播到应用程序中

javascript - Titanium:从 Android 的相机/图库图像本地保存文件

java - Android camera2 镜头本征校准

permissions - queryPermissionsByGroup 在 android Q 上返回 null

android - 面向 29 的 WebView 未显示内容

java - 如何在 TextView 中最后一次更改后的某个时间调用函数?

android - 拍照后返回按钮不起作用