【发布时间】:2021-10-02 22:39:44
【问题描述】:
我在 Pictures 文件夹中创建了 MyAppImages 文件夹。我想在这个文件夹中保存一张新图片。
当我通过ContentResolver插入MediaStore.Image.Media.EXTERNAL_CONTENT_URI时,我可以将图片直接保存到图片文件夹中。
当我使用 FileProvider 通过 uri 添加自己的文件夹时,我收到 java.lang.UnsupportedOperationException: No external inserts 错误。
当我用Uri.fromFile(myDirFile) 添加我自己的文件夹时,我得到了
java.lang.IllegalArgumentException: Unknown URL file:///storage/emulated/0/Android/data/com.my.app/files/Pictures/MyApp%20Image 错误。但是,当我调用myDirFile.exists() 时,它返回true。
我的代码:
private void saveByteToFile(byte[] byteArray, String contentType, long seconds){
File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//getOrCreate MyApp Images directory
File myDirFile = new File(attachmentDir.getAbsolutePath(), "MyApp Images");
//first error I mentioned
//Uri myDirUri = FileProviderUtil.getUriFor(MyApplication.getContext(), myDirFile);
//second error I mentioned
Uri myDirUri = Uri.fromFile(myDirFile);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!myDirFile.exists())
Files.createDirectory(Paths.get(myDirFile.getAbsolutePath()));
} else {
myDirFile.mkdirs();
}
Logger.i(myDirFile.exists() + " myDirUri: " + myDirUri); //exists return true
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, contentType);
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, seconds);
contentValues.put(MediaStore.MediaColumns.DATE_MODIFIED, seconds);
contentValues.put(MediaStore.Images.Media.DATA, myDirFile.getAbsolutePath());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
}
ContentResolver resolver = getContext().getContentResolver();
try {
Uri outputUri = resolver.insert(myDirUri, contentValues); //->the errors I mentioned here are returning
if (outputUri == null)
throw new IOException("Failed to create new MediaStore record.");
try (final OutputStream stream = resolver.openOutputStream(outputUri)) {
if (stream == null)
throw new IOException("Failed to open output stream.");
stream.write(byteArray);
} finally {
if (Build.VERSION.SDK_INT > 28) {
ContentValues updateValues = new ContentValues();
updateValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
resolver.update(outputUri, updateValues, null, null);
}
}
return outputUri;
} catch (IOException e) {
Logger.exception(e);
throw e;
}
}
【问题讨论】:
标签: android file fileoutputstream android-10.0 android-contentresolver