Android无法对sd卡进行写入和删除操作

2024-03-04

我现在正在开发 ImageCompressor 应用程序。

我需要delete and write(更新)图像文件。在内部存储中工作正常,但 **SD​​ 卡无法让我访问删除和写入文件。

我的应用程序如何能够做到write and delete对sd卡的操作(移动存储)?

我已经在没有这个的情况下完成了整个项目,所以我必须找到一种方法。

Update:

我已经在研究和讨论这个问题了。并明白我必须使用storage access framework但我是 SAF 的新手。

我用了一个library压缩需要的照片文件不是 Uri。为此我做Uri -> File并使用Intent.ACTION_OPEN_DOCUMENT并从可移动存储中选取图像。

但对于可移动存储,我无法从 uri 找到图像真实路径。

我不知道这是正确的方法还是错误的方法。如果有什么办法在 SAF 中我可以使用 uri 压缩我的图像, 让我知道。或者如何从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);
}

如果您使用 File 和 FileOutputStream 类,则可移动 SD 卡只能在现代 Android 设备上写入。

如果你幸运的话你的设备使用getExternalFilesDirs()返回卡上您仍然可以写入的应用程序特定目录作为第二项。

对于其余部分,请使用存储访问框架 https://developer.android.com/guide/topics/providers/document-provider.

首先让用户选择 SD 卡Intent.ACTION_OPEN_DOCUMENT_TREE或一个文件Intent.ACTION_OPEN_DOCUMENT.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android无法对sd卡进行写入和删除操作 的相关文章

随机推荐