You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android拍照图片已保存却触发File Not Found Exception问题求助

Troubleshooting Camera Capture Issues in Your Android App

Hey there! Let's tackle that camera capture problem you're facing—glad to hear the gallery upload is working smoothly, that narrows things down a bit. Since you based your image creation logic on the Android docs, let's walk through the most common pitfalls that cause camera failures even when the code looks close to the example.

Common Issues & Fixes

1. Scoped Storage & Permission Misconfiguration

Android 10 (API 29) introduced Scoped Storage, which restricts direct access to public external storage directories. If your createImageFile() uses Environment.getExternalStoragePublicDirectory(), this will fail on newer Android versions.

Fix: Use app-specific storage instead, which doesn't require extra permissions (for Android 10+):

private File createImageFile() throws IOException {
    // Use app-specific Pictures directory
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    
    // Ensure the directory exists (critical—createTempFile will fail otherwise)
    if (!storageDir.exists()) {
        storageDir.mkdirs();
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    
    // Create temp file in the app-specific directory
    return File.createTempFile(
        imageFileName,  /* Prefix */
        ".jpg",         /* Suffix */
        storageDir      /* Directory */
    );
}

For Android 9 and below, you'll still need the WRITE_EXTERNAL_STORAGE permission in your manifest, but you can add a maxSdkVersion to avoid requesting it unnecessarily:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />

2. Incorrect FileProvider Setup

When launching the camera intent, you need to pass a Uri that the camera app has permission to write to. Using FileProvider is the correct way to do this (avoid Uri.fromFile()—it throws FileUriExposedException on Android 7+).

Step 1: Register FileProvider in AndroidManifest.xml

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Step 2: Create res/xml/file_paths.xml
This tells FileProvider which directories it can expose:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="camera_images" path="Pictures" />
</paths>

Step 3: Generate the Uri for the Camera Intent

File imageFile = createImageFile();
Uri photoUri = FileProvider.getUriForFile(
    this,
    getPackageName() + ".fileprovider", // Match the authority in your manifest
    imageFile
);

// Grant write permission to the camera app
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);

3. Unhandled File Creation Failures

Even small oversights here can break the flow:

  • Always check if the storage directory exists before creating the file (we added mkdirs() in the first fix).
  • Avoid special characters in the filename—using timestamps + UUIDs (or the default createTempFile logic) is safe.
  • Catch IOException properly and handle it (e.g., show an error toast to the user instead of crashing).

4. Faulty Result Handling

After capturing the photo, make sure you're validating the result before trying to use the image:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        // Only proceed if the capture was successful
        File imageFile = getImageFileFromYourStoredPath(); // Retrieve the file you created earlier
        if (imageFile.exists() && imageFile.canRead()) {
            // Pass the file to your image recognition API
        } else {
            // Handle case where the camera didn't write the file
            Toast.makeText(this, "Failed to save photo", Toast.LENGTH_SHORT).show();
        }
    }
}

If you're using Jetpack's registerForActivityResult instead of onActivityResult, apply the same validation logic there.

5. Image File Access for the API

When passing the image to your recognition API, ensure you're reading the file correctly:

  • Use FileInputStream to read the bytes, or get the absolute path of the file (since it's in your app's private storage, you have full access).
  • Avoid trying to use content URIs unless your API specifically supports them—stick to the file path for simplicity.

If you can share the full createImageFile() code and specify exactly what "serious problem" you're seeing (e.g., app crash, photo not saving, API can't read the file, blank image), I can help you zero in on the exact issue!

内容的提问来源于stack exchange,提问作者Devildude4427

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:28:31