【发布时间】:2019-01-29 14:03:49
【问题描述】:
我现在正在开发 ImageCompressor 应用程序。
我需要delete 和write(更新)图像文件。在内部存储中完美运行,但 **SD 卡无法让我访问删除和写入文件。
我的应用如何在 sd 卡上进行write 和delete 操作(可移动存储)?
没有这个我已经完成了整个项目,所以我必须想办法。
更新:
我已经在研究和讨论这个问题。并且明白我必须使用storage access framework 但我是 SAF 的新手。
我使用库来压缩需要File not Uri的照片。为此,我使用Uri -> File 并使用Intent.ACTION_OPEN_DOCUMENT 并从可移动存储中选择图像。
但对于可移动存储,我无法从 uri 中找到 Image Real Path。
我不知道这是否正确。如果有任何方法在 SAF 中我可以使用 uri 压缩图像,请告诉我。或者如何从Removable Storage Photo的uri获取图片真实路径。
更新代码 SAF:
// ----------- Intent -------------
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
// ------------ On Activity Result --------------
Uri uri = data.getData();
try {
ParcelFileDescriptor fileDescriptor = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fos = new FileOutputStream(fileDescriptor.getFileDescriptor());
FileInputStream fis = new FileInputStream(getImageFilePath(uri));
FileChannel source = fis.getChannel();
FileChannel destination = fos.getChannel();
destination.transferFrom(source, 0, source.size());
fis.close();
fos.close();
fileDescriptor.close();
Toast.makeText(this, "File save successfully.", Toast.LENGTH_SHORT).show();
}
Uri 到文件路径,我完成了从媒体应用程序(如图库、照片)中选择图像的位置,但是从 sd 卡中选择什么而不是 MediaStore.Images.Media.DATA 我不知道。代码:
private File getImageFilePath(Uri uri) throws IOException {
String image_id = null, imagePath = null;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
image_id = cursor.getString(0);
image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
cursor.close();
}
cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
}
File file = new File(imagePath);
return new Compressor(this).setQuality(50).compressToFile(file);
}
【问题讨论】:
-
您是否尝试过搜索? stackoverflow.com/questions/2121833/…
-
@MikeM。是的,我说的是可移动存储。
-
@BackSlash 问题和答案已经很老了。并且在 5.0 Lolipop android 之后更改了他们的 sd 卡访问策略。
-
@B001ᛦ 是的,我提供了正确的许可,这就是为什么在手机内存中所有东西都能完美运行的原因。但是 SD 卡有问题。
标签: java android permissions file-permissions storage-access-framework