【发布时间】:2018-02-06 01:40:14
【问题描述】:
我使用 Storage Access Framework 为我的应用程序设置了一个首选项以选择保存文件夹。获取 uri onActivityResult 后,我将其作为字符串保存到 SharedPreferences,并在需要保存时保存图像。
我正在使用这个方法成功保存图片。
public void saveImageWithDocumentFile(String uriString, String mimeType, String name) {
isImageSaved = false;
try {
Uri uri = Uri.parse(uriString);
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri);
DocumentFile file = pickedDir.createFile(mimeType, name);
OutputStream out = getContentResolver().openOutputStream(file.getUri());
isImageSaved = mBitmap.compress(CompressFormat.JPEG, 100, out);
out.close();
} catch (IOException e) {
throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
}
Toast.makeText(MainActivity.this, "Image saved " + isImageSaved, Toast.LENGTH_SHORT).show();
}
如果用户删除使用 SAF 选择的文件夹,iget null DocumentFile file 和应用程序崩溃。我的第一个问题是如何在不再次打开 SAF ui 的情况下检查文件夹是否存在。
我也想用 ParcelFileDescriptor 用这个方法保存同一张图片
public void saveImageWithParcelFileDescriptor(String folder, String name) {
if (mBitmap == null) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
return;
}
String image = folder + File.separator + name + ".jpg";
Toast.makeText(MainActivity.this, "image " + image, Toast.LENGTH_LONG).show();
Uri uri = Uri.parse(image);
ParcelFileDescriptor pfd = null;
FileOutputStream fileOutputStream = null;
try {
pfd = getContentResolver().openFileDescriptor(uri, "w");
fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
mBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pfd != null) {
try {
pfd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Image saved " + isImageSaved, Toast.LENGTH_SHORT).show();
}
我得到java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/612E-B7BF%3Aname/imagePFD.jpg
在线pfd = getContentResolver().openFileDescriptor(uri, "w");
这就是我调用此方法的方式,currentFolder 是我在第一种方法中使用意图和相同文件夹获得的文件夹。
saveImageWithParcelFileDescriptor(currentFolder, "imagePFD");
我该如何解决这个问题,哪种方法更可取,为什么?
【问题讨论】:
标签: android storage-access-framework