Java File.createTempFile抛出权限被拒绝
我想用jpg格式制作保存图像的文件Java File.createTempFile抛出权限被拒绝,java,android,android-studio,Java,Android,Android Studio,我想用jpg格式制作保存图像的文件 public static File createImageFile() throws IOException { final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); final String imageFileName = "IM
public static File createImageFile() throws IOException {
final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
final String imageFileName = "IMG_" + timestamp;
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
storageDir.mkdirs();
return File.createTempFile(imageFileName, ".jpg", storageDir);
}
上面是我创建文件的函数,位于名为FileHelper的类中,这是我使用该函数时的示例代码
if (filePath == null) {
File photoFile = null;
try {
photoFile = FileHelper.createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
filePath = photoFile.getAbsolutePath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
try {
bmp = getBitmap(filePath);
} catch (Exception e) {
e.printStackTrace();
bmp = BitmapHelper.reduceResolution(filePath, widthPixels, heightPixels);
}
}
它在某些设备中工作,在某些设备中也会抛出错误,错误为:
W/System.err: java.io.IOException: Permission denied
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
at java.io.File.createTempFile(File.java:2018)
at com.mogawe.mosurvei.util.FileHelper.createImageFile(FileHelper.java:671)
有人知道如何解决此问题吗?我找到了解决我自己问题的方法>\u我找到了解决我自己问题的方法>\u您是否获得了存储权限?您的目标版本是什么?您运行此应用的设备API是什么?(因为在Oreo中,我可以使用sme代码获取文件路径)@NaitikSoni我的targetSdkVersion是29,minSdkVersion是2923@JyotishBiswas我已经完成了。您是否获得了存储权限?您的TargetSDK版本是什么?您在哪个设备API中运行此应用程序?(因为在Oreo中,我可以使用sme代码获取文件路径)@NaitikSoni我的targetSdkVersion是29,minSdkVersion是2923@JyotishBiswas我已经做到了
<manifest ... >
<!-- This attribute is "false" by default on apps targeting
Android 10 or higher. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>