【发布时间】:2020-01-04 17:12:44
【问题描述】:
首先,我已经检查了this similar question,但它似乎不适用于我的代码。所以在这里,我的问题是每当我尝试打开相机拍照并存储它时,我的应用程序就会崩溃。这是我正在使用的代码:
@RequiresApi(api = Build.VERSION_CODES.M)
private void dispatchTakePictureIntent() throws IOException {
Log.i("Debug","dispatchTakePictureIntent entered");
checkCameraPermissions();
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Makes sure there's an activity that handles the intent
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
File image = null;
try{
image = createImageFile();
} catch (IOException ex) {
Log.i("Debug", "IOException: " + ex);
}
// Continues if the file is created correctly
if(image != null){
Uri imageUri = Uri.fromFile(image); // <-- Here's the error
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
Log.i("Debug", "Photo succesfully saved " + takePictureIntent);
}
}
}
还有,我的方法 createImageFile:
private File createImageFile() throws IOException {
File imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File newFile = new File(imageRoot, imageFileName + ".jpg");
if(!imageRoot.exists())
if (!imageRoot.mkdirs())
return null;
mCurrentPhotoPath = newFile.getAbsolutePath();
return newFile;
}
当我按下应用内的相机按钮时出现的错误:
FATAL EXCEPTION: main
Process: com.odoo.quipons, PID: 13976
android.os.FileUriExposedException: file:///data/user/0/com.odoo.myApp/files/Android/data/myApp/files/Pictures/JPEG_20171122_111843_.jpg exposed beyond app through ClipData.Item.getUri()
【问题讨论】:
-
你有一个 FileUriExposedException。您引用的链接应该足以解决您的问题。那么问题出在哪里?
-
Log.i("Debug", "Photo succesfully saved " + takePictureIntent);。那是错误的地方。您只需在那里启动相机应用程序。照片还没拍。尚未保存任何内容。 -
if(!imageRoot.exists()) imageRoot.mkdirs();。图像根?未知变量!此外,您应该检查 mkdirs 的返回值,如果失败则不要继续。请调整您的代码。 -
getContext().getFilesDir(), "Android/data/MyApp/files/Pictures");为什么要在您的私人内存中创建所有这些子目录?在我看来,您对 getExternalFilesDir() 感到困惑。 -
// Continues if the file is created correctly。您还没有尝试创建文件。没关系。您只在 File 对象中构造了一个文件名。
标签: android