建立檔案 Uri 後,除錯器顯示 uriString = "NOT CACHED",實際檔案操作可能失敗。
Uri.fromFile(file) 回傳的 Uri 物件內部 uriString 欄位為延遲計算,除錯器未觸發 toString() 導致顯示「NOT CACHED」,**實際 Uri 正常**。
// 1. 僅在需要時建立 Uri,避免過早持有
File photoFile = createImageFile(); // 你的建檔邏輯
Uri photoUri = Uri.fromFile(photoFile);
// 2. 直接用於 Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, REQUEST_CODE);
// 3. 若需在 onActivityResult 再用,重新建立或傳遞路徑字串
String photoPath = photoFile.getAbsolutePath();
// 傳遞 photoPath 而非 Uri 物件,避免序列化問題
file:// Uri 跨應用傳遞,會拋出 FileUriExposedException。請改用 FileProvider 產生 content:// Uri。FileProvider 範例:// 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>
<paths>
<files-path name="my_images" path="images/"/>
</paths>
-- 程式碼 --
File photoFile = new File(getFilesDir(), "images/photo.jpg");
Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);