Android无法在SD卡上写入和删除操作 [英] Android couldn't able to write and delete operation on sd card

查看:95
本文介绍了Android无法在SD卡上写入和删除操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在使用ImageCompressor应用程序.

我需要删除 write (更新)图像文件.在内部存储中,效果很好,但** SD卡无法让我访问删除和写入"文件.

我的应用程序如何在SD卡上进行写入删除操作(可移动存储)?

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

更新:

我已经在研究&讨论这个问题.并且了解我必须使用存储访问框架但我对SAF还是陌生的.

我使用了来压缩需要文件而不是Uri 的照片.为此,我做了 Uri->文件,然后使用 Intent.ACTION_OPEN_DOCUMENT 并从可移动存储中选择图像.

但是对于可移动存储,我无法从uri中找到Image Real Path.

我不知道这是正确的方法.如果在SAF中有可以使用uri压缩图像的任何方式,请告诉我.或如何从可移动存储照片的uri获取图像的真实路径.

更新代码SAF:

 //-----------意向-------------意图意图=新意图(Intent.ACTION_OPEN_DOCUMENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("*/*");//------------关于活动结果--------------Uri uri = data.getData();尝试 {ParcelFileDescriptor fileDescriptor = getContentResolver().openFileDescriptor(uri,"w");FileOutputStream fos = new FileOutputStream(fileDescriptor.getFileDescriptor());FileInputStream fis =新的FileInputStream(getImageFilePath(uri));FileChannel源= fis.getChannel();FileChannel目标= fos.getChannel();destination.transferFrom(source,0,source.size());fis.close();fos.close();fileDescriptor.close();Toast.makeText(this,文件成功保存.",Toast.LENGTH_SHORT).show();} 

从Uri到文件路径,我从媒体应用(例如Gallary,Photos)中选择图像,但是从sd卡中选择了什么而不是 MediaStore.Images.Media.DATA 我不知道.代码:

 私有文件getImageFilePath(Uri uri)引发IOException {字符串image_id = null,imagePath = null;游标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 +"=?",新的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);返回新的Compressor(this).setQuality(50).compressToFile(file);} 

解决方案

我挖了一个我的旧Android应用程序,并找到了它:

此方法将sdcard uri的根转换为 File 路径.

 公共文件getRootPath(上下文上下文,Uri sdcardRootUri){List< String>pathSegments = sdcardRootUri.getPathSegments();String []令牌= pathSegments.get(pathSegments.size()-1).split(:");对于(文件f:ContextCompat.getExternalFilesDirs(context,null)){字符串路径= f.getAbsolutePath().substring(0,f.getAbsolutePath().indexOf("/Android/"));如果(path.contains(tokens [0])){返回新的文件(路径);}}返回null;} 

然后为了检索sdcard根的uri,我使用了它:

  Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);startActivityForResult(intent,SDCARD_ROOT_CODE); 

然后用户将选择sdcard的根,然后,我像这样处理结果:

 受保护的void onActivityResult(int requestCode,int resultCode,Intent data){如果(resultCode == RESULT_OK& requestCode == SDCARD_ROOT_CODE){//坚持访问权限Uri sdcdardRootUri = data.getData();grantUriPermission(getPackageName(),sdcdardRootUri,Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);final int takeFlags = data.getFlags()&(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);getContentResolver().takePersistableUriPermission(sdcdardRootUri,takeFlags);//使用sdcdardRootUri做任何你想做的事}} 

我希望这就是您要寻找的.有了它,您可以读取/写入/删除sdcard上想要的任何文件.

I am working now on ImageCompressor app.

I need to delete and write (update) image file. In Internal storage works perfectly but **SD Card can't give me access to Delete and Write files.

How can my app able to do write and delete operation on sd card (removable storage)?

I've already done whole project without this, so I have to must find a way.

Update:

I am already research & discuss about this issue. And understood I have to use storage access framework But I'm new on SAF.

I used a library to compress photo that need File not Uri. For that I do Uri -> File and use Intent.ACTION_OPEN_DOCUMENT and pick image from Removable storage.

But for removable storage I can't find Image Real Path from uri.

I don't know it's the right way or not. If there have any way in SAF where I can Compress my Image using uri, let me know. Or How to get Image real path from uri of Removable Storage Photo.

Update code 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 to File Path, I done where pick image from media apps(like Gallary, Photos) But pick from sd card what will instead of MediaStore.Images.Media.DATA I don't know. Code:

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);
}

解决方案

I digged into an old Android app of mine and retrieved this :

This method convert the root of the sdcard uri, to a File path.

public File getRootPath(Context context, Uri sdcardRootUri)
{
    List<String> pathSegments =  sdcardRootUri.getPathSegments();
    String[] tokens = pathSegments.get(pathSegments.size()-1).split(":");
    for (File f : ContextCompat.getExternalFilesDirs(context, null))
    {
        String path = f.getAbsolutePath().substring(0, f.getAbsolutePath().indexOf("/Android/"));
        if (path.contains(tokens[0]))
        {
            return new File(path);
        }
    }
    return null;
}

And in order to retrieved the uri of the sdcard root, I used that :

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, SDCARD_ROOT_CODE);

Then the user would choose the root of the sdcard and then, I handled the result like this :

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (resultCode == RESULT_OK && requestCode == SDCARD_ROOT_CODE)
    {
        // Persist access permissions
        Uri sdcdardRootUri = data.getData();
        grantUriPermission(getPackageName(), sdcdardRootUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getContentResolver().takePersistableUriPermission(sdcdardRootUri, takeFlags);

        // Do whatever you want with sdcdardRootUri
    }
}

I hope it's what you are looking for. With that you can read/write/delete any file you want on the sdcard.

这篇关于Android无法在SD卡上写入和删除操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆