在 android 10 内用相机拍照

Take picture with camera in android 10

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

编辑: 在本文中: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)
}

我有两个问题:

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

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

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

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