如何使用Java检查Android中的Activity Intent中是否捕获了图像

问题描述 投票:0回答:1

我正在使用 Java 编写 Android 应用程序。我有一个使用活动意图来捕获图像文件的功能。我想如何以编程方式检查图像文件是否被捕获。

我的功能:

private void launchTakeImageWithCameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    File imageFile = createTemporaryWritableImageFile();
    path = imageFile.getPath();

    Uri imageUri = Uri.fromFile(imageFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    grantUriPermissions(intent, imageUri);

    try {
      activity.startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_ID);  // <-- how to check if the image file is captured or not?
    } catch (ActivityNotFoundException e) {
      try {
        if (!imageFile.delete()) {
          throw new RuntimeException("failed to delete image file.");
        }
      } catch (SecurityException exception) {
        exception.printStackTrace();
      }
      result.error(
          "no_available_activity",
          "no camera available for taking picture.",
          null
      );
    }
}

如有任何帮助,我们将不胜感激。

java android android-camera-intent
1个回答
0
投票

在这个onActivityResult方法中可以通过查看结果码来判断是否捕获成功

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == CAPTURE_IMAGE_REQUEST_ID) {
    if (resultCode == RESULT_OK) {
        // Image captured successfully
        // You can now check if the image file exists at the specified path
        File imageFile = new File(path);
        if (imageFile.exists()) {
            // Image file exists
            // You can proceed with further actions
        } else {
            // Image file doesn't exist
            // Handle this case as needed
        }
    } else if (resultCode == RESULT_CANCELED) {
        // User canceled the capture
        // Handle this case if needed
    } else {
        // Capture failed or was not successful
        // Handle this case if needed
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.